PageRenderTime 62ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/tags/1.3b/includes/pear/MDB2.php

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