DB.php 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
  3. // +----------------------------------------------------------------------+
  4. // | PHP Version 4 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1997-2004 The PHP Group |
  7. // +----------------------------------------------------------------------+
  8. // | This source file is subject to version 2.02 of the PHP license, |
  9. // | that is bundled with this package in the file LICENSE, and is |
  10. // | available at through the world-wide-web at |
  11. // | http://www.php.net/license/2_02.txt. |
  12. // | If you did not receive a copy of the PHP license and are unable to |
  13. // | obtain it through the world-wide-web, please send a note to |
  14. // | license@php.net so we can mail you a copy immediately. |
  15. // +----------------------------------------------------------------------+
  16. // | Authors: Stig Bakken <ssb@php.net> |
  17. // | Tomas V.V.Cox <cox@idecnet.com> |
  18. // | Maintainer: Daniel Convissor <danielc@php.net> |
  19. // +----------------------------------------------------------------------+
  20. //
  21. // $Id: DB.php,v 1.55 2004/02/18 23:07:09 danielc Exp $
  22. //
  23. // Database independent query interface.
  24. require_once 'PEAR.php';
  25. // {{{ constants
  26. // {{{ error codes
  27. /*
  28. * The method mapErrorCode in each DB_dbtype implementation maps
  29. * native error codes to one of these.
  30. *
  31. * If you add an error code here, make sure you also add a textual
  32. * version of it in DB::errorMessage().
  33. */
  34. define('DB_OK', 1);
  35. define('DB_ERROR', -1);
  36. define('DB_ERROR_SYNTAX', -2);
  37. define('DB_ERROR_CONSTRAINT', -3);
  38. define('DB_ERROR_NOT_FOUND', -4);
  39. define('DB_ERROR_ALREADY_EXISTS', -5);
  40. define('DB_ERROR_UNSUPPORTED', -6);
  41. define('DB_ERROR_MISMATCH', -7);
  42. define('DB_ERROR_INVALID', -8);
  43. define('DB_ERROR_NOT_CAPABLE', -9);
  44. define('DB_ERROR_TRUNCATED', -10);
  45. define('DB_ERROR_INVALID_NUMBER', -11);
  46. define('DB_ERROR_INVALID_DATE', -12);
  47. define('DB_ERROR_DIVZERO', -13);
  48. define('DB_ERROR_NODBSELECTED', -14);
  49. define('DB_ERROR_CANNOT_CREATE', -15);
  50. define('DB_ERROR_CANNOT_DELETE', -16);
  51. define('DB_ERROR_CANNOT_DROP', -17);
  52. define('DB_ERROR_NOSUCHTABLE', -18);
  53. define('DB_ERROR_NOSUCHFIELD', -19);
  54. define('DB_ERROR_NEED_MORE_DATA', -20);
  55. define('DB_ERROR_NOT_LOCKED', -21);
  56. define('DB_ERROR_VALUE_COUNT_ON_ROW', -22);
  57. define('DB_ERROR_INVALID_DSN', -23);
  58. define('DB_ERROR_CONNECT_FAILED', -24);
  59. define('DB_ERROR_EXTENSION_NOT_FOUND',-25);
  60. define('DB_ERROR_ACCESS_VIOLATION', -26);
  61. define('DB_ERROR_NOSUCHDB', -27);
  62. define('DB_ERROR_CONSTRAINT_NOT_NULL',-29);
  63. // }}}
  64. // {{{ prepared statement-related
  65. /*
  66. * These constants are used when storing information about prepared
  67. * statements (using the "prepare" method in DB_dbtype).
  68. *
  69. * The prepare/execute model in DB is mostly borrowed from the ODBC
  70. * extension, in a query the "?" character means a scalar parameter.
  71. * There are two extensions though, a "&" character means an opaque
  72. * parameter. An opaque parameter is simply a file name, the real
  73. * data are in that file (useful for putting uploaded files into your
  74. * database and such). The "!" char means a parameter that must be
  75. * left as it is.
  76. * They modify the quote behavoir:
  77. * DB_PARAM_SCALAR (?) => 'original string quoted'
  78. * DB_PARAM_OPAQUE (&) => 'string from file quoted'
  79. * DB_PARAM_MISC (!) => original string
  80. */
  81. define('DB_PARAM_SCALAR', 1);
  82. define('DB_PARAM_OPAQUE', 2);
  83. define('DB_PARAM_MISC', 3);
  84. // }}}
  85. // {{{ binary data-related
  86. /*
  87. * These constants define different ways of returning binary data
  88. * from queries. Again, this model has been borrowed from the ODBC
  89. * extension.
  90. *
  91. * DB_BINMODE_PASSTHRU sends the data directly through to the browser
  92. * when data is fetched from the database.
  93. * DB_BINMODE_RETURN lets you return data as usual.
  94. * DB_BINMODE_CONVERT returns data as well, only it is converted to
  95. * hex format, for example the string "123" would become "313233".
  96. */
  97. define('DB_BINMODE_PASSTHRU', 1);
  98. define('DB_BINMODE_RETURN', 2);
  99. define('DB_BINMODE_CONVERT', 3);
  100. // }}}
  101. // {{{ fetch modes
  102. /**
  103. * This is a special constant that tells DB the user hasn't specified
  104. * any particular get mode, so the default should be used.
  105. */
  106. define('DB_FETCHMODE_DEFAULT', 0);
  107. /**
  108. * Column data indexed by numbers, ordered from 0 and up
  109. */
  110. define('DB_FETCHMODE_ORDERED', 1);
  111. /**
  112. * Column data indexed by column names
  113. */
  114. define('DB_FETCHMODE_ASSOC', 2);
  115. /**
  116. * Column data as object properties
  117. */
  118. define('DB_FETCHMODE_OBJECT', 3);
  119. /**
  120. * For multi-dimensional results: normally the first level of arrays
  121. * is the row number, and the second level indexed by column number or name.
  122. * DB_FETCHMODE_FLIPPED switches this order, so the first level of arrays
  123. * is the column name, and the second level the row number.
  124. */
  125. define('DB_FETCHMODE_FLIPPED', 4);
  126. /* for compatibility */
  127. define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED);
  128. define('DB_GETMODE_ASSOC', DB_FETCHMODE_ASSOC);
  129. define('DB_GETMODE_FLIPPED', DB_FETCHMODE_FLIPPED);
  130. // }}}
  131. // {{{ tableInfo() && autoPrepare()-related
  132. /**
  133. * these are constants for the tableInfo-function
  134. * they are bitwised or'ed. so if there are more constants to be defined
  135. * in the future, adjust DB_TABLEINFO_FULL accordingly
  136. */
  137. define('DB_TABLEINFO_ORDER', 1);
  138. define('DB_TABLEINFO_ORDERTABLE', 2);
  139. define('DB_TABLEINFO_FULL', 3);
  140. /*
  141. * Used by autoPrepare()
  142. */
  143. define('DB_AUTOQUERY_INSERT', 1);
  144. define('DB_AUTOQUERY_UPDATE', 2);
  145. // }}}
  146. // {{{ portability modes
  147. /**
  148. * Portability: turn off all portability features.
  149. * @see DB_common::setOption()
  150. */
  151. define('DB_PORTABILITY_NONE', 0);
  152. /**
  153. * Portability: convert names of tables and fields to lower case
  154. * when using the get*(), fetch*() and tableInfo() methods.
  155. * @see DB_common::setOption()
  156. */
  157. define('DB_PORTABILITY_LOWERCASE', 1);
  158. /**
  159. * Portability: right trim the data output by get*() and fetch*().
  160. * @see DB_common::setOption()
  161. */
  162. define('DB_PORTABILITY_RTRIM', 2);
  163. /**
  164. * Portability: force reporting the number of rows deleted.
  165. * @see DB_common::setOption()
  166. */
  167. define('DB_PORTABILITY_DELETE_COUNT', 4);
  168. /**
  169. * Portability: enable hack that makes numRows() work in Oracle.
  170. * @see DB_common::setOption()
  171. */
  172. define('DB_PORTABILITY_NUMROWS', 8);
  173. /**
  174. * Portability: makes certain error messages in certain drivers compatible
  175. * with those from other DBMS's.
  176. *
  177. * + mysql, mysqli: change unique/primary key constraints
  178. * DB_ERROR_ALREADY_EXISTS -> DB_ERROR_CONSTRAINT
  179. *
  180. * + odbc(access): MS's ODBC driver reports 'no such field' as code
  181. * 07001, which means 'too few parameters.' When this option is on
  182. * that code gets mapped to DB_ERROR_NOSUCHFIELD.
  183. *
  184. * @see DB_common::setOption()
  185. */
  186. define('DB_PORTABILITY_ERRORS', 16);
  187. /**
  188. * Portability: convert null values to empty strings in data output by
  189. * get*() and fetch*().
  190. * @see DB_common::setOption()
  191. */
  192. define('DB_PORTABILITY_NULL_TO_EMPTY', 32);
  193. /**
  194. * Portability: turn on all portability features.
  195. * @see DB_common::setOption()
  196. */
  197. define('DB_PORTABILITY_ALL', 63);
  198. // }}}
  199. // }}}
  200. // {{{ class DB
  201. /**
  202. * The main "DB" class is simply a container class with some static
  203. * methods for creating DB objects as well as some utility functions
  204. * common to all parts of DB.
  205. *
  206. * The object model of DB is as follows (indentation means inheritance):
  207. *
  208. * DB The main DB class. This is simply a utility class
  209. * with some "static" methods for creating DB objects as
  210. * well as common utility functions for other DB classes.
  211. *
  212. * DB_common The base for each DB implementation. Provides default
  213. * | implementations (in OO lingo virtual methods) for
  214. * | the actual DB implementations as well as a bunch of
  215. * | query utility functions.
  216. * |
  217. * +-DB_mysql The DB implementation for MySQL. Inherits DB_common.
  218. * When calling DB::factory or DB::connect for MySQL
  219. * connections, the object returned is an instance of this
  220. * class.
  221. *
  222. * @package DB
  223. * @author Stig Bakken <ssb@php.net>
  224. * @author Tomas V.V.Cox <cox@idecnet.com>
  225. * @since PHP 4.0
  226. * @version $Id: DB.php,v 1.55 2004/02/18 23:07:09 danielc Exp $
  227. * @category Database
  228. */
  229. class DB
  230. {
  231. // {{{ &factory()
  232. /**
  233. * Create a new DB object for the specified database type.
  234. *
  235. * Allows creation of a DB_<driver> object from which the object's
  236. * methods can be utilized without actually connecting to a database.
  237. *
  238. * @param string $type database type, for example "mysql"
  239. * @param array $options associative array of option names and values
  240. *
  241. * @return object a new DB object. On error, an error object.
  242. *
  243. * @see DB_common::setOption()
  244. * @access public
  245. */
  246. function &factory($type, $options = false)
  247. {
  248. if (!is_array($options)) {
  249. $options = array('persistent' => $options);
  250. }
  251. if (isset($options['debug']) && $options['debug'] >= 2) {
  252. // expose php errors with sufficient debug level
  253. include_once "DB/{$type}.php";
  254. } else {
  255. @include_once "DB/{$type}.php";
  256. }
  257. $classname = "DB_${type}";
  258. if (!class_exists($classname)) {
  259. $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
  260. "Unable to include the DB/{$type}.php file",
  261. 'DB_Error', true);
  262. return $tmp;
  263. }
  264. @$obj =& new $classname;
  265. foreach ($options as $option => $value) {
  266. $test = $obj->setOption($option, $value);
  267. if (DB::isError($test)) {
  268. return $test;
  269. }
  270. }
  271. return $obj;
  272. }
  273. // }}}
  274. // {{{ &connect()
  275. /**
  276. * Create a new DB object and connect to the specified database.
  277. *
  278. * Example 1.
  279. * <code> <?php
  280. * require_once 'DB.php';
  281. *
  282. * $dsn = 'mysql://user:password@host/database'
  283. * $options = array(
  284. * 'debug' => 2,
  285. * 'portability' => DB_PORTABILITY_ALL,
  286. * );
  287. *
  288. * $dbh =& DB::connect($dsn, $options);
  289. * if (DB::isError($dbh)) {
  290. * die($dbh->getMessage());
  291. * }
  292. * ?></code>
  293. *
  294. * @param mixed $dsn string "data source name" or an array in the
  295. * format returned by DB::parseDSN()
  296. *
  297. * @param array $options an associative array of option names and
  298. * their values
  299. *
  300. * @return object a newly created DB connection object, or a DB
  301. * error object on error
  302. *
  303. * @see DB::parseDSN(), DB_common::setOption(), DB::isError()
  304. * @access public
  305. */
  306. function &connect($dsn, $options = array())
  307. {
  308. $dsninfo = DB::parseDSN($dsn);
  309. $type = $dsninfo['phptype'];
  310. if (!is_array($options)) {
  311. /*
  312. * For backwards compatibility. $options used to be boolean,
  313. * indicating whether the connection should be persistent.
  314. */
  315. $options = array('persistent' => $options);
  316. }
  317. if (isset($options['debug']) && $options['debug'] >= 2) {
  318. // expose php errors with sufficient debug level
  319. include_once "DB/${type}.php";
  320. } else {
  321. @include_once "DB/${type}.php";
  322. }
  323. $classname = "DB_${type}";
  324. if (!class_exists($classname)) {
  325. $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
  326. "Unable to include the DB/{$type}.php file for `$dsn'",
  327. 'DB_Error', true);
  328. return $tmp;
  329. }
  330. @$obj =& new $classname;
  331. foreach ($options as $option => $value) {
  332. $test = $obj->setOption($option, $value);
  333. if (DB::isError($test)) {
  334. return $test;
  335. }
  336. }
  337. $err = $obj->connect($dsninfo, $obj->getOption('persistent'));
  338. if (DB::isError($err)) {
  339. $err->addUserInfo($dsn);
  340. return $err;
  341. }
  342. return $obj;
  343. }
  344. // }}}
  345. // {{{ apiVersion()
  346. /**
  347. * Return the DB API version
  348. *
  349. * @return int the DB API version number
  350. *
  351. * @access public
  352. */
  353. function apiVersion()
  354. {
  355. return 2;
  356. }
  357. // }}}
  358. // {{{ isError()
  359. /**
  360. * Tell whether a result code from a DB method is an error
  361. *
  362. * @param int $value result code
  363. *
  364. * @return bool whether $value is an error
  365. *
  366. * @access public
  367. */
  368. function isError($value)
  369. {
  370. return is_a($value, 'DB_Error');
  371. }
  372. // }}}
  373. // {{{ isConnection()
  374. /**
  375. * Tell whether a value is a DB connection
  376. *
  377. * @param mixed $value value to test
  378. *
  379. * @return bool whether $value is a DB connection
  380. *
  381. * @access public
  382. */
  383. function isConnection($value)
  384. {
  385. return (is_object($value) &&
  386. is_subclass_of($value, 'db_common') &&
  387. method_exists($value, 'simpleQuery'));
  388. }
  389. // }}}
  390. // {{{ isManip()
  391. /**
  392. * Tell whether a query is a data manipulation query (insert,
  393. * update or delete) or a data definition query (create, drop,
  394. * alter, grant, revoke).
  395. *
  396. * @access public
  397. *
  398. * @param string $query the query
  399. *
  400. * @return boolean whether $query is a data manipulation query
  401. */
  402. function isManip($query)
  403. {
  404. $manips = 'INSERT|UPDATE|DELETE|'.'REPLACE|CREATE|DROP|'.
  405. 'ALTER|GRANT|REVOKE|'.'LOCK|UNLOCK';
  406. if (preg_match('/^\s*"?('.$manips.')\s+/i', $query)) {
  407. return true;
  408. }
  409. return false;
  410. }
  411. // }}}
  412. // {{{ errorMessage()
  413. /**
  414. * Return a textual error message for a DB error code
  415. *
  416. * @param integer $value error code
  417. *
  418. * @return string error message, or false if the error code was
  419. * not recognized
  420. */
  421. function errorMessage($value)
  422. {
  423. static $errorMessages;
  424. if (!isset($errorMessages)) {
  425. $errorMessages = array(
  426. DB_ERROR => 'unknown error',
  427. DB_ERROR_ALREADY_EXISTS => 'already exists',
  428. DB_ERROR_CANNOT_CREATE => 'can not create',
  429. DB_ERROR_CANNOT_DELETE => 'can not delete',
  430. DB_ERROR_CANNOT_DROP => 'can not drop',
  431. DB_ERROR_CONSTRAINT => 'constraint violation',
  432. DB_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',
  433. DB_ERROR_DIVZERO => 'division by zero',
  434. DB_ERROR_INVALID => 'invalid',
  435. DB_ERROR_INVALID_DATE => 'invalid date or time',
  436. DB_ERROR_INVALID_NUMBER => 'invalid number',
  437. DB_ERROR_MISMATCH => 'mismatch',
  438. DB_ERROR_NODBSELECTED => 'no database selected',
  439. DB_ERROR_NOSUCHFIELD => 'no such field',
  440. DB_ERROR_NOSUCHTABLE => 'no such table',
  441. DB_ERROR_NOT_CAPABLE => 'DB backend not capable',
  442. DB_ERROR_NOT_FOUND => 'not found',
  443. DB_ERROR_NOT_LOCKED => 'not locked',
  444. DB_ERROR_SYNTAX => 'syntax error',
  445. DB_ERROR_UNSUPPORTED => 'not supported',
  446. DB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
  447. DB_ERROR_INVALID_DSN => 'invalid DSN',
  448. DB_ERROR_CONNECT_FAILED => 'connect failed',
  449. DB_OK => 'no error',
  450. DB_ERROR_NEED_MORE_DATA => 'insufficient data supplied',
  451. DB_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
  452. DB_ERROR_NOSUCHDB => 'no such database',
  453. DB_ERROR_ACCESS_VIOLATION => 'insufficient permissions',
  454. DB_ERROR_TRUNCATED => 'truncated'
  455. );
  456. }
  457. if (DB::isError($value)) {
  458. $value = $value->getCode();
  459. }
  460. return isset($errorMessages[$value]) ? $errorMessages[$value] : $errorMessages[DB_ERROR];
  461. }
  462. // }}}
  463. // {{{ parseDSN()
  464. /**
  465. * Parse a data source name.
  466. *
  467. * Additional keys can be added by appending a URI query string to the
  468. * end of the DSN.
  469. *
  470. * The format of the supplied DSN is in its fullest form:
  471. * <code>
  472. * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
  473. * </code>
  474. *
  475. * Most variations are allowed:
  476. * <code>
  477. * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
  478. * phptype://username:password@hostspec/database_name
  479. * phptype://username:password@hostspec
  480. * phptype://username@hostspec
  481. * phptype://hostspec/database
  482. * phptype://hostspec
  483. * phptype(dbsyntax)
  484. * phptype
  485. * </code>
  486. *
  487. * @param string $dsn Data Source Name to be parsed
  488. *
  489. * @return array an associative array with the following keys:
  490. * + phptype: Database backend used in PHP (mysql, odbc etc.)
  491. * + dbsyntax: Database used with regards to SQL syntax etc.
  492. * + protocol: Communication protocol to use (tcp, unix etc.)
  493. * + hostspec: Host specification (hostname[:port])
  494. * + database: Database to use on the DBMS server
  495. * + username: User name for login
  496. * + password: Password for login
  497. *
  498. * @author Tomas V.V.Cox <cox@idecnet.com>
  499. */
  500. function parseDSN($dsn)
  501. {
  502. $parsed = array(
  503. 'phptype' => false,
  504. 'dbsyntax' => false,
  505. 'username' => false,
  506. 'password' => false,
  507. 'protocol' => false,
  508. 'hostspec' => false,
  509. 'port' => false,
  510. 'socket' => false,
  511. 'database' => false,
  512. );
  513. if (is_array($dsn)) {
  514. $dsn = array_merge($parsed, $dsn);
  515. if (!$dsn['dbsyntax']) {
  516. $dsn['dbsyntax'] = $dsn['phptype'];
  517. }
  518. return $dsn;
  519. }
  520. // Find phptype and dbsyntax
  521. if (($pos = strpos($dsn, '://')) !== false) {
  522. $str = substr($dsn, 0, $pos);
  523. $dsn = substr($dsn, $pos + 3);
  524. } else {
  525. $str = $dsn;
  526. $dsn = NULL;
  527. }
  528. // Get phptype and dbsyntax
  529. // $str => phptype(dbsyntax)
  530. if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
  531. $parsed['phptype'] = $arr[1];
  532. $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
  533. } else {
  534. $parsed['phptype'] = $str;
  535. $parsed['dbsyntax'] = $str;
  536. }
  537. if (!count($dsn)) {
  538. return $parsed;
  539. }
  540. // Get (if found): username and password
  541. // $dsn => username:password@protocol+hostspec/database
  542. if (($at = strrpos($dsn,'@')) !== false) {
  543. $str = substr($dsn, 0, $at);
  544. $dsn = substr($dsn, $at + 1);
  545. if (($pos = strpos($str, ':')) !== false) {
  546. $parsed['username'] = rawurldecode(substr($str, 0, $pos));
  547. $parsed['password'] = rawurldecode(substr($str, $pos + 1));
  548. } else {
  549. $parsed['username'] = rawurldecode($str);
  550. }
  551. }
  552. // Find protocol and hostspec
  553. // $dsn => proto(proto_opts)/database
  554. if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
  555. $proto = $match[1];
  556. $proto_opts = $match[2] ? $match[2] : false;
  557. $dsn = $match[3];
  558. // $dsn => protocol+hostspec/database (old format)
  559. } else {
  560. if (strpos($dsn, '+') !== false) {
  561. list($proto, $dsn) = explode('+', $dsn, 2);
  562. }
  563. if (strpos($dsn, '/') !== false) {
  564. list($proto_opts, $dsn) = explode('/', $dsn, 2);
  565. } else {
  566. $proto_opts = $dsn;
  567. $dsn = null;
  568. }
  569. }
  570. // process the different protocol options
  571. $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
  572. $proto_opts = rawurldecode($proto_opts);
  573. if ($parsed['protocol'] == 'tcp') {
  574. if (strpos($proto_opts, ':') !== false) {
  575. list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
  576. } else {
  577. $parsed['hostspec'] = $proto_opts;
  578. }
  579. } elseif ($parsed['protocol'] == 'unix') {
  580. $parsed['socket'] = $proto_opts;
  581. }
  582. // Get dabase if any
  583. // $dsn => database
  584. if ($dsn) {
  585. // /database
  586. if (($pos = strpos($dsn, '?')) === false) {
  587. $parsed['database'] = $dsn;
  588. // /database?param1=value1&param2=value2
  589. } else {
  590. $parsed['database'] = substr($dsn, 0, $pos);
  591. $dsn = substr($dsn, $pos + 1);
  592. if (strpos($dsn, '&') !== false) {
  593. $opts = explode('&', $dsn);
  594. } else { // database?param1=value1
  595. $opts = array($dsn);
  596. }
  597. foreach ($opts as $opt) {
  598. list($key, $value) = explode('=', $opt);
  599. if (!isset($parsed[$key])) {
  600. // don't allow params overwrite
  601. $parsed[$key] = rawurldecode($value);
  602. }
  603. }
  604. }
  605. }
  606. return $parsed;
  607. }
  608. // }}}
  609. // {{{ assertExtension()
  610. /**
  611. * Load a PHP database extension if it is not loaded already.
  612. *
  613. * @access public
  614. *
  615. * @param string $name the base name of the extension (without the .so or
  616. * .dll suffix)
  617. *
  618. * @return boolean true if the extension was already or successfully
  619. * loaded, false if it could not be loaded
  620. */
  621. function assertExtension($name)
  622. {
  623. if (!extension_loaded($name)) {
  624. $dlext = OS_WINDOWS ? '.dll' : '.so';
  625. $dlprefix = OS_WINDOWS ? 'php_' : '';
  626. @dl($dlprefix . $name . $dlext);
  627. return extension_loaded($name);
  628. }
  629. return true;
  630. }
  631. // }}}
  632. }
  633. // }}}
  634. // {{{ class DB_Error
  635. /**
  636. * DB_Error implements a class for reporting portable database error
  637. * messages.
  638. *
  639. * @package DB
  640. * @author Stig Bakken <ssb@php.net>
  641. */
  642. class DB_Error extends PEAR_Error
  643. {
  644. // {{{ constructor
  645. /**
  646. * DB_Error constructor.
  647. *
  648. * @param mixed $code DB error code, or string with error message.
  649. * @param integer $mode what "error mode" to operate in
  650. * @param integer $level what error level to use for $mode & PEAR_ERROR_TRIGGER
  651. * @param mixed $debuginfo additional debug info, such as the last query
  652. *
  653. * @access public
  654. *
  655. * @see PEAR_Error
  656. */
  657. function DB_Error($code = DB_ERROR, $mode = PEAR_ERROR_RETURN,
  658. $level = E_USER_NOTICE, $debuginfo = null)
  659. {
  660. if (is_int($code)) {
  661. $this->PEAR_Error('DB Error: ' . DB::errorMessage($code), $code, $mode, $level, $debuginfo);
  662. } else {
  663. $this->PEAR_Error("DB Error: $code", DB_ERROR, $mode, $level, $debuginfo);
  664. }
  665. }
  666. // }}}
  667. }
  668. // }}}
  669. // {{{ class DB_result
  670. /**
  671. * This class implements a wrapper for a DB result set.
  672. * A new instance of this class will be returned by the DB implementation
  673. * after processing a query that returns data.
  674. *
  675. * @package DB
  676. * @author Stig Bakken <ssb@php.net>
  677. */
  678. class DB_result
  679. {
  680. // {{{ properties
  681. var $dbh;
  682. var $result;
  683. var $row_counter = null;
  684. /**
  685. * for limit queries, the row to start fetching
  686. * @var integer
  687. */
  688. var $limit_from = null;
  689. /**
  690. * for limit queries, the number of rows to fetch
  691. * @var integer
  692. */
  693. var $limit_count = null;
  694. // }}}
  695. // {{{ constructor
  696. /**
  697. * DB_result constructor.
  698. * @param resource &$dbh DB object reference
  699. * @param resource $result result resource id
  700. * @param array $options assoc array with optional result options
  701. */
  702. function DB_result(&$dbh, $result, $options = array())
  703. {
  704. $this->dbh = &$dbh;
  705. $this->result = $result;
  706. foreach ($options as $key => $value) {
  707. $this->setOption($key, $value);
  708. }
  709. $this->limit_type = $dbh->features['limit'];
  710. $this->autofree = $dbh->options['autofree'];
  711. $this->fetchmode = $dbh->fetchmode;
  712. $this->fetchmode_object_class = $dbh->fetchmode_object_class;
  713. }
  714. function setOption($key, $value = null)
  715. {
  716. switch ($key) {
  717. case 'limit_from':
  718. $this->limit_from = $value; break;
  719. case 'limit_count':
  720. $this->limit_count = $value; break;
  721. }
  722. }
  723. // }}}
  724. // {{{ fetchRow()
  725. /**
  726. * Fetch a row of data and return it by reference into an array.
  727. *
  728. * The type of array returned can be controlled either by setting this
  729. * method's <var>$fetchmode</var> parameter or by changing the default
  730. * fetch mode setFetchMode() before calling this method.
  731. *
  732. * There are two options for standardizing the information returned
  733. * from databases, ensuring their values are consistent when changing
  734. * DBMS's. These portability options can be turned on when creating a
  735. * new DB object or by using setOption().
  736. *
  737. * + <samp>DB_PORTABILITY_LOWERCASE</samp>
  738. * convert names of fields to lower case
  739. *
  740. * + <samp>DB_PORTABILITY_RTRIM</samp>
  741. * right trim the data
  742. *
  743. * @param int $fetchmode how the resulting array should be indexed
  744. * @param int $rownum the row number to fetch
  745. *
  746. * @return array a row of data, NULL on no more rows or PEAR_Error
  747. * object on error
  748. *
  749. * @see DB_common::setOption(), DB_common::setFetchMode()
  750. * @access public
  751. */
  752. function &fetchRow($fetchmode = DB_FETCHMODE_DEFAULT, $rownum=null)
  753. {
  754. if ($fetchmode === DB_FETCHMODE_DEFAULT) {
  755. $fetchmode = $this->fetchmode;
  756. }
  757. if ($fetchmode === DB_FETCHMODE_OBJECT) {
  758. $fetchmode = DB_FETCHMODE_ASSOC;
  759. $object_class = $this->fetchmode_object_class;
  760. }
  761. if ($this->limit_from !== null) {
  762. if ($this->row_counter === null) {
  763. $this->row_counter = $this->limit_from;
  764. // Skip rows
  765. if ($this->limit_type == false) {
  766. $i = 0;
  767. while ($i++ < $this->limit_from) {
  768. $this->dbh->fetchInto($this->result, $arr, $fetchmode);
  769. }
  770. }
  771. }
  772. if ($this->row_counter >= (
  773. $this->limit_from + $this->limit_count))
  774. {
  775. if ($this->autofree) {
  776. $this->free();
  777. }
  778. $tmp = null;
  779. return $tmp;
  780. }
  781. if ($this->limit_type == 'emulate') {
  782. $rownum = $this->row_counter;
  783. }
  784. $this->row_counter++;
  785. }
  786. $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
  787. if ($res === DB_OK) {
  788. if (isset($object_class)) {
  789. // default mode specified in DB_common::fetchmode_object_class property
  790. if ($object_class == 'stdClass') {
  791. $arr = (object) $arr;
  792. } else {
  793. $arr = &new $object_class($arr);
  794. }
  795. }
  796. return $arr;
  797. }
  798. if ($res == null && $this->autofree) {
  799. $this->free();
  800. }
  801. return $res;
  802. }
  803. // }}}
  804. // {{{ fetchInto()
  805. /**
  806. * Fetch a row of data into an array which is passed by reference.
  807. *
  808. * The type of array returned can be controlled either by setting this
  809. * method's <var>$fetchmode</var> parameter or by changing the default
  810. * fetch mode setFetchMode() before calling this method.
  811. *
  812. * There are two options for standardizing the information returned
  813. * from databases, ensuring their values are consistent when changing
  814. * DBMS's. These portability options can be turned on when creating a
  815. * new DB object or by using setOption().
  816. *
  817. * + <samp>DB_PORTABILITY_LOWERCASE</samp>
  818. * convert names of fields to lower case
  819. *
  820. * + <samp>DB_PORTABILITY_RTRIM</samp>
  821. * right trim the data
  822. *
  823. * @param array &$arr (reference) array where data from the row
  824. * should be placed
  825. * @param int $fetchmode how the resulting array should be indexed
  826. * @param int $rownum the row number to fetch
  827. *
  828. * @return mixed DB_OK on success, NULL on no more rows or
  829. * a DB_Error object on error
  830. *
  831. * @see DB_common::setOption(), DB_common::setFetchMode()
  832. * @access public
  833. */
  834. function fetchInto(&$arr, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum=null)
  835. {
  836. if ($fetchmode === DB_FETCHMODE_DEFAULT) {
  837. $fetchmode = $this->fetchmode;
  838. }
  839. if ($fetchmode === DB_FETCHMODE_OBJECT) {
  840. $fetchmode = DB_FETCHMODE_ASSOC;
  841. $object_class = $this->fetchmode_object_class;
  842. }
  843. if ($this->limit_from !== null) {
  844. if ($this->row_counter === null) {
  845. $this->row_counter = $this->limit_from;
  846. // Skip rows
  847. if ($this->limit_type == false) {
  848. $i = 0;
  849. while ($i++ < $this->limit_from) {
  850. $this->dbh->fetchInto($this->result, $arr, $fetchmode);
  851. }
  852. }
  853. }
  854. if ($this->row_counter >= (
  855. $this->limit_from + $this->limit_count))
  856. {
  857. if ($this->autofree) {
  858. $this->free();
  859. }
  860. return null;
  861. }
  862. if ($this->limit_type == 'emulate') {
  863. $rownum = $this->row_counter;
  864. }
  865. $this->row_counter++;
  866. }
  867. $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
  868. if ($res === DB_OK) {
  869. if (isset($object_class)) {
  870. // default mode specified in DB_common::fetchmode_object_class property
  871. if ($object_class == 'stdClass') {
  872. $arr = (object) $arr;
  873. } else {
  874. $arr = new $object_class($arr);
  875. }
  876. }
  877. return DB_OK;
  878. }
  879. if ($res == null && $this->autofree) {
  880. $this->free();
  881. }
  882. return $res;
  883. }
  884. // }}}
  885. // {{{ numCols()
  886. /**
  887. * Get the the number of columns in a result set.
  888. *
  889. * @return int the number of columns, or a DB error
  890. *
  891. * @access public
  892. */
  893. function numCols()
  894. {
  895. return $this->dbh->numCols($this->result);
  896. }
  897. // }}}
  898. // {{{ numRows()
  899. /**
  900. * Get the number of rows in a result set.
  901. *
  902. * @return int the number of rows, or a DB error
  903. *
  904. * @access public
  905. */
  906. function numRows()
  907. {
  908. return $this->dbh->numRows($this->result);
  909. }
  910. // }}}
  911. // {{{ nextResult()
  912. /**
  913. * Get the next result if a batch of queries was executed.
  914. *
  915. * @return bool true if a new result is available or false if not.
  916. *
  917. * @access public
  918. */
  919. function nextResult()
  920. {
  921. return $this->dbh->nextResult($this->result);
  922. }
  923. // }}}
  924. // {{{ free()
  925. /**
  926. * Frees the resources allocated for this result set.
  927. * @return int error code
  928. *
  929. * @access public
  930. */
  931. function free()
  932. {
  933. $err = $this->dbh->freeResult($this->result);
  934. if(DB::isError($err)) {
  935. return $err;
  936. }
  937. $this->result = false;
  938. return true;
  939. }
  940. // }}}
  941. // {{{ tableInfo()
  942. /**
  943. * @deprecated
  944. * @internal
  945. * @see DB_common::tableInfo()
  946. */
  947. function tableInfo($mode = null)
  948. {
  949. if (is_string($mode)) {
  950. return $this->dbh->raiseError(DB_ERROR_NEED_MORE_DATA);
  951. }
  952. return $this->dbh->tableInfo($this, $mode);
  953. }
  954. // }}}
  955. // {{{ getRowCounter()
  956. /**
  957. * returns the actual row number
  958. * @return integer
  959. */
  960. function getRowCounter()
  961. {
  962. return $this->row_counter;
  963. }
  964. // }}}
  965. }
  966. // }}}
  967. // {{{ class DB_Row
  968. /**
  969. * Pear DB Row Object
  970. * @see DB_common::setFetchMode()
  971. */
  972. class DB_row
  973. {
  974. // {{{ constructor
  975. /**
  976. * constructor
  977. *
  978. * @param resource row data as array
  979. */
  980. function DB_row(&$arr)
  981. {
  982. foreach ($arr as $key => $value) {
  983. $this->$key = &$arr[$key];
  984. }
  985. }
  986. // }}}
  987. }
  988. // }}}
  989. /*
  990. * Local variables:
  991. * tab-width: 4
  992. * c-basic-offset: 4
  993. * End:
  994. */
  995. ?>