Automatically exported from code.google.com/p/planningalerts
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

4211 lines
134 KiB

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