PageRenderTime 114ms CodeModel.GetById 17ms RepoModel.GetById 4ms app.codeStats 1ms

/j/kfm/includes/pear/MDB2.php

http://kv-webme.googlecode.com/
PHP | 4213 lines | 1819 code | 364 blank | 2030 comment | 298 complexity | 06a8b49acaf098294725b4810de586cd MD5 | raw file
Possible License(s): LGPL-3.0, GPL-2.0, BSD-3-Clause, BSD-2-Clause, Apache-2.0, MIT, LGPL-2.1
  1. <?php
  2. // vim: set et ts=4 sw=4 fdm=marker:
  3. // +----------------------------------------------------------------------+
  4. // | PHP versions 4 and 5 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox, |
  7. // | Stig. S. Bakken, Lukas Smith |
  8. // | All rights reserved. |
  9. // +----------------------------------------------------------------------+
  10. // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
  11. // | API as well as database abstraction for PHP applications. |
  12. // | This LICENSE is in the BSD license style. |
  13. // | |
  14. // | Redistribution and use in source and binary forms, with or without |
  15. // | modification, are permitted provided that the following conditions |
  16. // | are met: |
  17. // | |
  18. // | Redistributions of source code must retain the above copyright |
  19. // | notice, this list of conditions and the following disclaimer. |
  20. // | |
  21. // | Redistributions in binary form must reproduce the above copyright |
  22. // | notice, this list of conditions and the following disclaimer in the |
  23. // | documentation and/or other materials provided with the distribution. |
  24. // | |
  25. // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
  26. // | Lukas Smith nor the names of his contributors may be used to endorse |
  27. // | or promote products derived from this software without specific prior|
  28. // | written permission. |
  29. // | |
  30. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
  31. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
  32. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
  33. // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
  34. // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
  35. // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
  36. // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
  37. // | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
  38. // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
  39. // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
  40. // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
  41. // | POSSIBILITY OF SUCH DAMAGE. |
  42. // +----------------------------------------------------------------------+
  43. // | Author: Lukas Smith <smith@pooteeweet.org> |
  44. // +----------------------------------------------------------------------+
  45. //
  46. // $Id: MDB2.php,v 1.292 2007/04/25 09:31:01 quipo Exp $
  47. //
  48. /**
  49. * @package MDB2
  50. * @category Database
  51. * @author Lukas Smith <smith@pooteeweet.org>
  52. */
  53. require_once 'PEAR.php';
  54. // {{{ Error constants
  55. /**
  56. * The method mapErrorCode in each MDB2_dbtype implementation maps
  57. * native error codes to one of these.
  58. *
  59. * If you add an error code here, make sure you also add a textual
  60. * version of it in MDB2::errorMessage().
  61. */
  62. define('MDB2_OK', true);
  63. define('MDB2_ERROR', -1);
  64. define('MDB2_ERROR_SYNTAX', -2);
  65. define('MDB2_ERROR_CONSTRAINT', -3);
  66. define('MDB2_ERROR_NOT_FOUND', -4);
  67. define('MDB2_ERROR_ALREADY_EXISTS', -5);
  68. define('MDB2_ERROR_UNSUPPORTED', -6);
  69. define('MDB2_ERROR_MISMATCH', -7);
  70. define('MDB2_ERROR_INVALID', -8);
  71. define('MDB2_ERROR_NOT_CAPABLE', -9);
  72. define('MDB2_ERROR_TRUNCATED', -10);
  73. define('MDB2_ERROR_INVALID_NUMBER', -11);
  74. define('MDB2_ERROR_INVALID_DATE', -12);
  75. define('MDB2_ERROR_DIVZERO', -13);
  76. define('MDB2_ERROR_NODBSELECTED', -14);
  77. define('MDB2_ERROR_CANNOT_CREATE', -15);
  78. define('MDB2_ERROR_CANNOT_DELETE', -16);
  79. define('MDB2_ERROR_CANNOT_DROP', -17);
  80. define('MDB2_ERROR_NOSUCHTABLE', -18);
  81. define('MDB2_ERROR_NOSUCHFIELD', -19);
  82. define('MDB2_ERROR_NEED_MORE_DATA', -20);
  83. define('MDB2_ERROR_NOT_LOCKED', -21);
  84. define('MDB2_ERROR_VALUE_COUNT_ON_ROW', -22);
  85. define('MDB2_ERROR_INVALID_DSN', -23);
  86. define('MDB2_ERROR_CONNECT_FAILED', -24);
  87. define('MDB2_ERROR_EXTENSION_NOT_FOUND',-25);
  88. define('MDB2_ERROR_NOSUCHDB', -26);
  89. define('MDB2_ERROR_ACCESS_VIOLATION', -27);
  90. define('MDB2_ERROR_CANNOT_REPLACE', -28);
  91. define('MDB2_ERROR_CONSTRAINT_NOT_NULL',-29);
  92. define('MDB2_ERROR_DEADLOCK', -30);
  93. define('MDB2_ERROR_CANNOT_ALTER', -31);
  94. define('MDB2_ERROR_MANAGER', -32);
  95. define('MDB2_ERROR_MANAGER_PARSE', -33);
  96. define('MDB2_ERROR_LOADMODULE', -34);
  97. define('MDB2_ERROR_INSUFFICIENT_DATA', -35);
  98. // }}}
  99. // {{{ Verbose constants
  100. /**
  101. * These are just helper constants to more verbosely express parameters to prepare()
  102. */
  103. define('MDB2_PREPARE_MANIP', false);
  104. define('MDB2_PREPARE_RESULT', null);
  105. // }}}
  106. // {{{ Fetchmode constants
  107. /**
  108. * This is a special constant that tells MDB2 the user hasn't specified
  109. * any particular get mode, so the default should be used.
  110. */
  111. define('MDB2_FETCHMODE_DEFAULT', 0);
  112. /**
  113. * Column data indexed by numbers, ordered from 0 and up
  114. */
  115. define('MDB2_FETCHMODE_ORDERED', 1);
  116. /**
  117. * Column data indexed by column names
  118. */
  119. define('MDB2_FETCHMODE_ASSOC', 2);
  120. /**
  121. * Column data as object properties
  122. */
  123. define('MDB2_FETCHMODE_OBJECT', 3);
  124. /**
  125. * For multi-dimensional results: normally the first level of arrays
  126. * is the row number, and the second level indexed by column number or name.
  127. * MDB2_FETCHMODE_FLIPPED switches this order, so the first level of arrays
  128. * is the column name, and the second level the row number.
  129. */
  130. define('MDB2_FETCHMODE_FLIPPED', 4);
  131. // }}}
  132. // {{{ Portability mode constants
  133. /**
  134. * Portability: turn off all portability features.
  135. * @see MDB2_Driver_Common::setOption()
  136. */
  137. define('MDB2_PORTABILITY_NONE', 0);
  138. /**
  139. * Portability: convert names of tables and fields to case defined in the
  140. * "field_case" option when using the query*(), fetch*() and tableInfo() methods.
  141. * @see MDB2_Driver_Common::setOption()
  142. */
  143. define('MDB2_PORTABILITY_FIX_CASE', 1);
  144. /**
  145. * Portability: right trim the data output by query*() and fetch*().
  146. * @see MDB2_Driver_Common::setOption()
  147. */
  148. define('MDB2_PORTABILITY_RTRIM', 2);
  149. /**
  150. * Portability: force reporting the number of rows deleted.
  151. * @see MDB2_Driver_Common::setOption()
  152. */
  153. define('MDB2_PORTABILITY_DELETE_COUNT', 4);
  154. /**
  155. * Portability: not needed in MDB2 (just left here for compatibility to DB)
  156. * @see MDB2_Driver_Common::setOption()
  157. */
  158. define('MDB2_PORTABILITY_NUMROWS', 8);
  159. /**
  160. * Portability: makes certain error messages in certain drivers compatible
  161. * with those from other DBMS's.
  162. *
  163. * + mysql, mysqli: change unique/primary key constraints
  164. * MDB2_ERROR_ALREADY_EXISTS -> MDB2_ERROR_CONSTRAINT
  165. *
  166. * + odbc(access): MS's ODBC driver reports 'no such field' as code
  167. * 07001, which means 'too few parameters.' When this option is on
  168. * that code gets mapped to MDB2_ERROR_NOSUCHFIELD.
  169. *
  170. * @see MDB2_Driver_Common::setOption()
  171. */
  172. define('MDB2_PORTABILITY_ERRORS', 16);
  173. /**
  174. * Portability: convert empty values to null strings in data output by
  175. * query*() and fetch*().
  176. * @see MDB2_Driver_Common::setOption()
  177. */
  178. define('MDB2_PORTABILITY_EMPTY_TO_NULL', 32);
  179. /**
  180. * Portability: removes database/table qualifiers from associative indexes
  181. * @see MDB2_Driver_Common::setOption()
  182. */
  183. define('MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES', 64);
  184. /**
  185. * Portability: turn on all portability features.
  186. * @see MDB2_Driver_Common::setOption()
  187. */
  188. define('MDB2_PORTABILITY_ALL', 127);
  189. // }}}
  190. // {{{ Globals for class instance tracking
  191. /**
  192. * These are global variables that are used to track the various class instances
  193. */
  194. $GLOBALS['_MDB2_databases'] = array();
  195. $GLOBALS['_MDB2_dsninfo_default'] = array(
  196. 'phptype' => false,
  197. 'dbsyntax' => false,
  198. 'username' => false,
  199. 'password' => false,
  200. 'protocol' => false,
  201. 'hostspec' => false,
  202. 'port' => false,
  203. 'socket' => false,
  204. 'database' => false,
  205. 'mode' => false,
  206. );
  207. // }}}
  208. // {{{ class MDB2
  209. /**
  210. * The main 'MDB2' class is simply a container class with some static
  211. * methods for creating DB objects as well as some utility functions
  212. * common to all parts of DB.
  213. *
  214. * The object model of MDB2 is as follows (indentation means inheritance):
  215. *
  216. * MDB2 The main MDB2 class. This is simply a utility class
  217. * with some 'static' methods for creating MDB2 objects as
  218. * well as common utility functions for other MDB2 classes.
  219. *
  220. * MDB2_Driver_Common The base for each MDB2 implementation. Provides default
  221. * | implementations (in OO lingo virtual methods) for
  222. * | the actual DB implementations as well as a bunch of
  223. * | query utility functions.
  224. * |
  225. * +-MDB2_Driver_mysql The MDB2 implementation for MySQL. Inherits MDB2_Driver_Common.
  226. * When calling MDB2::factory or MDB2::connect for MySQL
  227. * connections, the object returned is an instance of this
  228. * class.
  229. * +-MDB2_Driver_pgsql The MDB2 implementation for PostGreSQL. Inherits MDB2_Driver_Common.
  230. * When calling MDB2::factory or MDB2::connect for PostGreSQL
  231. * connections, the object returned is an instance of this
  232. * class.
  233. *
  234. * @package MDB2
  235. * @category Database
  236. * @author Lukas Smith <smith@pooteeweet.org>
  237. */
  238. class MDB2
  239. {
  240. // {{{ function setOptions(&$db, $options)
  241. /**
  242. * set option array in an exiting database object
  243. *
  244. * @param MDB2_Driver_Common MDB2 object
  245. * @param array An associative array of option names and their values.
  246. *
  247. * @return mixed MDB2_OK or a PEAR Error object
  248. *
  249. * @access public
  250. */
  251. static function setOptions(&$db, $options)
  252. {
  253. if (is_array($options)) {
  254. foreach ($options as $option => $value) {
  255. $test = $db->setOption($option, $value);
  256. if (PEAR::isError($test)) {
  257. return $test;
  258. }
  259. }
  260. }
  261. return MDB2_OK;
  262. }
  263. // }}}
  264. // {{{ function classExists($classname)
  265. /**
  266. * Checks if a class exists without triggering __autoload
  267. *
  268. * @param string classname
  269. *
  270. * @return bool true success and false on error
  271. * @static
  272. * @access public
  273. */
  274. static function classExists($classname)
  275. {
  276. if (version_compare(phpversion(), "5.0", ">=")) {
  277. return class_exists($classname, false);
  278. }
  279. return class_exists($classname);
  280. }
  281. // }}}
  282. // {{{ function loadClass($class_name, $debug)
  283. /**
  284. * Loads a PEAR class.
  285. *
  286. * @param string classname to load
  287. * @param bool if errors should be suppressed
  288. *
  289. * @return mixed true success or PEAR_Error on failure
  290. *
  291. * @access public
  292. */
  293. static function loadClass($class_name, $debug)
  294. {
  295. if (!MDB2::classExists($class_name)) {
  296. $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
  297. $include = include_once($file_name);
  298. if (!$include) {
  299. if (!MDB2::fileExists($file_name)) {
  300. $msg = "unable to find package '$class_name' file '$file_name'";
  301. } else {
  302. $msg = "unable to load class '$class_name' from file '$file_name'";
  303. }
  304. $err =& MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null, $msg);
  305. return $err;
  306. }
  307. }
  308. return MDB2_OK;
  309. }
  310. // }}}
  311. // {{{ function &factory($dsn, $options = false)
  312. /**
  313. * Create a new MDB2 object for the specified database type
  314. *
  315. * IMPORTANT: In order for MDB2 to work properly it is necessary that
  316. * you make sure that you work with a reference of the original
  317. * object instead of a copy (this is a PHP4 quirk).
  318. *
  319. * For example:
  320. * $db =& MDB2::factory($dsn);
  321. * ^^
  322. * And not:
  323. * $db = MDB2::factory($dsn);
  324. *
  325. * @param mixed 'data source name', see the MDB2::parseDSN
  326. * method for a description of the dsn format.
  327. * Can also be specified as an array of the
  328. * format returned by MDB2::parseDSN.
  329. * @param array An associative array of option names and
  330. * their values.
  331. *
  332. * @return mixed a newly created MDB2 object, or false on error
  333. *
  334. * @access public
  335. */
  336. static function &factory($dsn, $options = false)
  337. {
  338. $dsninfo = MDB2::parseDSN($dsn);
  339. if (empty($dsninfo['phptype'])) {
  340. $err =& MDB2::raiseError(MDB2_ERROR_NOT_FOUND,
  341. null, null, 'no RDBMS driver specified');
  342. return $err;
  343. }
  344. $class_name = 'MDB2_Driver_'.$dsninfo['phptype'];
  345. $debug = (!empty($options['debug']));
  346. $err = MDB2::loadClass($class_name, $debug);
  347. if (PEAR::isError($err)) {
  348. return $err;
  349. }
  350. $db =new $class_name();
  351. $db->setDSN($dsninfo);
  352. $err = MDB2::setOptions($db, $options);
  353. if (PEAR::isError($err)) {
  354. return $err;
  355. }
  356. return $db;
  357. }
  358. // }}}
  359. // {{{ function &connect($dsn, $options = false)
  360. /**
  361. * Create a new MDB2 connection object and connect to the specified
  362. * database
  363. *
  364. * IMPORTANT: In order for MDB2 to work properly it is necessary that
  365. * you make sure that you work with a reference of the original
  366. * object instead of a copy (this is a PHP4 quirk).
  367. *
  368. * For example:
  369. * $db =& MDB2::connect($dsn);
  370. * ^^
  371. * And not:
  372. * $db = MDB2::connect($dsn);
  373. * ^^
  374. *
  375. * @param mixed 'data source name', see the MDB2::parseDSN
  376. * method for a description of the dsn format.
  377. * Can also be specified as an array of the
  378. * format returned by MDB2::parseDSN.
  379. * @param array An associative array of option names and
  380. * their values.
  381. *
  382. * @return mixed a newly created MDB2 connection object, or a MDB2
  383. * error object on error
  384. *
  385. * @access public
  386. * @see MDB2::parseDSN
  387. */
  388. static function &connect($dsn, $options = false)
  389. {
  390. $db =& MDB2::factory($dsn, $options);
  391. if (PEAR::isError($db)) {
  392. return $db;
  393. }
  394. $err = $db->connect();
  395. if (PEAR::isError($err)) {
  396. $dsn = $db->getDSN('string', 'xxx');
  397. $db->disconnect();
  398. $err->addUserInfo($dsn);
  399. return $err;
  400. }
  401. return $db;
  402. }
  403. // }}}
  404. // {{{ function &singleton($dsn = null, $options = false)
  405. /**
  406. * Returns a MDB2 connection with the requested DSN.
  407. * A new MDB2 connection object is only created if no object with the
  408. * requested DSN exists yet.
  409. *
  410. * IMPORTANT: In order for MDB2 to work properly it is necessary that
  411. * you make sure that you work with a reference of the original
  412. * object instead of a copy (this is a PHP4 quirk).
  413. *
  414. * For example:
  415. * $db =& MDB2::singleton($dsn);
  416. * ^^
  417. * And not:
  418. * $db = MDB2::singleton($dsn);
  419. * ^^
  420. *
  421. * @param mixed 'data source name', see the MDB2::parseDSN
  422. * method for a description of the dsn format.
  423. * Can also be specified as an array of the
  424. * format returned by MDB2::parseDSN.
  425. * @param array An associative array of option names and
  426. * their values.
  427. *
  428. * @return mixed a newly created MDB2 connection object, or a MDB2
  429. * error object on error
  430. *
  431. * @access public
  432. * @see MDB2::parseDSN
  433. */
  434. function &singleton($dsn = null, $options = false)
  435. {
  436. if ($dsn) {
  437. $dsninfo = MDB2::parseDSN($dsn);
  438. $dsninfo = array_merge($GLOBALS['_MDB2_dsninfo_default'], $dsninfo);
  439. $keys = array_keys($GLOBALS['_MDB2_databases']);
  440. for ($i=0, $j=count($keys); $i<$j; ++$i) {
  441. if (isset($GLOBALS['_MDB2_databases'][$keys[$i]])) {
  442. $tmp_dsn = $GLOBALS['_MDB2_databases'][$keys[$i]]->getDSN('array');
  443. if (count(array_diff_assoc($tmp_dsn, $dsninfo)) == 0) {
  444. MDB2::setOptions($GLOBALS['_MDB2_databases'][$keys[$i]], $options);
  445. return $GLOBALS['_MDB2_databases'][$keys[$i]];
  446. }
  447. }
  448. }
  449. } elseif (is_array($GLOBALS['_MDB2_databases']) && reset($GLOBALS['_MDB2_databases'])) {
  450. $db =& $GLOBALS['_MDB2_databases'][key($GLOBALS['_MDB2_databases'])];
  451. return $db;
  452. }
  453. $db =& MDB2::factory($dsn, $options);
  454. return $db;
  455. }
  456. // }}}
  457. // {{{ function loadFile($file)
  458. /**
  459. * load a file (like 'Date')
  460. *
  461. * @param string name of the file in the MDB2 directory (without '.php')
  462. *
  463. * @return string name of the file that was included
  464. *
  465. * @access public
  466. */
  467. function loadFile($file)
  468. {
  469. $file_name = 'MDB2'.DIRECTORY_SEPARATOR.$file.'.php';
  470. if (!MDB2::fileExists($file_name)) {
  471. return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  472. 'unable to find: '.$file_name);
  473. }
  474. if (!include_once($file_name)) {
  475. return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  476. 'unable to load driver class: '.$file_name);
  477. }
  478. return $file_name;
  479. }
  480. // }}}
  481. // {{{ function apiVersion()
  482. /**
  483. * Return the MDB2 API version
  484. *
  485. * @return string the MDB2 API version number
  486. *
  487. * @access public
  488. */
  489. function apiVersion()
  490. {
  491. return '2.4.1';
  492. }
  493. // }}}
  494. // {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
  495. /**
  496. * This method is used to communicate an error and invoke error
  497. * callbacks etc. Basically a wrapper for PEAR::raiseError
  498. * without the message string.
  499. *
  500. * @param mixed int error code
  501. *
  502. * @param int error mode, see PEAR_Error docs
  503. *
  504. * @param mixed If error mode is PEAR_ERROR_TRIGGER, this is the
  505. * error level (E_USER_NOTICE etc). If error mode is
  506. * PEAR_ERROR_CALLBACK, this is the callback function,
  507. * either as a function name, or as an array of an
  508. * object and method name. For other error modes this
  509. * parameter is ignored.
  510. *
  511. * @param string Extra debug information. Defaults to the last
  512. * query and native error code.
  513. *
  514. * @return PEAR_Error instance of a PEAR Error object
  515. *
  516. * @access private
  517. * @see PEAR_Error
  518. */
  519. function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
  520. {
  521. $err =& PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
  522. return $err;
  523. }
  524. // }}}
  525. // {{{ function isError($data, $code = null)
  526. /**
  527. * Tell whether a value is a MDB2 error.
  528. *
  529. * @param mixed the value to test
  530. * @param int if is an error object, return true
  531. * only if $code is a string and
  532. * $db->getMessage() == $code or
  533. * $code is an integer and $db->getCode() == $code
  534. *
  535. * @return bool true if parameter is an error
  536. *
  537. * @access public
  538. */
  539. function isError($data, $code = null)
  540. {
  541. if ($data instanceof MDB2_Error) {
  542. if (is_null($code)) {
  543. return true;
  544. } elseif (is_string($code)) {
  545. return $data->getMessage() === $code;
  546. } else {
  547. $code = (array)$code;
  548. return in_array($data->getCode(), $code);
  549. }
  550. }
  551. return false;
  552. }
  553. // }}}
  554. // {{{ function isConnection($value)
  555. /**
  556. * Tell whether a value is a MDB2 connection
  557. *
  558. * @param mixed value to test
  559. *
  560. * @return bool whether $value is a MDB2 connection
  561. *
  562. * @access public
  563. */
  564. function isConnection($value)
  565. {
  566. return $value instanceof MDB2_Driver_Common;
  567. }
  568. // }}}
  569. // {{{ function isResult($value)
  570. /**
  571. * Tell whether a value is a MDB2 result
  572. *
  573. * @param mixed value to test
  574. *
  575. * @return bool whether $value is a MDB2 result
  576. *
  577. * @access public
  578. */
  579. function isResult($value)
  580. {
  581. return $value instanceof MDB2_Result;
  582. }
  583. // }}}
  584. // {{{ function isResultCommon($value)
  585. /**
  586. * Tell whether a value is a MDB2 result implementing the common interface
  587. *
  588. * @param mixed value to test
  589. *
  590. * @return bool whether $value is a MDB2 result implementing the common interface
  591. *
  592. * @access public
  593. */
  594. static function isResultCommon($value)
  595. {
  596. return $value instanceof MDB2_Result_Common;
  597. }
  598. // }}}
  599. // {{{ function isStatement($value)
  600. /**
  601. * Tell whether a value is a MDB2 statement interface
  602. *
  603. * @param mixed value to test
  604. *
  605. * @return bool whether $value is a MDB2 statement interface
  606. *
  607. * @access public
  608. */
  609. function isStatement($value)
  610. {
  611. return $value instanceof MDB2_Statement;
  612. }
  613. // }}}
  614. // {{{ function errorMessage($value = null)
  615. /**
  616. * Return a textual error message for a MDB2 error code
  617. *
  618. * @param int|array integer error code,
  619. null to get the current error code-message map,
  620. or an array with a new error code-message map
  621. *
  622. * @return string error message, or false if the error code was
  623. * not recognized
  624. *
  625. * @access public
  626. */
  627. function errorMessage($value = null)
  628. {
  629. static $errorMessages;
  630. if (is_array($value)) {
  631. $errorMessages = $value;
  632. return MDB2_OK;
  633. }
  634. if (!isset($errorMessages)) {
  635. $errorMessages = array(
  636. MDB2_OK => 'no error',
  637. MDB2_ERROR => 'unknown error',
  638. MDB2_ERROR_ALREADY_EXISTS => 'already exists',
  639. MDB2_ERROR_CANNOT_CREATE => 'can not create',
  640. MDB2_ERROR_CANNOT_ALTER => 'can not alter',
  641. MDB2_ERROR_CANNOT_REPLACE => 'can not replace',
  642. MDB2_ERROR_CANNOT_DELETE => 'can not delete',
  643. MDB2_ERROR_CANNOT_DROP => 'can not drop',
  644. MDB2_ERROR_CONSTRAINT => 'constraint violation',
  645. MDB2_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',
  646. MDB2_ERROR_DIVZERO => 'division by zero',
  647. MDB2_ERROR_INVALID => 'invalid',
  648. MDB2_ERROR_INVALID_DATE => 'invalid date or time',
  649. MDB2_ERROR_INVALID_NUMBER => 'invalid number',
  650. MDB2_ERROR_MISMATCH => 'mismatch',
  651. MDB2_ERROR_NODBSELECTED => 'no database selected',
  652. MDB2_ERROR_NOSUCHFIELD => 'no such field',
  653. MDB2_ERROR_NOSUCHTABLE => 'no such table',
  654. MDB2_ERROR_NOT_CAPABLE => 'MDB2 backend not capable',
  655. MDB2_ERROR_NOT_FOUND => 'not found',
  656. MDB2_ERROR_NOT_LOCKED => 'not locked',
  657. MDB2_ERROR_SYNTAX => 'syntax error',
  658. MDB2_ERROR_UNSUPPORTED => 'not supported',
  659. MDB2_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
  660. MDB2_ERROR_INVALID_DSN => 'invalid DSN',
  661. MDB2_ERROR_CONNECT_FAILED => 'connect failed',
  662. MDB2_ERROR_NEED_MORE_DATA => 'insufficient data supplied',
  663. MDB2_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
  664. MDB2_ERROR_NOSUCHDB => 'no such database',
  665. MDB2_ERROR_ACCESS_VIOLATION => 'insufficient permissions',
  666. MDB2_ERROR_LOADMODULE => 'error while including on demand module',
  667. MDB2_ERROR_TRUNCATED => 'truncated',
  668. MDB2_ERROR_DEADLOCK => 'deadlock detected',
  669. );
  670. }
  671. if (is_null($value)) {
  672. return $errorMessages;
  673. }
  674. if (PEAR::isError($value)) {
  675. $value = $value->getCode();
  676. }
  677. return isset($errorMessages[$value]) ?
  678. $errorMessages[$value] : $errorMessages[MDB2_ERROR];
  679. }
  680. // }}}
  681. // {{{ function parseDSN($dsn)
  682. /**
  683. * Parse a data source name.
  684. *
  685. * Additional keys can be added by appending a URI query string to the
  686. * end of the DSN.
  687. *
  688. * The format of the supplied DSN is in its fullest form:
  689. * <code>
  690. * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
  691. * </code>
  692. *
  693. * Most variations are allowed:
  694. * <code>
  695. * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
  696. * phptype://username:password@hostspec/database_name
  697. * phptype://username:password@hostspec
  698. * phptype://username@hostspec
  699. * phptype://hostspec/database
  700. * phptype://hostspec
  701. * phptype(dbsyntax)
  702. * phptype
  703. * </code>
  704. *
  705. * @param string Data Source Name to be parsed
  706. *
  707. * @return array an associative array with the following keys:
  708. * + phptype: Database backend used in PHP (mysql, odbc etc.)
  709. * + dbsyntax: Database used with regards to SQL syntax etc.
  710. * + protocol: Communication protocol to use (tcp, unix etc.)
  711. * + hostspec: Host specification (hostname[:port])
  712. * + database: Database to use on the DBMS server
  713. * + username: User name for login
  714. * + password: Password for login
  715. *
  716. * @access public
  717. * @author Tomas V.V.Cox <cox@idecnet.com>
  718. */
  719. static function parseDSN($dsn)
  720. {
  721. $parsed = $GLOBALS['_MDB2_dsninfo_default'];
  722. if (is_array($dsn)) {
  723. $dsn = array_merge($parsed, $dsn);
  724. if (!$dsn['dbsyntax']) {
  725. $dsn['dbsyntax'] = $dsn['phptype'];
  726. }
  727. return $dsn;
  728. }
  729. // Find phptype and dbsyntax
  730. if (($pos = strpos($dsn, '://')) !== false) {
  731. $str = substr($dsn, 0, $pos);
  732. $dsn = substr($dsn, $pos + 3);
  733. } else {
  734. $str = $dsn;
  735. $dsn = null;
  736. }
  737. // Get phptype and dbsyntax
  738. // $str => phptype(dbsyntax)
  739. if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
  740. $parsed['phptype'] = $arr[1];
  741. $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
  742. } else {
  743. $parsed['phptype'] = $str;
  744. $parsed['dbsyntax'] = $str;
  745. }
  746. if (!count($dsn)) {
  747. return $parsed;
  748. }
  749. // Get (if found): username and password
  750. // $dsn => username:password@protocol+hostspec/database
  751. if (($at = strrpos($dsn,'@')) !== false) {
  752. $str = substr($dsn, 0, $at);
  753. $dsn = substr($dsn, $at + 1);
  754. if (($pos = strpos($str, ':')) !== false) {
  755. $parsed['username'] = rawurldecode(substr($str, 0, $pos));
  756. $parsed['password'] = rawurldecode(substr($str, $pos + 1));
  757. } else {
  758. $parsed['username'] = rawurldecode($str);
  759. }
  760. }
  761. // Find protocol and hostspec
  762. // $dsn => proto(proto_opts)/database
  763. if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
  764. $proto = $match[1];
  765. $proto_opts = $match[2] ? $match[2] : false;
  766. $dsn = $match[3];
  767. // $dsn => protocol+hostspec/database (old format)
  768. } else {
  769. if (strpos($dsn, '+') !== false) {
  770. list($proto, $dsn) = explode('+', $dsn, 2);
  771. }
  772. if ( strpos($dsn, '//') === 0
  773. && strpos($dsn, '/', 2) !== false
  774. && $parsed['phptype'] == 'oci8'
  775. ) {
  776. //oracle's "Easy Connect" syntax:
  777. //"username/password@[//]host[:port][/service_name]"
  778. //e.g. "scott/tiger@//mymachine:1521/oracle"
  779. $proto_opts = $dsn;
  780. $dsn = null;
  781. } elseif (strpos($dsn, '/') !== false) {
  782. list($proto_opts, $dsn) = explode('/', $dsn, 2);
  783. } else {
  784. $proto_opts = $dsn;
  785. $dsn = null;
  786. }
  787. }
  788. // process the different protocol options
  789. $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
  790. $proto_opts = rawurldecode($proto_opts);
  791. if (strpos($proto_opts, ':') !== false) {
  792. list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
  793. }
  794. if ($parsed['protocol'] == 'tcp') {
  795. $parsed['hostspec'] = $proto_opts;
  796. } elseif ($parsed['protocol'] == 'unix') {
  797. $parsed['socket'] = $proto_opts;
  798. }
  799. // Get dabase if any
  800. // $dsn => database
  801. if ($dsn) {
  802. // /database
  803. if (($pos = strpos($dsn, '?')) === false) {
  804. $parsed['database'] = $dsn;
  805. // /database?param1=value1&param2=value2
  806. } else {
  807. $parsed['database'] = substr($dsn, 0, $pos);
  808. $dsn = substr($dsn, $pos + 1);
  809. if (strpos($dsn, '&') !== false) {
  810. $opts = explode('&', $dsn);
  811. } else { // database?param1=value1
  812. $opts = array($dsn);
  813. }
  814. foreach ($opts as $opt) {
  815. list($key, $value) = explode('=', $opt);
  816. if (!isset($parsed[$key])) {
  817. // don't allow params overwrite
  818. $parsed[$key] = rawurldecode($value);
  819. }
  820. }
  821. }
  822. }
  823. return $parsed;
  824. }
  825. // }}}
  826. // {{{ function fileExists($file)
  827. /**
  828. * Checks if a file exists in the include path
  829. *
  830. * @param string filename
  831. *
  832. * @return bool true success and false on error
  833. *
  834. * @access public
  835. */
  836. function fileExists($file)
  837. {
  838. // safe_mode does notwork with is_readable()
  839. if (!@ini_get('safe_mode')) {
  840. $dirs = explode(PATH_SEPARATOR, ini_get('include_path'));
  841. foreach ($dirs as $dir) {
  842. if (is_readable($dir . DIRECTORY_SEPARATOR . $file)) {
  843. return true;
  844. }
  845. }
  846. } else {
  847. $fp = @fopen($file, 'r', true);
  848. if (is_resource($fp)) {
  849. @fclose($fp);
  850. return true;
  851. }
  852. }
  853. return false;
  854. }
  855. // }}}
  856. }
  857. // }}}
  858. // {{{ class MDB2_Error extends PEAR_Error
  859. /**
  860. * MDB2_Error implements a class for reporting portable database error
  861. * messages.
  862. *
  863. * @package MDB2
  864. * @category Database
  865. * @author Stig Bakken <ssb@fast.no>
  866. */
  867. class MDB2_Error extends PEAR_Error
  868. {
  869. // {{{ constructor: function MDB2_Error($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN, $level = E_USER_NOTICE, $debuginfo = null)
  870. /**
  871. * MDB2_Error constructor.
  872. *
  873. * @param mixed MDB2 error code, or string with error message.
  874. * @param int what 'error mode' to operate in
  875. * @param int what error level to use for $mode & PEAR_ERROR_TRIGGER
  876. * @param smixed additional debug info, such as the last query
  877. */
  878. function MDB2_Error($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN,
  879. $level = E_USER_NOTICE, $debuginfo = null)
  880. {
  881. if (is_null($code)) {
  882. $code = MDB2_ERROR;
  883. }
  884. $this->PEAR_Error('MDB2 Error: '.MDB2::errorMessage($code), $code,
  885. $mode, $level, $debuginfo);
  886. }
  887. // }}}
  888. }
  889. // }}}
  890. // {{{ class MDB2_Driver_Common extends PEAR
  891. /**
  892. * MDB2_Driver_Common: Base class that is extended by each MDB2 driver
  893. *
  894. * @package MDB2
  895. * @category Database
  896. * @author Lukas Smith <smith@pooteeweet.org>
  897. */
  898. class MDB2_Driver_Common extends PEAR
  899. {
  900. // {{{ Variables (Properties)
  901. /**
  902. * index of the MDB2 object within the $GLOBALS['_MDB2_databases'] array
  903. * @var int
  904. * @access public
  905. */
  906. var $db_index = 0;
  907. /**
  908. * DSN used for the next query
  909. * @var array
  910. * @access protected
  911. */
  912. var $dsn = array();
  913. /**
  914. * DSN that was used to create the current connection
  915. * @var array
  916. * @access protected
  917. */
  918. var $connected_dsn = array();
  919. /**
  920. * connection resource
  921. * @var mixed
  922. * @access protected
  923. */
  924. var $connection = 0;
  925. /**
  926. * if the current opened connection is a persistent connection
  927. * @var bool
  928. * @access protected
  929. */
  930. var $opened_persistent;
  931. /**
  932. * the name of the database for the next query
  933. * @var string
  934. * @access protected
  935. */
  936. var $database_name = '';
  937. /**
  938. * the name of the database currently selected
  939. * @var string
  940. * @access protected
  941. */
  942. var $connected_database_name = '';
  943. /**
  944. * server version information
  945. * @var string
  946. * @access protected
  947. */
  948. var $connected_server_info = '';
  949. /**
  950. * list of all supported features of the given driver
  951. * @var array
  952. * @access public
  953. */
  954. var $supported = array(
  955. 'sequences' => false,
  956. 'indexes' => false,
  957. 'affected_rows' => false,
  958. 'summary_functions' => false,
  959. 'order_by_text' => false,
  960. 'transactions' => false,
  961. 'savepoints' => false,
  962. 'current_id' => false,
  963. 'limit_queries' => false,
  964. 'LOBs' => false,
  965. 'replace' => false,
  966. 'sub_selects' => false,
  967. 'auto_increment' => false,
  968. 'primary_key' => false,
  969. 'result_introspection' => false,
  970. 'prepared_statements' => false,
  971. 'identifier_quoting' => false,
  972. 'pattern_escaping' => false,
  973. 'new_link' => false,
  974. );
  975. /**
  976. * Array of supported options that can be passed to the MDB2 instance.
  977. *
  978. * The options can be set during object creation, using
  979. * MDB2::connect(), MDB2::factory() or MDB2::singleton(). The options can
  980. * also be set after the object is created, using MDB2::setOptions() or
  981. * MDB2_Driver_Common::setOption().
  982. * The list of available option includes:
  983. * <ul>
  984. * <li>$options['ssl'] -> boolean: determines if ssl should be used for connections</li>
  985. * <li>$options['field_case'] -> CASE_LOWER|CASE_UPPER: determines what case to force on field/table names</li>
  986. * <li>$options['disable_query'] -> boolean: determines if queries should be executed</li>
  987. * <li>$options['result_class'] -> string: class used for result sets</li>
  988. * <li>$options['buffered_result_class'] -> string: class used for buffered result sets</li>
  989. * <li>$options['result_wrap_class'] -> string: class used to wrap result sets into</li>
  990. * <li>$options['result_buffering'] -> boolean should results be buffered or not?</li>
  991. * <li>$options['fetch_class'] -> string: class to use when fetch mode object is used</li>
  992. * <li>$options['persistent'] -> boolean: persistent connection?</li>
  993. * <li>$options['debug'] -> integer: numeric debug level</li>
  994. * <li>$options['debug_handler'] -> string: function/method that captures debug messages</li>
  995. * <li>$options['debug_expanded_output'] -> bool: BC option to determine if more context information should be send to the debug handler</li>
  996. * <li>$options['default_text_field_length'] -> integer: default text field length to use</li>
  997. * <li>$options['lob_buffer_length'] -> integer: LOB buffer length</li>
  998. * <li>$options['log_line_break'] -> string: line-break format</li>
  999. * <li>$options['idxname_format'] -> string: pattern for index name</li>
  1000. * <li>$options['seqname_format'] -> string: pattern for sequence name</li>
  1001. * <li>$options['savepoint_format'] -> string: pattern for auto generated savepoint names</li>
  1002. * <li>$options['statement_format'] -> string: pattern for prepared statement names</li>
  1003. * <li>$options['seqcol_name'] -> string: sequence column name</li>
  1004. * <li>$options['quote_identifier'] -> boolean: if identifier quoting should be done when check_option is used</li>
  1005. * <li>$options['use_transactions'] -> boolean: if transaction use should be enabled</li>
  1006. * <li>$options['decimal_places'] -> integer: number of decimal places to handle</li>
  1007. * <li>$options['portability'] -> integer: portability constant</li>
  1008. * <li>$options['modules'] -> array: short to long module name mapping for __call()</li>
  1009. * <li>$options['emulate_prepared'] -> boolean: force prepared statements to be emulated</li>
  1010. * <li>$options['datatype_map'] -> array: map user defined datatypes to other primitive datatypes</li>
  1011. * <li>$options['datatype_map_callback'] -> array: callback function/method that should be called</li>
  1012. * </ul>
  1013. *
  1014. * @var array
  1015. * @access public
  1016. * @see MDB2::connect()
  1017. * @see MDB2::factory()
  1018. * @see MDB2::singleton()
  1019. * @see MDB2_Driver_Common::setOption()
  1020. */
  1021. var $options = array(
  1022. 'ssl' => false,
  1023. 'field_case' => CASE_LOWER,
  1024. 'disable_query' => false,
  1025. 'result_class' => 'MDB2_Result_%s',
  1026. 'buffered_result_class' => 'MDB2_BufferedResult_%s',
  1027. 'result_wrap_class' => false,
  1028. 'result_buffering' => true,
  1029. 'fetch_class' => 'stdClass',
  1030. 'persistent' => false,
  1031. 'debug' => 0,
  1032. 'debug_handler' => 'MDB2_defaultDebugOutput',
  1033. 'debug_expanded_output' => false,
  1034. 'default_text_field_length' => 4096,
  1035. 'lob_buffer_length' => 8192,
  1036. 'log_line_break' => "\n",
  1037. 'idxname_format' => '%s_idx',
  1038. 'seqname_format' => '%s_seq',
  1039. 'savepoint_format' => 'MDB2_SAVEPOINT_%s',
  1040. 'statement_format' => 'MDB2_STATEMENT_%1$s_%2$s',
  1041. 'seqcol_name' => 'sequence',
  1042. 'quote_identifier' => false,
  1043. 'use_transactions' => true,
  1044. 'decimal_places' => 2,
  1045. 'portability' => MDB2_PORTABILITY_ALL,
  1046. 'modules' => array(
  1047. 'ex' => 'Extended',
  1048. 'dt' => 'Datatype',
  1049. 'mg' => 'Manager',
  1050. 'rv' => 'Reverse',
  1051. 'na' => 'Native',
  1052. 'fc' => 'Function',
  1053. ),
  1054. 'emulate_prepared' => false,
  1055. 'datatype_map' => array(),
  1056. 'datatype_map_callback' => array(),
  1057. 'nativetype_map_callback' => array(),
  1058. );
  1059. /**
  1060. * string array
  1061. * @var string
  1062. * @access protected
  1063. */
  1064. var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => false, 'escape_pattern' => false);
  1065. /**
  1066. * identifier quoting
  1067. * @var array
  1068. * @access protected
  1069. */
  1070. var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
  1071. /**
  1072. * sql comments
  1073. * @var array
  1074. * @access protected
  1075. */
  1076. var $sql_comments = array(
  1077. array('start' => '--', 'end' => "\n", 'escape' => false),
  1078. array('start' => '/*', 'end' => '*/', 'escape' => false),
  1079. );
  1080. /**
  1081. * comparision wildcards
  1082. * @var array
  1083. * @access protected
  1084. */
  1085. var $wildcards = array('%', '_');
  1086. /**
  1087. * column alias keyword
  1088. * @var string
  1089. * @access protected
  1090. */
  1091. var $as_keyword = ' AS ';
  1092. /**
  1093. * warnings
  1094. * @var array
  1095. * @access protected
  1096. */
  1097. var $warnings = array();
  1098. /**
  1099. * string with the debugging information
  1100. * @var string
  1101. * @access public
  1102. */
  1103. var $debug_output = '';
  1104. /**
  1105. * determine if there is an open transaction
  1106. * @var bool
  1107. * @access protected
  1108. */
  1109. var $in_transaction = false;
  1110. /**
  1111. * the smart transaction nesting depth
  1112. * @var int
  1113. * @access protected
  1114. */
  1115. var $nested_transaction_counter = null;
  1116. /**
  1117. * the first error that occured inside a nested transaction
  1118. * @var MDB2_Error|bool
  1119. * @access protected
  1120. */
  1121. var $has_transaction_error = false;
  1122. /**
  1123. * result offset used in the next query
  1124. * @var int
  1125. * @access protected
  1126. */
  1127. var $offset = 0;
  1128. /**
  1129. * result limit used in the next query
  1130. * @var int
  1131. * @access protected
  1132. */
  1133. var $limit = 0;
  1134. /**
  1135. * Database backend used in PHP (mysql, odbc etc.)
  1136. * @var string
  1137. * @access public
  1138. */
  1139. var $phptype;
  1140. /**
  1141. * Database used with regards to SQL syntax etc.
  1142. * @var string
  1143. * @access public
  1144. */
  1145. var $dbsyntax;
  1146. /**
  1147. * the last query sent to the driver
  1148. * @var string
  1149. * @access public
  1150. */
  1151. var $last_query;
  1152. /**
  1153. * the default fetchmode used
  1154. * @var int
  1155. * @access protected
  1156. */
  1157. var $fetchmode = MDB2_FETCHMODE_ORDERED;
  1158. /**
  1159. * array of module instances
  1160. * @var array
  1161. * @access protected
  1162. */
  1163. var $modules = array();
  1164. /**
  1165. * determines of the PHP4 destructor emulation has been enabled yet
  1166. * @var array
  1167. * @access protected
  1168. */
  1169. var $destructor_registered = true;
  1170. // }}}
  1171. // {{{ constructor: function __construct()
  1172. /**
  1173. * Constructor
  1174. */
  1175. function __construct()
  1176. {
  1177. end($GLOBALS['_MDB2_databases']);
  1178. $db_index = key($GLOBALS['_MDB2_databases']) + 1;
  1179. $GLOBALS['_MDB2_databases'][$db_index] = &$this;
  1180. $this->db_index = $db_index;
  1181. }
  1182. // }}}
  1183. // {{{ destructor: function __destruct()
  1184. /**
  1185. * Destructor
  1186. */
  1187. function __destruct()
  1188. {
  1189. $this->disconnect(false);
  1190. }
  1191. // }}}
  1192. // {{{ function free()
  1193. /**
  1194. * Free the internal references so that the instance can be destroyed
  1195. *
  1196. * @return bool true on success, false if result is invalid
  1197. *
  1198. * @access public
  1199. */
  1200. function free()
  1201. {
  1202. unset($GLOBALS['_MDB2_databases'][$this->db_index]);
  1203. unset($this->db_index);
  1204. return MDB2_OK;
  1205. }
  1206. // }}}
  1207. // {{{ function __toString()
  1208. /**
  1209. * String conversation
  1210. *
  1211. * @return string representation of the object
  1212. *
  1213. * @access public
  1214. */
  1215. function __toString()
  1216. {
  1217. $info = get_class($this);
  1218. $info.= ': (phptype = '.$this->phptype.', dbsyntax = '.$this->dbsyntax.')';
  1219. if ($this->connection) {
  1220. $info.= ' [connected]';
  1221. }
  1222. return $info;
  1223. }
  1224. // }}}
  1225. // {{{ function errorInfo($error = null)
  1226. /**
  1227. * This method is used to collect information about an error
  1228. *
  1229. * @param mixed error code or resource
  1230. *
  1231. * @return array with MDB2 errorcode, native error code, native message
  1232. *
  1233. * @access public
  1234. */
  1235. function errorInfo($error = null)
  1236. {
  1237. return array($error, null, null);
  1238. }
  1239. // }}}
  1240. // {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
  1241. /**
  1242. * This method is used to communicate an error and invoke error
  1243. * callbacks etc. Basically a wrapper for PEAR::raiseError
  1244. * without the message string.
  1245. *
  1246. * @param mixed integer error code, or a PEAR error object (all other
  1247. * parameters are ignored if this parameter is an object
  1248. * @param int error mode, see PEAR_Error docs
  1249. * @param mixed If error mode is PEAR_ERROR_TRIGGER, this is the
  1250. * error level (E_USER_NOTICE etc). If error mode is
  1251. * PEAR_ERROR_CALLBACK, this is the callback function,
  1252. * either as a function name, or as an array of an
  1253. * object and method name. For other error modes this
  1254. * parameter is ignored.
  1255. * @param string Extra debug information. Defaults to the last
  1256. * query and native error code.
  1257. * @param string name of the method that triggered the error
  1258. *
  1259. * @return PEAR_Error instance of a PEAR Error object
  1260. *
  1261. * @access public
  1262. * @see PEAR_Error
  1263. */
  1264. function &raiseError($code = null, $mode = null, $options = null, $userinfo = null, $method = null)
  1265. {
  1266. $userinfo = "[Error message: $userinfo]\n";
  1267. // The error is yet a MDB2 error object
  1268. if (PEAR::isError($code)) {
  1269. // because we use the static PEAR::raiseError, our global
  1270. // handler should be used if it is set
  1271. if (is_null($mode) && !empty($this->_default_error_mode)) {
  1272. $mode = $this->_default_error_mode;
  1273. $options = $this->_default_error_options;
  1274. }
  1275. if (is_null($userinfo)) {
  1276. $userinfo = $code->getUserinfo();
  1277. }
  1278. $code = $code->getCode();
  1279. } elseif ($code == MDB2_ERROR_NOT_FOUND) {
  1280. // extension not loaded: don't call $this->errorInfo() or the script
  1281. // will die
  1282. } elseif (isset($this->connection)) {
  1283. if (!empty($this->last_query)) {
  1284. $userinfo.= "[Last executed query: {$this->last_query}]\n";
  1285. }
  1286. $native_errno = $native_msg = null;
  1287. list($code, $native_errno, $native_msg) = $this->errorInfo($code);
  1288. if (!is_null($native_errno) && $native_errno !== '') {
  1289. $userinfo.= "[Native code: $native_errno]\n";
  1290. }
  1291. if (!is_null($native_msg) && $native_msg !== '') {
  1292. $userinfo.= "[Native message: ". strip_tags($native_msg) ."]\n";
  1293. }
  1294. if (!is_null($method)) {
  1295. $userinfo = $method.': '.$userinfo;
  1296. }
  1297. }
  1298. $err =& PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
  1299. if ($err->getMode() !== PEAR_ERROR_RETURN
  1300. && isset($this->nested_transaction_counter) && !$this->has_transaction_error) {
  1301. $this->has_transaction_error =& $err;
  1302. }
  1303. return $err;
  1304. }
  1305. // }}}
  1306. // {{{ function resetWarnings()
  1307. /**
  1308. * reset the warning array
  1309. *
  1310. * @return void
  1311. *
  1312. * @access public
  1313. */
  1314. function resetWarnings()
  1315. {
  1316. $this->warnings = array();
  1317. }
  1318. // }}}
  1319. // {{{ function getWarnings()
  1320. /**
  1321. * Get all warnings in reverse order.
  1322. * This means that the last warning is the first element in the array
  1323. *
  1324. * @return array with warnings
  1325. *
  1326. * @access public
  1327. * @see resetWarnings()
  1328. */
  1329. function getWarnings()
  1330. {
  1331. return array_reverse($this->warnings);
  1332. }
  1333. // }}}
  1334. // {{{ function setFetchMode($fetchmode, $object_class = 'stdClass')
  1335. /**
  1336. * Sets which fetch mode should be used by default on queries
  1337. * on this connection
  1338. *
  1339. * @param int MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC
  1340. * or MDB2_FETCHMODE_OBJECT
  1341. * @param string the class name of the object to be returned
  1342. * by the fetch methods when the
  1343. * MDB2_FETCHMODE_OBJECT mode is selected.
  1344. * If no class is specified by default a cast
  1345. * to object from the assoc array row will be
  1346. * done. There is also the possibility to use
  1347. * and extend the 'MDB2_row' class.
  1348. *
  1349. * @return mixed MDB2_OK or MDB2 Error Object
  1350. *
  1351. * @access public
  1352. * @see MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC, MDB2_FETCHMODE_OBJECT
  1353. */
  1354. function setFetchMode($fetchmode, $object_class = 'stdClass')
  1355. {
  1356. switch ($fetchmode) {
  1357. case MDB2_FETCHMODE_OBJECT:
  1358. $this->options['fetch_class'] = $object_class;
  1359. case MDB2_FETCHMODE_ORDERED:
  1360. case MDB2_FETCHMODE_ASSOC:
  1361. $this->fetchmode = $fetchmode;
  1362. break;
  1363. default:
  1364. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  1365. 'invalid fetchmode mode', __FUNCTION__);
  1366. }
  1367. return MDB2_OK;
  1368. }
  1369. // }}}
  1370. // {{{ function setOption($option, $value)
  1371. /**
  1372. * set the option for the db class
  1373. *
  1374. * @param string option name
  1375. * @param mixed value for the option
  1376. *
  1377. * @return mixed MDB2_OK or MDB2 Error Object
  1378. *
  1379. * @access public
  1380. */
  1381. function setOption($option, $value)
  1382. {
  1383. if (array_key_exists($option, $this->options)) {
  1384. $this->options[$option] = $value;
  1385. return MDB2_OK;
  1386. }
  1387. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  1388. "unknown option $option", __FUNCTION__);
  1389. }
  1390. // }}}
  1391. // {{{ function getOption($option)
  1392. /**
  1393. * Returns the value of an option
  1394. *
  1395. * @param string option name
  1396. *
  1397. * @return mixed the option value or error object
  1398. *
  1399. * @access public
  1400. */
  1401. function getOption($option)
  1402. {
  1403. if (array_key_exists($option, $this->options)) {
  1404. return $this->options[$option];
  1405. }
  1406. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  1407. "unknown option $option", __FUNCTION__);
  1408. }
  1409. // }}}
  1410. // {{{ function debug($message, $scope = '', $is_manip = null)
  1411. /**
  1412. * set a debug message
  1413. *
  1414. * @param string message that should be appended to the debug variable
  1415. * @param string usually the method name that triggered the debug call:
  1416. * for example 'query', 'prepare', 'execute', 'parameters',
  1417. * 'beginTransaction', 'commit', 'rollback'
  1418. * @param array contains context information about the debug() call
  1419. * common keys are: is_manip, time, result etc.
  1420. *
  1421. * @return void
  1422. *
  1423. * @access public
  1424. */
  1425. function debug($message, $scope = '', $context = array())
  1426. {
  1427. if ($this->options['debug'] && $this->options['debug_handler']) {
  1428. if (!$this->options['debug_expanded_output']) {
  1429. if (!empty($context['when']) && $context['when'] !== 'pre') {
  1430. return null;
  1431. }
  1432. $context = empty($context['is_manip']) ? false : $context['is_manip'];
  1433. }
  1434. return call_user_func_array($this->options['debug_handler'], array(&$this, $scope, $message, $context));
  1435. }
  1436. return null;
  1437. }
  1438. // }}}
  1439. // {{{ function getDebugOutput()
  1440. /**
  1441. * output debug info
  1442. *
  1443. * @return string content of the debug_output class variable
  1444. *
  1445. * @access public
  1446. */
  1447. function getDebugOutput()
  1448. {
  1449. return $this->debug_output;
  1450. }
  1451. // }}}
  1452. // {{{ function escape($text)
  1453. /**
  1454. * Quotes a string so it can be safely used in a query. It will quote
  1455. * the text so it can safely be used within a query.
  1456. *
  1457. * @param string the input string to quote
  1458. * @param bool escape wildcards
  1459. *
  1460. * @return string quoted string
  1461. *
  1462. * @access public
  1463. */
  1464. function escape($text, $escape_wildcards = false)
  1465. {
  1466. if ($escape_wildcards) {
  1467. $text = $this->escapePattern($text);
  1468. }
  1469. $text = str_replace($this->string_quoting['end'], $this->string_quoting['escape'] . $this->string_quoting['end'], $text);
  1470. return $text;
  1471. }
  1472. // }}}
  1473. // {{{ function escapePattern($text)
  1474. /**
  1475. * Quotes pattern (% and _) characters in a string)
  1476. *
  1477. * EXPERIMENTAL
  1478. *
  1479. * WARNING: this function is experimental and may change signature at
  1480. * any time until labelled as non-experimental
  1481. *
  1482. * @param string the input string to quote
  1483. *
  1484. * @return string quoted string
  1485. *
  1486. * @access public
  1487. */
  1488. function escapePattern($text)
  1489. {
  1490. if ($this->string_quoting['escape_pattern']) {
  1491. $text = str_replace($this->string_quoting['escape_pattern'], $this->string_quoting['escape_pattern'] . $this->string_quoting['escape_pattern'], $text);
  1492. foreach ($this->wildcards as $wildcard) {
  1493. $text = str_replace($wildcard, $this->string_quoting['escape_pattern'] . $wildcard, $text);
  1494. }
  1495. }
  1496. return $text;
  1497. }
  1498. // }}}
  1499. // {{{ function quoteIdentifier($str, $check_option = false)
  1500. /**
  1501. * Quote a string so it can be safely used as a table or column name
  1502. *
  1503. * Delimiting style depends on which database driver is being used.
  1504. *
  1505. * NOTE: just because you CAN use delimited identifiers doesn't mean
  1506. * you SHOULD use them. In general, they end up causing way more
  1507. * problems than they solve.
  1508. *
  1509. * Portability is broken by using the following characters inside
  1510. * delimited identifiers:
  1511. * + backtick (<kbd>`</kbd>) -- due to MySQL
  1512. * + double quote (<kbd>"</kbd>) -- due to Oracle
  1513. * + brackets (<kbd>[</kbd> or <kbd>]</kbd>) -- due to Access
  1514. *
  1515. * Delimited identifiers are known to generally work correctly under
  1516. * the following drivers:
  1517. * + mssql
  1518. * + mysql
  1519. * + mysqli
  1520. * + oci8
  1521. * + pgsql
  1522. * + sqlite
  1523. *
  1524. * InterBase doesn't seem to be able to use delimited identifiers
  1525. * via PHP 4. They work fine under PHP 5.
  1526. *
  1527. * @param string identifier name to be quoted
  1528. * @param bool check the 'quote_identifier' option
  1529. *
  1530. * @return string quoted identifier string
  1531. *
  1532. * @access public
  1533. */
  1534. function quoteIdentifier($str, $check_option = false)
  1535. {
  1536. if ($check_option && !$this->options['quote_identifier']) {
  1537. return $str;
  1538. }
  1539. $str = str_replace($this->identifier_quoting['end'], $this->identifier_quoting['escape'] . $this->identifier_quoting['end'], $str);
  1540. return $this->identifier_quoting['start'] . $str . $this->identifier_quoting['end'];
  1541. }
  1542. // }}}
  1543. // {{{ function getAsKeyword()
  1544. /**
  1545. * Gets the string to alias column
  1546. *
  1547. * @return string to use when aliasing a column
  1548. */
  1549. function getAsKeyword()
  1550. {
  1551. return $this->as_keyword;
  1552. }
  1553. // }}}
  1554. // {{{ function getConnection()
  1555. /**
  1556. * Returns a native connection
  1557. *
  1558. * @return mixed a valid MDB2 connection object,
  1559. * or a MDB2 error object on error
  1560. *
  1561. * @access public
  1562. */
  1563. function getConnection()
  1564. {
  1565. $result = $this->connect();
  1566. if (PEAR::isError($result)) {
  1567. return $result;
  1568. }
  1569. return $this->connection;
  1570. }
  1571. // }}}
  1572. // {{{ function _fixResultArrayValues(&$row, $mode)
  1573. /**
  1574. * Do all necessary conversions on result arrays to fix DBMS quirks
  1575. *
  1576. * @param array the array to be fixed (passed by reference)
  1577. * @param array bit-wise addition of the required portability modes
  1578. *
  1579. * @return void
  1580. *
  1581. * @access protected
  1582. */
  1583. function _fixResultArrayValues(&$row, $mode)
  1584. {
  1585. switch ($mode) {
  1586. case MDB2_PORTABILITY_EMPTY_TO_NULL:
  1587. foreach ($row as $key => $value) {
  1588. if ($value === '') {
  1589. $row[$key] = null;
  1590. }
  1591. }
  1592. break;
  1593. case MDB2_PORTABILITY_RTRIM:
  1594. foreach ($row as $key => $value) {
  1595. if (is_string($value)) {
  1596. $row[$key] = rtrim($value);
  1597. }
  1598. }
  1599. break;
  1600. case MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES:
  1601. $tmp_row = array();
  1602. foreach ($row as $key => $value) {
  1603. $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
  1604. }
  1605. $row = $tmp_row;
  1606. break;
  1607. case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL):
  1608. foreach ($row as $key => $value) {
  1609. if ($value === '') {
  1610. $row[$key] = null;
  1611. } elseif (is_string($value)) {
  1612. $row[$key] = rtrim($value);
  1613. }
  1614. }
  1615. break;
  1616. case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
  1617. $tmp_row = array();
  1618. foreach ($row as $key => $value) {
  1619. if (is_string($value)) {
  1620. $value = rtrim($value);
  1621. }
  1622. $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
  1623. }
  1624. $row = $tmp_row;
  1625. break;
  1626. case (MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
  1627. $tmp_row = array();
  1628. foreach ($row as $key => $value) {
  1629. if ($value === '') {
  1630. $value = null;
  1631. }
  1632. $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
  1633. }
  1634. $row = $tmp_row;
  1635. break;
  1636. case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
  1637. $tmp_row = array();
  1638. foreach ($row as $key => $value) {
  1639. if ($value === '') {
  1640. $value = null;
  1641. } elseif (is_string($value)) {
  1642. $value = rtrim($value);
  1643. }
  1644. $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
  1645. }
  1646. $row = $tmp_row;
  1647. break;
  1648. }
  1649. }
  1650. // }}}
  1651. // {{{ function &loadModule($module, $property = null, $phptype_specific = null)
  1652. /**
  1653. * loads a module
  1654. *
  1655. * @param string name of the module that should be loaded
  1656. * (only used for error messages)
  1657. * @param string name of the property into which the class will be loaded
  1658. * @param bool if the class to load for the module is specific to the
  1659. * phptype
  1660. *
  1661. * @return object on success a reference to the given module is returned
  1662. * and on failure a PEAR error
  1663. *
  1664. * @access public
  1665. */
  1666. function &loadModule($module, $property = null, $phptype_specific = null)
  1667. {
  1668. if (!$property) {
  1669. $property = strtolower($module);
  1670. }
  1671. if (!isset($this->{$property})) {
  1672. $version = $phptype_specific;
  1673. if ($phptype_specific !== false) {
  1674. $version = true;
  1675. $class_name = 'MDB2_Driver_'.$module.'_'.$this->phptype;
  1676. $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
  1677. }
  1678. if ($phptype_specific === false
  1679. || (!MDB2::classExists($class_name) && !MDB2::fileExists($file_name))
  1680. ) {
  1681. $version = false;
  1682. $class_name = 'MDB2_'.$module;
  1683. $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
  1684. }
  1685. $err = MDB2::loadClass($class_name, $this->getOption('debug'));
  1686. if (PEAR::isError($err)) {
  1687. return $err;
  1688. }
  1689. // load modul in a specific version
  1690. if ($version) {
  1691. if (method_exists($class_name, 'getClassName')) {
  1692. $class_name_new = call_user_func(array($class_name, 'getClassName'), $this->db_index);
  1693. if ($class_name != $class_name_new) {
  1694. $class_name = $class_name_new;
  1695. $err = MDB2::loadClass($class_name, $this->getOption('debug'));
  1696. if (PEAR::isError($err)) {
  1697. return $err;
  1698. }
  1699. }
  1700. }
  1701. }
  1702. if (!MDB2::classExists($class_name)) {
  1703. $err =& $this->raiseError(MDB2_ERROR_LOADMODULE, null, null,
  1704. "unable to load module '$module' into property '$property'", __FUNCTION__);
  1705. return $err;
  1706. }
  1707. $this->{$property} = new $class_name($this->db_index);
  1708. $this->modules[$module] =& $this->{$property};
  1709. if ($version) {
  1710. // this will be used in the connect method to determine if the module
  1711. // needs to be loaded with a different version if the server
  1712. // version changed in between connects
  1713. $this->loaded_version_modules[] = $property;
  1714. }
  1715. }
  1716. return $this->{$property};
  1717. }
  1718. // }}}
  1719. // {{{ function __call($method, $params)
  1720. /**
  1721. * Calls a module method using the __call magic method
  1722. *
  1723. * @param string Method name.
  1724. * @param array Arguments.
  1725. *
  1726. * @return mixed Returned value.
  1727. */
  1728. function __call($method, $params)
  1729. {
  1730. $module = null;
  1731. if (preg_match('/^([a-z]+)([A-Z])(.*)$/', $method, $match)
  1732. && isset($this->options['modules'][$match[1]])
  1733. ) {
  1734. $module = $this->options['modules'][$match[1]];
  1735. $method = strtolower($match[2]).$match[3];
  1736. if (!isset($this->modules[$module]) || !is_object($this->modules[$module])) {
  1737. $result =& $this->loadModule($module);
  1738. if (PEAR::isError($result)) {
  1739. return $result;
  1740. }
  1741. }
  1742. } else {
  1743. foreach ($this->modules as $key => $foo) {
  1744. if (is_object($this->modules[$key])
  1745. && method_exists($this->modules[$key], $method)
  1746. ) {
  1747. $module = $key;
  1748. break;
  1749. }
  1750. }
  1751. }
  1752. if (!is_null($module)) {
  1753. return call_user_func_array(array(&$this->modules[$module], $method), $params);
  1754. }
  1755. trigger_error(sprintf('Call to undefined function: %s::%s().', get_class($this), $method), E_USER_ERROR);
  1756. }
  1757. // }}}
  1758. // {{{ function beginTransaction($savepoint = null)
  1759. /**
  1760. * Start a transaction or set a savepoint.
  1761. *
  1762. * @param string name of a savepoint to set
  1763. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1764. *
  1765. * @access public
  1766. */
  1767. function beginTransaction($savepoint = null)
  1768. {
  1769. $this->debug('Starting transaction', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  1770. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  1771. 'transactions are not supported', __FUNCTION__);
  1772. }
  1773. // }}}
  1774. // {{{ function commit($savepoint = null)
  1775. /**
  1776. * Commit the database changes done during a transaction that is in
  1777. * progress or release a savepoint. This function may only be called when
  1778. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  1779. * transaction is implicitly started after committing the pending changes.
  1780. *
  1781. * @param string name of a savepoint to release
  1782. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1783. *
  1784. * @access public
  1785. */
  1786. function commit($savepoint = null)
  1787. {
  1788. $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  1789. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  1790. 'commiting transactions is not supported', __FUNCTION__);
  1791. }
  1792. // }}}
  1793. // {{{ function rollback($savepoint = null)
  1794. /**
  1795. * Cancel any database changes done during a transaction or since a specific
  1796. * savepoint that is in progress. This function may only be called when
  1797. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  1798. * transaction is implicitly started after canceling the pending changes.
  1799. *
  1800. * @param string name of a savepoint to rollback to
  1801. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1802. *
  1803. * @access public
  1804. */
  1805. function rollback($savepoint = null)
  1806. {
  1807. $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  1808. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  1809. 'rolling back transactions is not supported', __FUNCTION__);
  1810. }
  1811. // }}}
  1812. // {{{ function inTransaction($ignore_nested = false)
  1813. /**
  1814. * If a transaction is currently open.
  1815. *
  1816. * @param bool if the nested transaction count should be ignored
  1817. * @return int|bool - an integer with the nesting depth is returned if a
  1818. * nested transaction is open
  1819. * - true is returned for a normal open transaction
  1820. * - false is returned if no transaction is open
  1821. *
  1822. * @access public
  1823. */
  1824. function inTransaction($ignore_nested = false)
  1825. {
  1826. if (!$ignore_nested && isset($this->nested_transaction_counter)) {
  1827. return $this->nested_transaction_counter;
  1828. }
  1829. return $this->in_transaction;
  1830. }
  1831. // }}}
  1832. // {{{ function setTransactionIsolation($isolation)
  1833. /**
  1834. * Set the transacton isolation level.
  1835. *
  1836. * @param string standard isolation level
  1837. * READ UNCOMMITTED (allows dirty reads)
  1838. * READ COMMITTED (prevents dirty reads)
  1839. * REPEATABLE READ (prevents nonrepeatable reads)
  1840. * SERIALIZABLE (prevents phantom reads)
  1841. * @param array some transaction options:
  1842. * 'wait' => 'WAIT' | 'NO WAIT'
  1843. * 'rw' => 'READ WRITE' | 'READ ONLY'
  1844. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1845. *
  1846. * @access public
  1847. * @since 2.1.1
  1848. */
  1849. function setTransactionIsolation($isolation, $options = array())
  1850. {
  1851. $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
  1852. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  1853. 'isolation level setting is not supported', __FUNCTION__);
  1854. }
  1855. // }}}
  1856. // {{{ function beginNestedTransaction($savepoint = false)
  1857. /**
  1858. * Start a nested transaction.
  1859. *
  1860. * EXPERIMENTAL
  1861. *
  1862. * WARNING: this function is experimental and may change signature at
  1863. * any time until labelled as non-experimental
  1864. *
  1865. * @return mixed MDB2_OK on success/savepoint name, a MDB2 error on failure
  1866. *
  1867. * @access public
  1868. * @since 2.1.1
  1869. */
  1870. function beginNestedTransaction()
  1871. {
  1872. if ($this->in_transaction) {
  1873. ++$this->nested_transaction_counter;
  1874. $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
  1875. if ($this->supports('savepoints') && $savepoint) {
  1876. return $this->beginTransaction($savepoint);
  1877. }
  1878. return MDB2_OK;
  1879. }
  1880. $this->has_transaction_error = false;
  1881. $result = $this->beginTransaction();
  1882. $this->nested_transaction_counter = 1;
  1883. return $result;
  1884. }
  1885. // }}}
  1886. // {{{ function completeNestedTransaction($force_rollback = false, $release = false)
  1887. /**
  1888. * Finish a nested transaction by rolling back if an error occured or
  1889. * committing otherwise.
  1890. *
  1891. * EXPERIMENTAL
  1892. *
  1893. * WARNING: this function is experimental and may change signature at
  1894. * any time until labelled as non-experimental
  1895. *
  1896. * @param bool if the transaction should be rolled back regardless
  1897. * even if no error was set within the nested transaction
  1898. * @return mixed MDB_OK on commit/counter decrementing, false on rollback
  1899. * and a MDB2 error on failure
  1900. *
  1901. * @access public
  1902. * @since 2.1.1
  1903. */
  1904. function completeNestedTransaction($force_rollback = false)
  1905. {
  1906. if ($this->nested_transaction_counter > 1) {
  1907. $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
  1908. if ($this->supports('savepoints') && $savepoint) {
  1909. if ($force_rollback || $this->has_transaction_error) {
  1910. $result = $this->rollback($savepoint);
  1911. if (!PEAR::isError($result)) {
  1912. $result = false;
  1913. $this->has_transaction_error = false;
  1914. }
  1915. } else {
  1916. $result = $this->commit($savepoint);
  1917. }
  1918. } else {
  1919. $result = MDB2_OK;
  1920. }
  1921. --$this->nested_transaction_counter;
  1922. return $result;
  1923. }
  1924. $this->nested_transaction_counter = null;
  1925. $result = MDB2_OK;
  1926. // transaction has not yet been rolled back
  1927. if ($this->in_transaction) {
  1928. if ($force_rollback || $this->has_transaction_error) {
  1929. $result = $this->rollback();
  1930. if (!PEAR::isError($result)) {
  1931. $result = false;
  1932. }
  1933. } else {
  1934. $result = $this->commit();
  1935. }
  1936. }
  1937. $this->has_transaction_error = false;
  1938. return $result;
  1939. }
  1940. // }}}
  1941. // {{{ function failNestedTransaction($error = null, $immediately = false)
  1942. /**
  1943. * Force setting nested transaction to failed.
  1944. *
  1945. * EXPERIMENTAL
  1946. *
  1947. * WARNING: this function is experimental and may change signature at
  1948. * any time until labelled as non-experimental
  1949. *
  1950. * @param mixed value to return in getNestededTransactionError()
  1951. * @param bool if the transaction should be rolled back immediately
  1952. * @return bool MDB2_OK
  1953. *
  1954. * @access public
  1955. * @since 2.1.1
  1956. */
  1957. function failNestedTransaction($error = null, $immediately = false)
  1958. {
  1959. if (is_null($error)) {
  1960. $error = $this->has_transaction_error ? $this->has_transaction_error : true;
  1961. } elseif (!$error) {
  1962. $error = true;
  1963. }
  1964. $this->has_transaction_error = $error;
  1965. if (!$immediately) {
  1966. return MDB2_OK;
  1967. }
  1968. return $this->rollback();
  1969. }
  1970. // }}}
  1971. // {{{ function getNestedTransactionError()
  1972. /**
  1973. * The first error that occured since the transaction start.
  1974. *
  1975. * EXPERIMENTAL
  1976. *
  1977. * WARNING: this function is experimental and may change signature at
  1978. * any time until labelled as non-experimental
  1979. *
  1980. * @return MDB2_Error|bool MDB2 error object if an error occured or false.
  1981. *
  1982. * @access public
  1983. * @since 2.1.1
  1984. */
  1985. function getNestedTransactionError()
  1986. {
  1987. return $this->has_transaction_error;
  1988. }
  1989. // }}}
  1990. // {{{ connect()
  1991. /**
  1992. * Connect to the database
  1993. *
  1994. * @return true on success, MDB2 Error Object on failure
  1995. */
  1996. function connect()
  1997. {
  1998. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  1999. 'method not implemented', __FUNCTION__);
  2000. }
  2001. // }}}
  2002. // {{{ setCharset($charset, $connection = null)
  2003. /**
  2004. * Set the charset on the current connection
  2005. *
  2006. * @param string charset
  2007. * @param resource connection handle
  2008. *
  2009. * @return true on success, MDB2 Error Object on failure
  2010. */
  2011. function setCharset($charset, $connection = null)
  2012. {
  2013. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2014. 'method not implemented', __FUNCTION__);
  2015. }
  2016. // }}}
  2017. // {{{ function disconnect($force = true)
  2018. /**
  2019. * Log out and disconnect from the database.
  2020. *
  2021. * @param bool if the disconnect should be forced even if the
  2022. * connection is opened persistently
  2023. *
  2024. * @return mixed true on success, false if not connected and error
  2025. * object on error
  2026. *
  2027. * @access public
  2028. */
  2029. function disconnect($force = true)
  2030. {
  2031. $this->connection = 0;
  2032. $this->connected_dsn = array();
  2033. $this->connected_database_name = '';
  2034. $this->opened_persistent = null;
  2035. $this->connected_server_info = '';
  2036. $this->in_transaction = null;
  2037. $this->nested_transaction_counter = null;
  2038. return MDB2_OK;
  2039. }
  2040. // }}}
  2041. // {{{ function setDatabase($name)
  2042. /**
  2043. * Select a different database
  2044. *
  2045. * @param string name of the database that should be selected
  2046. *
  2047. * @return string name of the database previously connected to
  2048. *
  2049. * @access public
  2050. */
  2051. function setDatabase($name)
  2052. {
  2053. $previous_database_name = (isset($this->database_name)) ? $this->database_name : '';
  2054. $this->database_name = $name;
  2055. $this->disconnect(false);
  2056. return $previous_database_name;
  2057. }
  2058. // }}}
  2059. // {{{ function getDatabase()
  2060. /**
  2061. * Get the current database
  2062. *
  2063. * @return string name of the database
  2064. *
  2065. * @access public
  2066. */
  2067. function getDatabase()
  2068. {
  2069. return $this->database_name;
  2070. }
  2071. // }}}
  2072. // {{{ function setDSN($dsn)
  2073. /**
  2074. * set the DSN
  2075. *
  2076. * @param mixed DSN string or array
  2077. *
  2078. * @return MDB2_OK
  2079. *
  2080. * @access public
  2081. */
  2082. function setDSN($dsn)
  2083. {
  2084. $dsn_default = $GLOBALS['_MDB2_dsninfo_default'];
  2085. $dsn = MDB2::parseDSN($dsn);
  2086. if (array_key_exists('database', $dsn)) {
  2087. $this->database_name = $dsn['database'];
  2088. unset($dsn['database']);
  2089. }
  2090. $this->dsn = array_merge($dsn_default, $dsn);
  2091. return $this->disconnect(false);
  2092. }
  2093. // }}}
  2094. // {{{ function getDSN($type = 'string', $hidepw = false)
  2095. /**
  2096. * return the DSN as a string
  2097. *
  2098. * @param string format to return ("array", "string")
  2099. * @param string string to hide the password with
  2100. *
  2101. * @return mixed DSN in the chosen type
  2102. *
  2103. * @access public
  2104. */
  2105. function getDSN($type = 'string', $hidepw = false)
  2106. {
  2107. $dsn = array_merge($GLOBALS['_MDB2_dsninfo_default'], $this->dsn);
  2108. $dsn['phptype'] = $this->phptype;
  2109. $dsn['database'] = $this->database_name;
  2110. if ($hidepw) {
  2111. $dsn['password'] = $hidepw;
  2112. }
  2113. switch ($type) {
  2114. // expand to include all possible options
  2115. case 'string':
  2116. $dsn = $dsn['phptype'].
  2117. ($dsn['dbsyntax'] ? ('('.$dsn['dbsyntax'].')') : '').
  2118. '://'.$dsn['username'].':'.
  2119. $dsn['password'].'@'.$dsn['hostspec'].
  2120. ($dsn['port'] ? (':'.$dsn['port']) : '').
  2121. '/'.$dsn['database'];
  2122. break;
  2123. case 'array':
  2124. default:
  2125. break;
  2126. }
  2127. return $dsn;
  2128. }
  2129. // }}}
  2130. // {{{ function &standaloneQuery($query, $types = null, $is_manip = false)
  2131. /**
  2132. * execute a query as database administrator
  2133. *
  2134. * @param string the SQL query
  2135. * @param mixed array that contains the types of the columns in
  2136. * the result set
  2137. * @param bool if the query is a manipulation query
  2138. *
  2139. * @return mixed MDB2_OK on success, a MDB2 error on failure
  2140. *
  2141. * @access public
  2142. */
  2143. function &standaloneQuery($query, $types = null, $is_manip = false)
  2144. {
  2145. $offset = $this->offset;
  2146. $limit = $this->limit;
  2147. $this->offset = $this->limit = 0;
  2148. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  2149. $connection = $this->getConnection();
  2150. if (PEAR::isError($connection)) {
  2151. return $connection;
  2152. }
  2153. $result =& $this->_doQuery($query, $is_manip, $connection, false);
  2154. if (PEAR::isError($result)) {
  2155. return $result;
  2156. }
  2157. if ($is_manip) {
  2158. $affected_rows = $this->_affectedRows($connection, $result);
  2159. return $affected_rows;
  2160. }
  2161. $result =& $this->_wrapResult($result, $types, true, false, $limit, $offset);
  2162. return $result;
  2163. }
  2164. // }}}
  2165. // {{{ function _modifyQuery($query, $is_manip, $limit, $offset)
  2166. /**
  2167. * Changes a query string for various DBMS specific reasons
  2168. *
  2169. * @param string query to modify
  2170. * @param bool if it is a DML query
  2171. * @param int limit the number of rows
  2172. * @param int start reading from given offset
  2173. *
  2174. * @return string modified query
  2175. *
  2176. * @access protected
  2177. */
  2178. function _modifyQuery($query, $is_manip, $limit, $offset)
  2179. {
  2180. return $query;
  2181. }
  2182. // }}}
  2183. // {{{ function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  2184. /**
  2185. * Execute a query
  2186. * @param string query
  2187. * @param bool if the query is a manipulation query
  2188. * @param resource connection handle
  2189. * @param string database name
  2190. *
  2191. * @return result or error object
  2192. *
  2193. * @access protected
  2194. */
  2195. function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  2196. {
  2197. $this->last_query = $query;
  2198. $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
  2199. if ($result) {
  2200. if (PEAR::isError($result)) {
  2201. return $result;
  2202. }
  2203. $query = $result;
  2204. }
  2205. $err =& $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2206. 'method not implemented', __FUNCTION__);
  2207. return $err;
  2208. }
  2209. // }}}
  2210. // {{{ function _affectedRows($connection, $result = null)
  2211. /**
  2212. * Returns the number of rows affected
  2213. *
  2214. * @param resource result handle
  2215. * @param resource connection handle
  2216. *
  2217. * @return mixed MDB2 Error Object or the number of rows affected
  2218. *
  2219. * @access private
  2220. */
  2221. function _affectedRows($connection, $result = null)
  2222. {
  2223. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2224. 'method not implemented', __FUNCTION__);
  2225. }
  2226. // }}}
  2227. // {{{ function &exec($query)
  2228. /**
  2229. * Execute a manipulation query to the database and return the number of affected rows
  2230. *
  2231. * @param string the SQL query
  2232. *
  2233. * @return mixed number of affected rows on success, a MDB2 error on failure
  2234. *
  2235. * @access public
  2236. */
  2237. function &exec($query)
  2238. {
  2239. $offset = $this->offset;
  2240. $limit = $this->limit;
  2241. $this->offset = $this->limit = 0;
  2242. $query = $this->_modifyQuery($query, true, $limit, $offset);
  2243. $connection = $this->getConnection();
  2244. if (PEAR::isError($connection)) {
  2245. return $connection;
  2246. }
  2247. $result =& $this->_doQuery($query, true, $connection, $this->database_name);
  2248. if (PEAR::isError($result)) {
  2249. return $result;
  2250. }
  2251. $affectedRows = $this->_affectedRows($connection, $result);
  2252. return $affectedRows;
  2253. }
  2254. // }}}
  2255. // {{{ function &query($query, $types = null, $result_class = true, $result_wrap_class = false)
  2256. /**
  2257. * Send a query to the database and return any results
  2258. *
  2259. * @param string the SQL query
  2260. * @param mixed array that contains the types of the columns in
  2261. * the result set
  2262. * @param mixed string which specifies which result class to use
  2263. * @param mixed string which specifies which class to wrap results in
  2264. *
  2265. * @return mixed an MDB2_Result handle on success, a MDB2 error on failure
  2266. *
  2267. * @access public
  2268. */
  2269. function &query($query, $types = null, $result_class = true, $result_wrap_class = false)
  2270. {
  2271. $offset = $this->offset;
  2272. $limit = $this->limit;
  2273. $this->offset = $this->limit = 0;
  2274. $query = $this->_modifyQuery($query, false, $limit, $offset);
  2275. $connection = $this->getConnection();
  2276. if (PEAR::isError($connection)) {
  2277. return $connection;
  2278. }
  2279. $result =& $this->_doQuery($query, false, $connection, $this->database_name);
  2280. if (PEAR::isError($result)) {
  2281. return $result;
  2282. }
  2283. $result =& $this->_wrapResult($result, $types, $result_class, $result_wrap_class, $limit, $offset);
  2284. return $result;
  2285. }
  2286. // }}}
  2287. // {{{ function &_wrapResult($result, $types = array(), $result_class = true, $result_wrap_class = false, $limit = null, $offset = null)
  2288. /**
  2289. * wrap a result set into the correct class
  2290. *
  2291. * @param resource result handle
  2292. * @param mixed array that contains the types of the columns in
  2293. * the result set
  2294. * @param mixed string which specifies which result class to use
  2295. * @param mixed string which specifies which class to wrap results in
  2296. * @param string number of rows to select
  2297. * @param string first row to select
  2298. *
  2299. * @return mixed an MDB2_Result, a MDB2 error on failure
  2300. *
  2301. * @access protected
  2302. */
  2303. function &_wrapResult($result, $types = array(), $result_class = true,
  2304. $result_wrap_class = false, $limit = null, $offset = null)
  2305. {
  2306. if ($types === true) {
  2307. if ($this->supports('result_introspection')) {
  2308. $this->loadModule('Reverse', null, true);
  2309. $tableInfo = $this->reverse->tableInfo($result);
  2310. if (PEAR::isError($tableInfo)) {
  2311. return $tableInfo;
  2312. }
  2313. $types = array();
  2314. foreach ($tableInfo as $field) {
  2315. $types[] = $field['mdb2type'];
  2316. }
  2317. } else {
  2318. $types = null;
  2319. }
  2320. }
  2321. if ($result_class === true) {
  2322. $result_class = $this->options['result_buffering']
  2323. ? $this->options['buffered_result_class'] : $this->options['result_class'];
  2324. }
  2325. if ($result_class) {
  2326. $class_name = sprintf($result_class, $this->phptype);
  2327. if (!MDB2::classExists($class_name)) {
  2328. $err =& $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  2329. 'result class does not exist '.$class_name, __FUNCTION__);
  2330. return $err;
  2331. }
  2332. $result =& new $class_name($this, $result, $limit, $offset);
  2333. if (!MDB2::isResultCommon($result)) {
  2334. $err =& $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  2335. 'result class is not extended from MDB2_Result_Common', __FUNCTION__);
  2336. return $err;
  2337. }
  2338. if (!empty($types)) {
  2339. $err = $result->setResultTypes($types);
  2340. if (PEAR::isError($err)) {
  2341. $result->free();
  2342. return $err;
  2343. }
  2344. }
  2345. }
  2346. if ($result_wrap_class === true) {
  2347. $result_wrap_class = $this->options['result_wrap_class'];
  2348. }
  2349. if ($result_wrap_class) {
  2350. if (!MDB2::classExists($result_wrap_class)) {
  2351. $err =& $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  2352. 'result wrap class does not exist '.$result_wrap_class, __FUNCTION__);
  2353. return $err;
  2354. }
  2355. $result = new $result_wrap_class($result, $this->fetchmode);
  2356. }
  2357. return $result;
  2358. }
  2359. // }}}
  2360. // {{{ function getServerVersion($native = false)
  2361. /**
  2362. * return version information about the server
  2363. *
  2364. * @param bool determines if the raw version string should be returned
  2365. *
  2366. * @return mixed array with version information or row string
  2367. *
  2368. * @access public
  2369. */
  2370. function getServerVersion($native = false)
  2371. {
  2372. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2373. 'method not implemented', __FUNCTION__);
  2374. }
  2375. // }}}
  2376. // {{{ function setLimit($limit, $offset = null)
  2377. /**
  2378. * set the range of the next query
  2379. *
  2380. * @param string number of rows to select
  2381. * @param string first row to select
  2382. *
  2383. * @return mixed MDB2_OK on success, a MDB2 error on failure
  2384. *
  2385. * @access public
  2386. */
  2387. function setLimit($limit, $offset = null)
  2388. {
  2389. if (!$this->supports('limit_queries')) {
  2390. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2391. 'limit is not supported by this driver', __FUNCTION__);
  2392. }
  2393. $limit = (int)$limit;
  2394. if ($limit < 0) {
  2395. return $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
  2396. 'it was not specified a valid selected range row limit', __FUNCTION__);
  2397. }
  2398. $this->limit = $limit;
  2399. if (!is_null($offset)) {
  2400. $offset = (int)$offset;
  2401. if ($offset < 0) {
  2402. return $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
  2403. 'it was not specified a valid first selected range row', __FUNCTION__);
  2404. }
  2405. $this->offset = $offset;
  2406. }
  2407. return MDB2_OK;
  2408. }
  2409. // }}}
  2410. // {{{ function subSelect($query, $type = false)
  2411. /**
  2412. * simple subselect emulation: leaves the query untouched for all RDBMS
  2413. * that support subselects
  2414. *
  2415. * @param string the SQL query for the subselect that may only
  2416. * return a column
  2417. * @param string determines type of the field
  2418. *
  2419. * @return string the query
  2420. *
  2421. * @access public
  2422. */
  2423. function subSelect($query, $type = false)
  2424. {
  2425. if ($this->supports('sub_selects') === true) {
  2426. return $query;
  2427. }
  2428. if (!$this->supports('sub_selects')) {
  2429. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2430. 'method not implemented', __FUNCTION__);
  2431. }
  2432. $col = $this->queryCol($query, $type);
  2433. if (PEAR::isError($col)) {
  2434. return $col;
  2435. }
  2436. if (!is_array($col) || count($col) == 0) {
  2437. return 'NULL';
  2438. }
  2439. if ($type) {
  2440. $this->loadModule('Datatype', null, true);
  2441. return $this->datatype->implodeArray($col, $type);
  2442. }
  2443. return implode(', ', $col);
  2444. }
  2445. // }}}
  2446. // {{{ function replace($table, $fields)
  2447. /**
  2448. * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  2449. * query, except that if there is already a row in the table with the same
  2450. * key field values, the REPLACE query just updates its values instead of
  2451. * inserting a new row.
  2452. *
  2453. * The REPLACE type of query does not make part of the SQL standards. Since
  2454. * practically only MySQL and SQLite implement it natively, this type of
  2455. * query isemulated through this method for other DBMS using standard types
  2456. * of queries inside a transaction to assure the atomicity of the operation.
  2457. *
  2458. * @param string name of the table on which the REPLACE query will
  2459. * be executed.
  2460. * @param array associative array that describes the fields and the
  2461. * values that will be inserted or updated in the specified table. The
  2462. * indexes of the array are the names of all the fields of the table.
  2463. * The values of the array are also associative arrays that describe
  2464. * the values and other properties of the table fields.
  2465. *
  2466. * Here follows a list of field properties that need to be specified:
  2467. *
  2468. * value
  2469. * Value to be assigned to the specified field. This value may be
  2470. * of specified in database independent type format as this
  2471. * function can perform the necessary datatype conversions.
  2472. *
  2473. * Default: this property is required unless the Null property is
  2474. * set to 1.
  2475. *
  2476. * type
  2477. * Name of the type of the field. Currently, all types MDB2
  2478. * are supported except for clob and blob.
  2479. *
  2480. * Default: no type conversion
  2481. *
  2482. * null
  2483. * bool property that indicates that the value for this field
  2484. * should be set to null.
  2485. *
  2486. * The default value for fields missing in INSERT queries may be
  2487. * specified the definition of a table. Often, the default value
  2488. * is already null, but since the REPLACE may be emulated using
  2489. * an UPDATE query, make sure that all fields of the table are
  2490. * listed in this function argument array.
  2491. *
  2492. * Default: 0
  2493. *
  2494. * key
  2495. * bool property that indicates that this field should be
  2496. * handled as a primary key or at least as part of the compound
  2497. * unique index of the table that will determine the row that will
  2498. * updated if it exists or inserted a new row otherwise.
  2499. *
  2500. * This function will fail if no key field is specified or if the
  2501. * value of a key field is set to null because fields that are
  2502. * part of unique index they may not be null.
  2503. *
  2504. * Default: 0
  2505. *
  2506. * @return mixed MDB2_OK on success, a MDB2 error on failure
  2507. *
  2508. * @access public
  2509. */
  2510. function replace($table, $fields)
  2511. {
  2512. if (!$this->supports('replace')) {
  2513. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2514. 'replace query is not supported', __FUNCTION__);
  2515. }
  2516. $count = count($fields);
  2517. $condition = $values = array();
  2518. for ($colnum = 0, reset($fields); $colnum < $count; next($fields), $colnum++) {
  2519. $name = key($fields);
  2520. if (isset($fields[$name]['null']) && $fields[$name]['null']) {
  2521. $value = 'NULL';
  2522. } else {
  2523. $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
  2524. $value = $this->quote($fields[$name]['value'], $type);
  2525. }
  2526. $values[$name] = $value;
  2527. if (isset($fields[$name]['key']) && $fields[$name]['key']) {
  2528. if ($value === 'NULL') {
  2529. return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
  2530. 'key value '.$name.' may not be NULL', __FUNCTION__);
  2531. }
  2532. $condition[] = $name . '=' . $value;
  2533. }
  2534. }
  2535. if (empty($condition)) {
  2536. return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
  2537. 'not specified which fields are keys', __FUNCTION__);
  2538. }
  2539. $result = null;
  2540. $in_transaction = $this->in_transaction;
  2541. if (!$in_transaction && PEAR::isError($result = $this->beginTransaction())) {
  2542. return $result;
  2543. }
  2544. $connection = $this->getConnection();
  2545. if (PEAR::isError($connection)) {
  2546. return $connection;
  2547. }
  2548. $condition = ' WHERE '.implode(' AND ', $condition);
  2549. $query = "DELETE FROM $table$condition";
  2550. $result =& $this->_doQuery($query, true, $connection);
  2551. if (!PEAR::isError($result)) {
  2552. $affected_rows = $this->_affectedRows($connection, $result);
  2553. $insert = implode(', ', array_keys($values));
  2554. $values = implode(', ', $values);
  2555. $query = "INSERT INTO $table ($insert) VALUES ($values)";
  2556. $result =& $this->_doQuery($query, true, $connection);
  2557. if (!PEAR::isError($result)) {
  2558. $affected_rows += $this->_affectedRows($connection, $result);;
  2559. }
  2560. }
  2561. if (!$in_transaction) {
  2562. if (PEAR::isError($result)) {
  2563. $this->rollback();
  2564. } else {
  2565. $result = $this->commit();
  2566. }
  2567. }
  2568. if (PEAR::isError($result)) {
  2569. return $result;
  2570. }
  2571. return $affected_rows;
  2572. }
  2573. // }}}
  2574. // {{{ function &prepare($query, $types = null, $result_types = null, $lobs = array())
  2575. /**
  2576. * Prepares a query for multiple execution with execute().
  2577. * With some database backends, this is emulated.
  2578. * prepare() requires a generic query as string like
  2579. * 'INSERT INTO numbers VALUES(?,?)' or
  2580. * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  2581. * The ? and :[a-zA-Z] and are placeholders which can be set using
  2582. * bindParam() and the query can be send off using the execute() method.
  2583. *
  2584. * @param string the query to prepare
  2585. * @param mixed array that contains the types of the placeholders
  2586. * @param mixed array that contains the types of the columns in
  2587. * the result set or MDB2_PREPARE_RESULT, if set to
  2588. * MDB2_PREPARE_MANIP the query is handled as a manipulation query
  2589. * @param mixed key (field) value (parameter) pair for all lob placeholders
  2590. *
  2591. * @return mixed resource handle for the prepared query on success,
  2592. * a MDB2 error on failure
  2593. *
  2594. * @access public
  2595. * @see bindParam, execute
  2596. */
  2597. function &prepare($query, $types = null, $result_types = null, $lobs = array())
  2598. {
  2599. $is_manip = ($result_types === MDB2_PREPARE_MANIP);
  2600. $offset = $this->offset;
  2601. $limit = $this->limit;
  2602. $this->offset = $this->limit = 0;
  2603. $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
  2604. if ($result) {
  2605. if (PEAR::isError($result)) {
  2606. return $result;
  2607. }
  2608. $query = $result;
  2609. }
  2610. $placeholder_type_guess = $placeholder_type = null;
  2611. $question = '?';
  2612. $colon = ':';
  2613. $positions = array();
  2614. $position = 0;
  2615. $ignores = $this->sql_comments;
  2616. $ignores[] = $this->string_quoting;
  2617. $ignores[] = $this->identifier_quoting;
  2618. while ($position < strlen($query)) {
  2619. $q_position = strpos($query, $question, $position);
  2620. $c_position = strpos($query, $colon, $position);
  2621. if ($q_position && $c_position) {
  2622. $p_position = min($q_position, $c_position);
  2623. } elseif ($q_position) {
  2624. $p_position = $q_position;
  2625. } elseif ($c_position) {
  2626. $p_position = $c_position;
  2627. } else {
  2628. break;
  2629. }
  2630. if (is_null($placeholder_type)) {
  2631. $placeholder_type_guess = $query[$p_position];
  2632. }
  2633. $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
  2634. if (PEAR::isError($new_pos)) {
  2635. return $new_pos;
  2636. }
  2637. if ($new_pos != $position) {
  2638. $position = $new_pos;
  2639. continue; //evaluate again starting from the new position
  2640. }
  2641. if ($query[$position] == $placeholder_type_guess) {
  2642. if (is_null($placeholder_type)) {
  2643. $placeholder_type = $query[$p_position];
  2644. $question = $colon = $placeholder_type;
  2645. if (!empty($types) && is_array($types)) {
  2646. if ($placeholder_type == ':') {
  2647. if (is_int(key($types))) {
  2648. $types_tmp = $types;
  2649. $types = array();
  2650. $count = -1;
  2651. }
  2652. } else {
  2653. $types = array_values($types);
  2654. }
  2655. }
  2656. }
  2657. if ($placeholder_type == ':') {
  2658. $parameter = preg_replace('/^.{'.($position+1).'}([a-z0-9_]+).*$/si', '\\1', $query);
  2659. if ($parameter === '') {
  2660. $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
  2661. 'named parameter with an empty name', __FUNCTION__);
  2662. return $err;
  2663. }
  2664. $positions[$p_position] = $parameter;
  2665. $query = substr_replace($query, '?', $position, strlen($parameter)+1);
  2666. // use parameter name in type array
  2667. if (isset($count) && isset($types_tmp[++$count])) {
  2668. $types[$parameter] = $types_tmp[$count];
  2669. }
  2670. } else {
  2671. $positions[$p_position] = count($positions);
  2672. }
  2673. $position = $p_position + 1;
  2674. } else {
  2675. $position = $p_position;
  2676. }
  2677. }
  2678. $class_name = 'MDB2_Statement_'.$this->phptype;
  2679. $statement = null;
  2680. $obj = new $class_name($this, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
  2681. $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
  2682. return $obj;
  2683. }
  2684. // }}}
  2685. // {{{ function _skipDelimitedStrings($query, $position, $p_position)
  2686. /**
  2687. * Utility method, used by prepare() to avoid replacing placeholders within delimited strings.
  2688. * Check if the placeholder is contained within a delimited string.
  2689. * If so, skip it and advance the position, otherwise return the current position,
  2690. * which is valid
  2691. *
  2692. * @param string $query
  2693. * @param integer $position current string cursor position
  2694. * @param integer $p_position placeholder position
  2695. *
  2696. * @return mixed integer $new_position on success
  2697. * MDB2_Error on failure
  2698. *
  2699. * @access protected
  2700. */
  2701. function _skipDelimitedStrings($query, $position, $p_position)
  2702. {
  2703. $ignores = $this->sql_comments;
  2704. $ignores[] = $this->string_quoting;
  2705. $ignores[] = $this->identifier_quoting;
  2706. foreach ($ignores as $ignore) {
  2707. if (!empty($ignore['start'])) {
  2708. if (is_int($start_quote = strpos($query, $ignore['start'], $position)) && $start_quote < $p_position) {
  2709. $end_quote = $start_quote;
  2710. do {
  2711. if (!is_int($end_quote = strpos($query, $ignore['end'], $end_quote + 1))) {
  2712. if ($ignore['end'] === "\n") {
  2713. $end_quote = strlen($query) - 1;
  2714. } else {
  2715. $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
  2716. 'query with an unterminated text string specified', __FUNCTION__);
  2717. return $err;
  2718. }
  2719. }
  2720. } while ($ignore['escape'] && $query[($end_quote - 1)] == $ignore['escape']);
  2721. $position = $end_quote + 1;
  2722. return $position;
  2723. }
  2724. }
  2725. }
  2726. return $position;
  2727. }
  2728. // }}}
  2729. // {{{ function quote($value, $type = null, $quote = true)
  2730. /**
  2731. * Convert a text value into a DBMS specific format that is suitable to
  2732. * compose query statements.
  2733. *
  2734. * @param string text string value that is intended to be converted.
  2735. * @param string type to which the value should be converted to
  2736. * @param bool quote
  2737. * @param bool escape wildcards
  2738. *
  2739. * @return string text string that represents the given argument value in
  2740. * a DBMS specific format.
  2741. *
  2742. * @access public
  2743. */
  2744. function quote($value, $type = null, $quote = true, $escape_wildcards = false)
  2745. {
  2746. $result = $this->loadModule('Datatype', null, true);
  2747. if (PEAR::isError($result)) {
  2748. return $result;
  2749. }
  2750. return $this->datatype->quote($value, $type, $quote, $escape_wildcards);
  2751. }
  2752. // }}}
  2753. // {{{ function getDeclaration($type, $name, $field)
  2754. /**
  2755. * Obtain DBMS specific SQL code portion needed to declare
  2756. * of the given type
  2757. *
  2758. * @param string type to which the value should be converted to
  2759. * @param string name the field to be declared.
  2760. * @param string definition of the field
  2761. *
  2762. * @return string DBMS specific SQL code portion that should be used to
  2763. * declare the specified field.
  2764. *
  2765. * @access public
  2766. */
  2767. function getDeclaration($type, $name, $field)
  2768. {
  2769. $result = $this->loadModule('Datatype', null, true);
  2770. if (PEAR::isError($result)) {
  2771. return $result;
  2772. }
  2773. return $this->datatype->getDeclaration($type, $name, $field);
  2774. }
  2775. // }}}
  2776. // {{{ function compareDefinition($current, $previous)
  2777. /**
  2778. * Obtain an array of changes that may need to applied
  2779. *
  2780. * @param array new definition
  2781. * @param array old definition
  2782. *
  2783. * @return array containing all changes that will need to be applied
  2784. *
  2785. * @access public
  2786. */
  2787. function compareDefinition($current, $previous)
  2788. {
  2789. $result = $this->loadModule('Datatype', null, true);
  2790. if (PEAR::isError($result)) {
  2791. return $result;
  2792. }
  2793. return $this->datatype->compareDefinition($current, $previous);
  2794. }
  2795. // }}}
  2796. // {{{ function supports($feature)
  2797. /**
  2798. * Tell whether a DB implementation or its backend extension
  2799. * supports a given feature.
  2800. *
  2801. * @param string name of the feature (see the MDB2 class doc)
  2802. *
  2803. * @return bool|string if this DB implementation supports a given feature
  2804. * false means no, true means native,
  2805. * 'emulated' means emulated
  2806. *
  2807. * @access public
  2808. */
  2809. function supports($feature)
  2810. {
  2811. if (array_key_exists($feature, $this->supported)) {
  2812. return $this->supported[$feature];
  2813. }
  2814. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2815. "unknown support feature $feature", __FUNCTION__);
  2816. }
  2817. // }}}
  2818. // {{{ function getSequenceName($sqn)
  2819. /**
  2820. * adds sequence name formatting to a sequence name
  2821. *
  2822. * @param string name of the sequence
  2823. *
  2824. * @return string formatted sequence name
  2825. *
  2826. * @access public
  2827. */
  2828. function getSequenceName($sqn)
  2829. {
  2830. return sprintf($this->options['seqname_format'],
  2831. preg_replace('/[^a-z0-9_\$.]/i', '_', $sqn));
  2832. }
  2833. // }}}
  2834. // {{{ function getIndexName($idx)
  2835. /**
  2836. * adds index name formatting to a index name
  2837. *
  2838. * @param string name of the index
  2839. *
  2840. * @return string formatted index name
  2841. *
  2842. * @access public
  2843. */
  2844. function getIndexName($idx)
  2845. {
  2846. return sprintf($this->options['idxname_format'],
  2847. preg_replace('/[^a-z0-9_\$]/i', '_', $idx));
  2848. }
  2849. // }}}
  2850. // {{{ function nextID($seq_name, $ondemand = true)
  2851. /**
  2852. * Returns the next free id of a sequence
  2853. *
  2854. * @param string name of the sequence
  2855. * @param bool when true missing sequences are automatic created
  2856. *
  2857. * @return mixed MDB2 Error Object or id
  2858. *
  2859. * @access public
  2860. */
  2861. function nextID($seq_name, $ondemand = true)
  2862. {
  2863. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2864. 'method not implemented', __FUNCTION__);
  2865. }
  2866. // }}}
  2867. // {{{ function lastInsertID($table = null, $field = null)
  2868. /**
  2869. * Returns the autoincrement ID if supported or $id or fetches the current
  2870. * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  2871. *
  2872. * @param string name of the table into which a new row was inserted
  2873. * @param string name of the field into which a new row was inserted
  2874. *
  2875. * @return mixed MDB2 Error Object or id
  2876. *
  2877. * @access public
  2878. */
  2879. function lastInsertID($table = null, $field = null)
  2880. {
  2881. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2882. 'method not implemented', __FUNCTION__);
  2883. }
  2884. // }}}
  2885. // {{{ function currID($seq_name)
  2886. /**
  2887. * Returns the current id of a sequence
  2888. *
  2889. * @param string name of the sequence
  2890. *
  2891. * @return mixed MDB2 Error Object or id
  2892. *
  2893. * @access public
  2894. */
  2895. function currID($seq_name)
  2896. {
  2897. $this->warnings[] = 'database does not support getting current
  2898. sequence value, the sequence value was incremented';
  2899. return $this->nextID($seq_name);
  2900. }
  2901. // }}}
  2902. // {{{ function queryOne($query, $type = null, $colnum = 0)
  2903. /**
  2904. * Execute the specified query, fetch the value from the first column of
  2905. * the first row of the result set and then frees
  2906. * the result set.
  2907. *
  2908. * @param string the SELECT query statement to be executed.
  2909. * @param string optional argument that specifies the expected
  2910. * datatype of the result set field, so that an eventual conversion
  2911. * may be performed. The default datatype is text, meaning that no
  2912. * conversion is performed
  2913. * @param int the column number to fetch
  2914. *
  2915. * @return mixed MDB2_OK or field value on success, a MDB2 error on failure
  2916. *
  2917. * @access public
  2918. */
  2919. function queryOne($query, $type = null, $colnum = 0)
  2920. {
  2921. $result = $this->query($query, $type);
  2922. if (!MDB2::isResultCommon($result)) {
  2923. return $result;
  2924. }
  2925. $one = $result->fetchOne($colnum);
  2926. $result->free();
  2927. return $one;
  2928. }
  2929. // }}}
  2930. // {{{ function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
  2931. /**
  2932. * Execute the specified query, fetch the values from the first
  2933. * row of the result set into an array and then frees
  2934. * the result set.
  2935. *
  2936. * @param string the SELECT query statement to be executed.
  2937. * @param array optional array argument that specifies a list of
  2938. * expected datatypes of the result set columns, so that the eventual
  2939. * conversions may be performed. The default list of datatypes is
  2940. * empty, meaning that no conversion is performed.
  2941. * @param int how the array data should be indexed
  2942. *
  2943. * @return mixed MDB2_OK or data array on success, a MDB2 error on failure
  2944. *
  2945. * @access public
  2946. */
  2947. function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
  2948. {
  2949. $result = $this->query($query, $types);
  2950. if (!MDB2::isResultCommon($result)) {
  2951. return $result;
  2952. }
  2953. $row = $result->fetchRow($fetchmode);
  2954. $result->free();
  2955. return $row;
  2956. }
  2957. // }}}
  2958. // {{{ function queryCol($query, $type = null, $colnum = 0)
  2959. /**
  2960. * Execute the specified query, fetch the value from the first column of
  2961. * each row of the result set into an array and then frees the result set.
  2962. *
  2963. * @param string the SELECT query statement to be executed.
  2964. * @param string optional argument that specifies the expected
  2965. * datatype of the result set field, so that an eventual conversion
  2966. * may be performed. The default datatype is text, meaning that no
  2967. * conversion is performed
  2968. * @param int the row number to fetch
  2969. *
  2970. * @return mixed MDB2_OK or data array on success, a MDB2 error on failure
  2971. *
  2972. * @access public
  2973. */
  2974. function queryCol($query, $type = null, $colnum = 0)
  2975. {
  2976. $result = $this->query($query, $type);
  2977. if (!MDB2::isResultCommon($result)) {
  2978. return $result;
  2979. }
  2980. $col = $result->fetchCol($colnum);
  2981. $result->free();
  2982. return $col;
  2983. }
  2984. // }}}
  2985. // {{{ function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
  2986. /**
  2987. * Execute the specified query, fetch all the rows of the result set into
  2988. * a two dimensional array and then frees the result set.
  2989. *
  2990. * @param string the SELECT query statement to be executed.
  2991. * @param array optional array argument that specifies a list of
  2992. * expected datatypes of the result set columns, so that the eventual
  2993. * conversions may be performed. The default list of datatypes is
  2994. * empty, meaning that no conversion is performed.
  2995. * @param int how the array data should be indexed
  2996. * @param bool if set to true, the $all will have the first
  2997. * column as its first dimension
  2998. * @param bool used only when the query returns exactly
  2999. * two columns. If true, the values of the returned array will be
  3000. * one-element arrays instead of scalars.
  3001. * @param bool if true, the values of the returned array is
  3002. * wrapped in another array. If the same key value (in the first
  3003. * column) repeats itself, the values will be appended to this array
  3004. * instead of overwriting the existing values.
  3005. *
  3006. * @return mixed MDB2_OK or data array on success, a MDB2 error on failure
  3007. *
  3008. * @access public
  3009. */
  3010. function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT,
  3011. $rekey = false, $force_array = false, $group = false)
  3012. {
  3013. $result = $this->query($query, $types);
  3014. if (!MDB2::isResultCommon($result)) {
  3015. return $result;
  3016. }
  3017. $all = $result->fetchAll($fetchmode, $rekey, $force_array, $group);
  3018. $result->free();
  3019. return $all;
  3020. }
  3021. // }}}
  3022. }
  3023. // }}}
  3024. // {{{ class MDB2_Result
  3025. /**
  3026. * The dummy class that all user space result classes should extend from
  3027. *
  3028. * @package MDB2
  3029. * @category Database
  3030. * @author Lukas Smith <smith@pooteeweet.org>
  3031. */
  3032. class MDB2_Result
  3033. {
  3034. }
  3035. // }}}
  3036. // {{{ class MDB2_Result_Common extends MDB2_Result
  3037. /**
  3038. * The common result class for MDB2 result objects
  3039. *
  3040. * @package MDB2
  3041. * @category Database
  3042. * @author Lukas Smith <smith@pooteeweet.org>
  3043. */
  3044. class MDB2_Result_Common extends MDB2_Result
  3045. {
  3046. // {{{ Variables (Properties)
  3047. var $db;
  3048. var $result;
  3049. var $rownum = -1;
  3050. var $types = array();
  3051. var $values = array();
  3052. var $offset;
  3053. var $offset_count = 0;
  3054. var $limit;
  3055. var $column_names;
  3056. // }}}
  3057. // {{{ constructor: function __construct(&$db, &$result, $limit = 0, $offset = 0)
  3058. /**
  3059. * Constructor
  3060. */
  3061. function __construct(&$db, &$result, $limit = 0, $offset = 0)
  3062. {
  3063. $this->db =& $db;
  3064. $this->result =& $result;
  3065. $this->offset = $offset;
  3066. $this->limit = max(0, $limit - 1);
  3067. }
  3068. // }}}
  3069. // {{{ function setResultTypes($types)
  3070. /**
  3071. * Define the list of types to be associated with the columns of a given
  3072. * result set.
  3073. *
  3074. * This function may be called before invoking fetchRow(), fetchOne(),
  3075. * fetchCol() and fetchAll() so that the necessary data type
  3076. * conversions are performed on the data to be retrieved by them. If this
  3077. * function is not called, the type of all result set columns is assumed
  3078. * to be text, thus leading to not perform any conversions.
  3079. *
  3080. * @param array variable that lists the
  3081. * data types to be expected in the result set columns. If this array
  3082. * contains less types than the number of columns that are returned
  3083. * in the result set, the remaining columns are assumed to be of the
  3084. * type text. Currently, the types clob and blob are not fully
  3085. * supported.
  3086. *
  3087. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3088. *
  3089. * @access public
  3090. */
  3091. function setResultTypes($types)
  3092. {
  3093. $load = $this->db->loadModule('Datatype', null, true);
  3094. if (PEAR::isError($load)) {
  3095. return $load;
  3096. }
  3097. $types = $this->db->datatype->checkResultTypes($types);
  3098. if (PEAR::isError($types)) {
  3099. return $types;
  3100. }
  3101. $this->types = $types;
  3102. return MDB2_OK;
  3103. }
  3104. // }}}
  3105. // {{{ function seek($rownum = 0)
  3106. /**
  3107. * Seek to a specific row in a result set
  3108. *
  3109. * @param int number of the row where the data can be found
  3110. *
  3111. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3112. *
  3113. * @access public
  3114. */
  3115. function seek($rownum = 0)
  3116. {
  3117. $target_rownum = $rownum - 1;
  3118. if ($this->rownum > $target_rownum) {
  3119. return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  3120. 'seeking to previous rows not implemented', __FUNCTION__);
  3121. }
  3122. while ($this->rownum < $target_rownum) {
  3123. $this->fetchRow();
  3124. }
  3125. return MDB2_OK;
  3126. }
  3127. // }}}
  3128. // {{{ function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  3129. /**
  3130. * Fetch and return a row of data
  3131. *
  3132. * @param int how the array data should be indexed
  3133. * @param int number of the row where the data can be found
  3134. *
  3135. * @return int data array on success, a MDB2 error on failure
  3136. *
  3137. * @access public
  3138. */
  3139. function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  3140. {
  3141. $err =& $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  3142. 'method not implemented', __FUNCTION__);
  3143. return $err;
  3144. }
  3145. // }}}
  3146. // {{{ function fetchOne($colnum = 0)
  3147. /**
  3148. * fetch single column from the next row from a result set
  3149. *
  3150. * @param int the column number to fetch
  3151. * @param int number of the row where the data can be found
  3152. *
  3153. * @return string data on success, a MDB2 error on failure
  3154. *
  3155. * @access public
  3156. */
  3157. function fetchOne($colnum = 0, $rownum = null)
  3158. {
  3159. $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
  3160. $row = $this->fetchRow($fetchmode, $rownum);
  3161. if (!is_array($row) || PEAR::isError($row)) {
  3162. return $row;
  3163. }
  3164. if (!array_key_exists($colnum, $row)) {
  3165. return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
  3166. 'column is not defined in the result set: '.$colnum, __FUNCTION__);
  3167. }
  3168. return $row[$colnum];
  3169. }
  3170. // }}}
  3171. // {{{ function fetchCol($colnum = 0)
  3172. /**
  3173. * Fetch and return a column from the current row pointer position
  3174. *
  3175. * @param int the column number to fetch
  3176. *
  3177. * @return mixed data array on success, a MDB2 error on failure
  3178. *
  3179. * @access public
  3180. */
  3181. function fetchCol($colnum = 0)
  3182. {
  3183. $column = array();
  3184. $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
  3185. $row = $this->fetchRow($fetchmode);
  3186. if (is_array($row)) {
  3187. if (!array_key_exists($colnum, $row)) {
  3188. return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
  3189. 'column is not defined in the result set: '.$colnum, __FUNCTION__);
  3190. }
  3191. do {
  3192. $column[] = $row[$colnum];
  3193. } while (is_array($row = $this->fetchRow($fetchmode)));
  3194. }
  3195. if (PEAR::isError($row)) {
  3196. return $row;
  3197. }
  3198. return $column;
  3199. }
  3200. // }}}
  3201. // {{{ function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
  3202. /**
  3203. * Fetch and return all rows from the current row pointer position
  3204. *
  3205. * @param int $fetchmode the fetch mode to use:
  3206. * + MDB2_FETCHMODE_ORDERED
  3207. * + MDB2_FETCHMODE_ASSOC
  3208. * + MDB2_FETCHMODE_ORDERED | MDB2_FETCHMODE_FLIPPED
  3209. * + MDB2_FETCHMODE_ASSOC | MDB2_FETCHMODE_FLIPPED
  3210. * @param bool if set to true, the $all will have the first
  3211. * column as its first dimension
  3212. * @param bool used only when the query returns exactly
  3213. * two columns. If true, the values of the returned array will be
  3214. * one-element arrays instead of scalars.
  3215. * @param bool if true, the values of the returned array is
  3216. * wrapped in another array. If the same key value (in the first
  3217. * column) repeats itself, the values will be appended to this array
  3218. * instead of overwriting the existing values.
  3219. *
  3220. * @return mixed data array on success, a MDB2 error on failure
  3221. *
  3222. * @access public
  3223. * @see getAssoc()
  3224. */
  3225. function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false,
  3226. $force_array = false, $group = false)
  3227. {
  3228. $all = array();
  3229. $row = $this->fetchRow($fetchmode);
  3230. if (PEAR::isError($row)) {
  3231. return $row;
  3232. } elseif (!$row) {
  3233. return $all;
  3234. }
  3235. $shift_array = $rekey ? false : null;
  3236. if (!is_null($shift_array)) {
  3237. if (is_object($row)) {
  3238. $colnum = count(get_object_vars($row));
  3239. } else {
  3240. $colnum = count($row);
  3241. }
  3242. if ($colnum < 2) {
  3243. return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
  3244. 'rekey feature requires atleast 2 column', __FUNCTION__);
  3245. }
  3246. $shift_array = (!$force_array && $colnum == 2);
  3247. }
  3248. if ($rekey) {
  3249. do {
  3250. if (is_object($row)) {
  3251. $arr = get_object_vars($row);
  3252. $key = reset($arr);
  3253. unset($row->{$key});
  3254. } else {
  3255. if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
  3256. $key = reset($row);
  3257. unset($row[key($row)]);
  3258. } else {
  3259. $key = array_shift($row);
  3260. }
  3261. if ($shift_array) {
  3262. $row = array_shift($row);
  3263. }
  3264. }
  3265. if ($group) {
  3266. $all[$key][] = $row;
  3267. } else {
  3268. $all[$key] = $row;
  3269. }
  3270. } while (($row = $this->fetchRow($fetchmode)));
  3271. } elseif ($fetchmode & MDB2_FETCHMODE_FLIPPED) {
  3272. do {
  3273. foreach ($row as $key => $val) {
  3274. $all[$key][] = $val;
  3275. }
  3276. } while (($row = $this->fetchRow($fetchmode)));
  3277. } else {
  3278. do {
  3279. $all[] = $row;
  3280. } while (($row = $this->fetchRow($fetchmode)));
  3281. }
  3282. return $all;
  3283. }
  3284. // }}}
  3285. // {{{ function rowCount()
  3286. /**
  3287. * Returns the actual row number that was last fetched (count from 0)
  3288. * @return int
  3289. *
  3290. * @access public
  3291. */
  3292. function rowCount()
  3293. {
  3294. return $this->rownum + 1;
  3295. }
  3296. // }}}
  3297. // {{{ function numRows()
  3298. /**
  3299. * Returns the number of rows in a result object
  3300. *
  3301. * @return mixed MDB2 Error Object or the number of rows
  3302. *
  3303. * @access public
  3304. */
  3305. function numRows()
  3306. {
  3307. return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  3308. 'method not implemented', __FUNCTION__);
  3309. }
  3310. // }}}
  3311. // {{{ function nextResult()
  3312. /**
  3313. * Move the internal result pointer to the next available result
  3314. *
  3315. * @return true on success, false if there is no more result set or an error object on failure
  3316. *
  3317. * @access public
  3318. */
  3319. function nextResult()
  3320. {
  3321. return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  3322. 'method not implemented', __FUNCTION__);
  3323. }
  3324. // }}}
  3325. // {{{ function getColumnNames()
  3326. /**
  3327. * Retrieve the names of columns returned by the DBMS in a query result or
  3328. * from the cache.
  3329. *
  3330. * @param bool If set to true the values are the column names,
  3331. * otherwise the names of the columns are the keys.
  3332. * @return mixed Array variable that holds the names of columns or an
  3333. * MDB2 error on failure.
  3334. * Some DBMS may not return any columns when the result set
  3335. * does not contain any rows.
  3336. *
  3337. * @access public
  3338. */
  3339. function getColumnNames($flip = false)
  3340. {
  3341. if (!isset($this->column_names)) {
  3342. $result = $this->_getColumnNames();
  3343. if (PEAR::isError($result)) {
  3344. return $result;
  3345. }
  3346. $this->column_names = $result;
  3347. }
  3348. if ($flip) {
  3349. return array_flip($this->column_names);
  3350. }
  3351. return $this->column_names;
  3352. }
  3353. // }}}
  3354. // {{{ function _getColumnNames()
  3355. /**
  3356. * Retrieve the names of columns returned by the DBMS in a query result.
  3357. *
  3358. * @return mixed Array variable that holds the names of columns as keys
  3359. * or an MDB2 error on failure.
  3360. * Some DBMS may not return any columns when the result set
  3361. * does not contain any rows.
  3362. *
  3363. * @access private
  3364. */
  3365. function _getColumnNames()
  3366. {
  3367. return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  3368. 'method not implemented', __FUNCTION__);
  3369. }
  3370. // }}}
  3371. // {{{ function numCols()
  3372. /**
  3373. * Count the number of columns returned by the DBMS in a query result.
  3374. *
  3375. * @return mixed integer value with the number of columns, a MDB2 error
  3376. * on failure
  3377. *
  3378. * @access public
  3379. */
  3380. function numCols()
  3381. {
  3382. return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  3383. 'method not implemented', __FUNCTION__);
  3384. }
  3385. // }}}
  3386. // {{{ function getResource()
  3387. /**
  3388. * return the resource associated with the result object
  3389. *
  3390. * @return resource
  3391. *
  3392. * @access public
  3393. */
  3394. function getResource()
  3395. {
  3396. return $this->result;
  3397. }
  3398. // }}}
  3399. // {{{ function bindColumn($column, &$value, $type = null)
  3400. /**
  3401. * Set bind variable to a column.
  3402. *
  3403. * @param int column number or name
  3404. * @param mixed variable reference
  3405. * @param string specifies the type of the field
  3406. *
  3407. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3408. *
  3409. * @access public
  3410. */
  3411. function bindColumn($column, &$value, $type = null)
  3412. {
  3413. if (!is_numeric($column)) {
  3414. $column_names = $this->getColumnNames();
  3415. if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  3416. if ($this->db->options['field_case'] == CASE_LOWER) {
  3417. $column = strtolower($column);
  3418. } else {
  3419. $column = strtoupper($column);
  3420. }
  3421. }
  3422. $column = $column_names[$column];
  3423. }
  3424. $this->values[$column] =& $value;
  3425. if (!is_null($type)) {
  3426. $this->types[$column] = $type;
  3427. }
  3428. return MDB2_OK;
  3429. }
  3430. // }}}
  3431. // {{{ function _assignBindColumns($row)
  3432. /**
  3433. * Bind a variable to a value in the result row.
  3434. *
  3435. * @param array row data
  3436. *
  3437. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3438. *
  3439. * @access private
  3440. */
  3441. function _assignBindColumns($row)
  3442. {
  3443. $row = array_values($row);
  3444. foreach ($row as $column => $value) {
  3445. if (array_key_exists($column, $this->values)) {
  3446. $this->values[$column] = $value;
  3447. }
  3448. }
  3449. return MDB2_OK;
  3450. }
  3451. // }}}
  3452. // {{{ function free()
  3453. /**
  3454. * Free the internal resources associated with result.
  3455. *
  3456. * @return bool true on success, false if result is invalid
  3457. *
  3458. * @access public
  3459. */
  3460. function free()
  3461. {
  3462. $this->result = false;
  3463. return MDB2_OK;
  3464. }
  3465. // }}}
  3466. }
  3467. // }}}
  3468. // {{{ class MDB2_Row
  3469. /**
  3470. * The simple class that accepts row data as an array
  3471. *
  3472. * @package MDB2
  3473. * @category Database
  3474. * @author Lukas Smith <smith@pooteeweet.org>
  3475. */
  3476. class MDB2_Row
  3477. {
  3478. // {{{ constructor: function __construct(&$row)
  3479. /**
  3480. * constructor
  3481. *
  3482. * @param resource row data as array
  3483. */
  3484. function __construct(&$row)
  3485. {
  3486. foreach ($row as $key => $value) {
  3487. $this->$key = &$row[$key];
  3488. }
  3489. }
  3490. // }}}
  3491. }
  3492. // }}}
  3493. // {{{ class MDB2_Statement_Common
  3494. /**
  3495. * The common statement class for MDB2 statement objects
  3496. *
  3497. * @package MDB2
  3498. * @category Database
  3499. * @author Lukas Smith <smith@pooteeweet.org>
  3500. */
  3501. class MDB2_Statement_Common
  3502. {
  3503. // {{{ Variables (Properties)
  3504. var $db;
  3505. var $statement;
  3506. var $query;
  3507. var $result_types;
  3508. var $types;
  3509. var $values = array();
  3510. var $limit;
  3511. var $offset;
  3512. var $is_manip;
  3513. // }}}
  3514. // {{{ constructor: function __construct(&$db, &$statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
  3515. /**
  3516. * Constructor
  3517. */
  3518. function __construct(&$db, &$statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
  3519. {
  3520. $this->db =& $db;
  3521. $this->statement =& $statement;
  3522. $this->positions = $positions;
  3523. $this->query = $query;
  3524. $this->types = (array)$types;
  3525. $this->result_types = (array)$result_types;
  3526. $this->limit = $limit;
  3527. $this->is_manip = $is_manip;
  3528. $this->offset = $offset;
  3529. }
  3530. // }}}
  3531. // {{{ function MDB2_Statement_Common(&$db, &$statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
  3532. // {{{ function bindValue($parameter, &$value, $type = null)
  3533. /**
  3534. * Set the value of a parameter of a prepared query.
  3535. *
  3536. * @param int the order number of the parameter in the query
  3537. * statement. The order number of the first parameter is 1.
  3538. * @param mixed value that is meant to be assigned to specified
  3539. * parameter. The type of the value depends on the $type argument.
  3540. * @param string specifies the type of the field
  3541. *
  3542. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3543. *
  3544. * @access public
  3545. */
  3546. function bindValue($parameter, $value, $type = null)
  3547. {
  3548. if (!is_numeric($parameter)) {
  3549. $parameter = preg_replace('/^:(.*)$/', '\\1', $parameter);
  3550. }
  3551. if (!in_array($parameter, $this->positions)) {
  3552. return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  3553. 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
  3554. }
  3555. $this->values[$parameter] = $value;
  3556. if (!is_null($type)) {
  3557. $this->types[$parameter] = $type;
  3558. }
  3559. return MDB2_OK;
  3560. }
  3561. // }}}
  3562. // {{{ function bindValueArray($values, $types = null)
  3563. /**
  3564. * Set the values of multiple a parameter of a prepared query in bulk.
  3565. *
  3566. * @param array specifies all necessary information
  3567. * for bindValue() the array elements must use keys corresponding to
  3568. * the number of the position of the parameter.
  3569. * @param array specifies the types of the fields
  3570. *
  3571. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3572. *
  3573. * @access public
  3574. * @see bindParam()
  3575. */
  3576. function bindValueArray($values, $types = null)
  3577. {
  3578. $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
  3579. $parameters = array_keys($values);
  3580. foreach ($parameters as $key => $parameter) {
  3581. $err = $this->bindValue($parameter, $values[$parameter], $types[$key]);
  3582. if (PEAR::isError($err)) {
  3583. return $err;
  3584. }
  3585. }
  3586. return MDB2_OK;
  3587. }
  3588. // }}}
  3589. // {{{ function bindParam($parameter, &$value, $type = null)
  3590. /**
  3591. * Bind a variable to a parameter of a prepared query.
  3592. *
  3593. * @param int the order number of the parameter in the query
  3594. * statement. The order number of the first parameter is 1.
  3595. * @param mixed variable that is meant to be bound to specified
  3596. * parameter. The type of the value depends on the $type argument.
  3597. * @param string specifies the type of the field
  3598. *
  3599. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3600. *
  3601. * @access public
  3602. */
  3603. function bindParam($parameter, &$value, $type = null)
  3604. {
  3605. if (!is_numeric($parameter)) {
  3606. $parameter = preg_replace('/^:(.*)$/', '\\1', $parameter);
  3607. }
  3608. if (!in_array($parameter, $this->positions)) {
  3609. return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  3610. 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
  3611. }
  3612. $this->values[$parameter] =& $value;
  3613. if (!is_null($type)) {
  3614. $this->types[$parameter] = $type;
  3615. }
  3616. return MDB2_OK;
  3617. }
  3618. // }}}
  3619. // {{{ function bindParamArray(&$values, $types = null)
  3620. /**
  3621. * Bind the variables of multiple a parameter of a prepared query in bulk.
  3622. *
  3623. * @param array specifies all necessary information
  3624. * for bindParam() the array elements must use keys corresponding to
  3625. * the number of the position of the parameter.
  3626. * @param array specifies the types of the fields
  3627. *
  3628. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3629. *
  3630. * @access public
  3631. * @see bindParam()
  3632. */
  3633. function bindParamArray(&$values, $types = null)
  3634. {
  3635. $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
  3636. $parameters = array_keys($values);
  3637. foreach ($parameters as $key => $parameter) {
  3638. $err = $this->bindParam($parameter, $values[$parameter], $types[$key]);
  3639. if (PEAR::isError($err)) {
  3640. return $err;
  3641. }
  3642. }
  3643. return MDB2_OK;
  3644. }
  3645. // }}}
  3646. // {{{ function &execute($values = null, $result_class = true, $result_wrap_class = false)
  3647. /**
  3648. * Execute a prepared query statement.
  3649. *
  3650. * @param array specifies all necessary information
  3651. * for bindParam() the array elements must use keys corresponding to
  3652. * the number of the position of the parameter.
  3653. * @param mixed specifies which result class to use
  3654. * @param mixed specifies which class to wrap results in
  3655. *
  3656. * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  3657. *
  3658. * @access public
  3659. */
  3660. function &execute($values = null, $result_class = true, $result_wrap_class = false)
  3661. {
  3662. if (is_null($this->positions)) {
  3663. return $this->db->raiseError(MDB2_ERROR, null, null,
  3664. 'Prepared statement has already been freed', __FUNCTION__);
  3665. }
  3666. $values = (array)$values;
  3667. if (!empty($values)) {
  3668. $err = $this->bindValueArray($values);
  3669. if (PEAR::isError($err)) {
  3670. return $this->db->raiseError(MDB2_ERROR, null, null,
  3671. 'Binding Values failed with message: ' . $err->getMessage(), __FUNCTION__);
  3672. }
  3673. }
  3674. $result =& $this->_execute($result_class, $result_wrap_class);
  3675. return $result;
  3676. }
  3677. // }}}
  3678. // {{{ function &_execute($result_class = true, $result_wrap_class = false)
  3679. /**
  3680. * Execute a prepared query statement helper method.
  3681. *
  3682. * @param mixed specifies which result class to use
  3683. * @param mixed specifies which class to wrap results in
  3684. *
  3685. * @return mixed MDB2_Result or integer on success, a MDB2 error on failure
  3686. *
  3687. * @access private
  3688. */
  3689. function &_execute($result_class = true, $result_wrap_class = false)
  3690. {
  3691. $this->last_query = $this->query;
  3692. $query = '';
  3693. $last_position = 0;
  3694. foreach ($this->positions as $current_position => $parameter) {
  3695. if (!array_key_exists($parameter, $this->values)) {
  3696. return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  3697. 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
  3698. }
  3699. $value = $this->values[$parameter];
  3700. $query.= substr($this->query, $last_position, $current_position - $last_position);
  3701. if (!isset($value)) {
  3702. $value_quoted = 'NULL';
  3703. } else {
  3704. $type = !empty($this->types[$parameter]) ? $this->types[$parameter] : null;
  3705. $value_quoted = $this->db->quote($value, $type);
  3706. if (PEAR::isError($value_quoted)) {
  3707. return $value_quoted;
  3708. }
  3709. }
  3710. $query.= $value_quoted;
  3711. $last_position = $current_position + 1;
  3712. }
  3713. $query.= substr($this->query, $last_position);
  3714. $this->db->offset = $this->offset;
  3715. $this->db->limit = $this->limit;
  3716. if ($this->is_manip) {
  3717. $result = $this->db->exec($query);
  3718. } else {
  3719. $result =& $this->db->query($query, $this->result_types, $result_class, $result_wrap_class);
  3720. }
  3721. return $result;
  3722. }
  3723. // }}}
  3724. // {{{ function free()
  3725. /**
  3726. * Release resources allocated for the specified prepared query.
  3727. *
  3728. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3729. *
  3730. * @access public
  3731. */
  3732. function free()
  3733. {
  3734. if (is_null($this->positions)) {
  3735. return $this->db->raiseError(MDB2_ERROR, null, null,
  3736. 'Prepared statement has already been freed', __FUNCTION__);
  3737. }
  3738. $this->statement = null;
  3739. $this->positions = null;
  3740. $this->query = null;
  3741. $this->types = null;
  3742. $this->result_types = null;
  3743. $this->limit = null;
  3744. $this->is_manip = null;
  3745. $this->offset = null;
  3746. $this->values = null;
  3747. return MDB2_OK;
  3748. }
  3749. // }}}
  3750. }
  3751. // }}}
  3752. // {{{ class MDB2_Module_Common
  3753. /**
  3754. * The common modules class for MDB2 module objects
  3755. *
  3756. * @package MDB2
  3757. * @category Database
  3758. * @author Lukas Smith <smith@pooteeweet.org>
  3759. */
  3760. class MDB2_Module_Common
  3761. {
  3762. // {{{ Variables (Properties)
  3763. /**
  3764. * contains the key to the global MDB2 instance array of the associated
  3765. * MDB2 instance
  3766. *
  3767. * @var int
  3768. * @access protected
  3769. */
  3770. var $db_index;
  3771. // }}}
  3772. // {{{ constructor: function __construct($db_index)
  3773. /**
  3774. * Constructor
  3775. */
  3776. function __construct($db_index)
  3777. {
  3778. $this->db_index = $db_index;
  3779. }
  3780. // }}}
  3781. // {{{ function MDB2_Module_Common($db_index)
  3782. // }}}
  3783. // {{{ function &getDBInstance()
  3784. /**
  3785. * Get the instance of MDB2 associated with the module instance
  3786. *
  3787. * @return object MDB2 instance or a MDB2 error on failure
  3788. *
  3789. * @access public
  3790. */
  3791. function &getDBInstance()
  3792. {
  3793. if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
  3794. $result =& $GLOBALS['_MDB2_databases'][$this->db_index];
  3795. } else {
  3796. $result =& MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  3797. 'could not find MDB2 instance');
  3798. }
  3799. return $result;
  3800. }
  3801. // }}}
  3802. }
  3803. // }}}
  3804. // {{{ function MDB2_closeOpenTransactions()
  3805. /**
  3806. * Close any open transactions form persistent connections
  3807. *
  3808. * @return void
  3809. *
  3810. * @access public
  3811. */
  3812. function MDB2_closeOpenTransactions()
  3813. {
  3814. reset($GLOBALS['_MDB2_databases']);
  3815. while (next($GLOBALS['_MDB2_databases'])) {
  3816. $key = key($GLOBALS['_MDB2_databases']);
  3817. if ($GLOBALS['_MDB2_databases'][$key]->opened_persistent
  3818. && $GLOBALS['_MDB2_databases'][$key]->in_transaction
  3819. ) {
  3820. $GLOBALS['_MDB2_databases'][$key]->rollback();
  3821. }
  3822. }
  3823. }
  3824. // }}}
  3825. // {{{ function MDB2_defaultDebugOutput(&$db, $scope, $message, $is_manip = null)
  3826. /**
  3827. * default debug output handler
  3828. *
  3829. * @param object reference to an MDB2 database object
  3830. * @param string usually the method name that triggered the debug call:
  3831. * for example 'query', 'prepare', 'execute', 'parameters',
  3832. * 'beginTransaction', 'commit', 'rollback'
  3833. * @param string message that should be appended to the debug variable
  3834. * @param array contains context information about the debug() call
  3835. * common keys are: is_manip, time, result etc.
  3836. *
  3837. * @return void|string optionally return a modified message, this allows
  3838. * rewriting a query before being issued or prepared
  3839. *
  3840. * @access public
  3841. */
  3842. function MDB2_defaultDebugOutput(&$db, $scope, $message, $context = array())
  3843. {
  3844. $db->debug_output.= $scope.'('.$db->db_index.'): ';
  3845. $db->debug_output.= $message.$db->getOption('log_line_break');
  3846. return $message;
  3847. }
  3848. // }}}
  3849. ?>