2 /* vim: set expandtab tabstop=4 shiftwidth=4: */
3 // +----------------------------------------------------------------------+
5 // +----------------------------------------------------------------------+
6 // | Copyright (c) 1997-2002 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@fast.no> |
17 // | Tomas V.V.Cox <cox@idecnet.com> |
18 // +----------------------------------------------------------------------+
21 // Based on code from the PHP CVS repository. The only modifications made
22 // have been modification of the include paths.
24 rcs_id('$Id: DB.php,v 1.1 2002-01-28 04:01:56 dairiki Exp $');
25 rcs_id('From Pear CVS: Id: DB.php,v 1.83 2002/01/19 07:46:23 cox Exp');
27 // Database independent query interface.
30 require_once "lib/pear/PEAR.php";
33 * The method mapErrorCode in each DB_dbtype implementation maps
34 * native error codes to one of these.
36 * If you add an error code here, make sure you also add a textual
37 * version of it in DB::errorMessage().
41 define("DB_ERROR", -1);
42 define("DB_ERROR_SYNTAX", -2);
43 define("DB_ERROR_CONSTRAINT", -3);
44 define("DB_ERROR_NOT_FOUND", -4);
45 define("DB_ERROR_ALREADY_EXISTS", -5);
46 define("DB_ERROR_UNSUPPORTED", -6);
47 define("DB_ERROR_MISMATCH", -7);
48 define("DB_ERROR_INVALID", -8);
49 define("DB_ERROR_NOT_CAPABLE", -9);
50 define("DB_ERROR_TRUNCATED", -10);
51 define("DB_ERROR_INVALID_NUMBER", -11);
52 define("DB_ERROR_INVALID_DATE", -12);
53 define("DB_ERROR_DIVZERO", -13);
54 define("DB_ERROR_NODBSELECTED", -14);
55 define("DB_ERROR_CANNOT_CREATE", -15);
56 define("DB_ERROR_CANNOT_DELETE", -16);
57 define("DB_ERROR_CANNOT_DROP", -17);
58 define("DB_ERROR_NOSUCHTABLE", -18);
59 define("DB_ERROR_NOSUCHFIELD", -19);
60 define("DB_ERROR_NEED_MORE_DATA", -20);
61 define("DB_ERROR_NOT_LOCKED", -21);
62 define("DB_ERROR_VALUE_COUNT_ON_ROW", -22);
63 define("DB_ERROR_INVALID_DSN", -23);
64 define("DB_ERROR_CONNECT_FAILED", -24);
65 define("DB_ERROR_EXTENSION_NOT_FOUND",-25);
68 * Warnings are not detected as errors by DB::isError(), and are not
69 * fatal. You can detect whether an error is in fact a warning with
73 define('DB_WARNING', -1000);
74 define('DB_WARNING_READ_ONLY', -1001);
77 * These constants are used when storing information about prepared
78 * statements (using the "prepare" method in DB_dbtype).
80 * The prepare/execute model in DB is mostly borrowed from the ODBC
81 * extension, in a query the "?" character means a scalar parameter.
82 * There are two extensions though, a "&" character means an opaque
83 * parameter. An opaque parameter is simply a file name, the real
84 * data are in that file (useful for putting uploaded files into your
85 * database and such). The "!" char means a parameter that must be
87 * They modify the quote behavoir:
88 * DB_PARAM_SCALAR (?) => 'original string quoted'
89 * DB_PARAM_OPAQUE (&) => 'string from file quoted'
90 * DB_PARAM_MISC (!) => original string
93 define('DB_PARAM_SCALAR', 1);
94 define('DB_PARAM_OPAQUE', 2);
95 define('DB_PARAM_MISC', 3);
98 * These constants define different ways of returning binary data
99 * from queries. Again, this model has been borrowed from the ODBC
102 * DB_BINMODE_PASSTHRU sends the data directly through to the browser
103 * when data is fetched from the database.
104 * DB_BINMODE_RETURN lets you return data as usual.
105 * DB_BINMODE_CONVERT returns data as well, only it is converted to
106 * hex format, for example the string "123" would become "313233".
109 define('DB_BINMODE_PASSTHRU', 1);
110 define('DB_BINMODE_RETURN', 2);
111 define('DB_BINMODE_CONVERT', 3);
114 * This is a special constant that tells DB the user hasn't specified
115 * any particular get mode, so the default should be used.
118 define('DB_FETCHMODE_DEFAULT', 0);
121 * Column data indexed by numbers, ordered from 0 and up
124 define('DB_FETCHMODE_ORDERED', 1);
127 * Column data indexed by column names
130 define('DB_FETCHMODE_ASSOC', 2);
133 * Column data as object properties
136 define('DB_FETCHMODE_OBJECT', 3);
139 * For multi-dimensional results: normally the first level of arrays
140 * is the row number, and the second level indexed by column number or name.
141 * DB_FETCHMODE_FLIPPED switches this order, so the first level of arrays
142 * is the column name, and the second level the row number.
145 define('DB_FETCHMODE_FLIPPED', 4);
147 /* for compatibility */
149 define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED);
150 define('DB_GETMODE_ASSOC', DB_FETCHMODE_ASSOC);
151 define('DB_GETMODE_FLIPPED', DB_FETCHMODE_FLIPPED);
154 * these are constants for the tableInfo-function
155 * they are bitwised or'ed. so if there are more constants to be defined
156 * in the future, adjust DB_TABLEINFO_FULL accordingly
159 define('DB_TABLEINFO_ORDER', 1);
160 define('DB_TABLEINFO_ORDERTABLE', 2);
161 define('DB_TABLEINFO_FULL', 3);
165 * The main "DB" class is simply a container class with some static
166 * methods for creating DB objects as well as some utility functions
167 * common to all parts of DB.
169 * The object model of DB is as follows (indentation means inheritance):
171 * DB The main DB class. This is simply a utility class
172 * with some "static" methods for creating DB objects as
173 * well as common utility functions for other DB classes.
175 * DB_common The base for each DB implementation. Provides default
176 * | implementations (in OO lingo virtual methods) for
177 * | the actual DB implementations as well as a bunch of
178 * | query utility functions.
180 * +-DB_mysql The DB implementation for MySQL. Inherits DB_common.
181 * When calling DB::factory or DB::connect for MySQL
182 * connections, the object returned is an instance of this
187 * @author Stig Bakken <ssb@fast.no>
194 * Create a new DB connection object for the specified database
197 * @param string $type database type, for example "mysql"
199 * @return mixed a newly created DB object, or a DB error code on
205 function &factory($type)
207 @include_once("lib/pear/DB/${type}.php");
209 $classname = "DB_${type}";
211 if (!class_exists($classname)) {
212 return PEAR::raiseError(null, DB_ERROR_NOT_FOUND,
213 null, null, null, 'DB_Error', true);
216 @$obj =& new $classname;
222 * Create a new DB connection object and connect to the specified
225 * @param mixed $dsn "data source name", see the DB::parseDSN
226 * method for a description of the dsn format. Can also be
227 * specified as an array of the format returned by DB::parseDSN.
229 * @param mixed $options An associative array of option names and
230 * their values. For backwards compatibility, this parameter may
231 * also be a boolean that tells whether the connection should be
232 * persistent. See DB_common::setOption for more information on
233 * connection options.
235 * @return mixed a newly created DB connection object, or a DB
236 * error object on error
240 * @see DB_common::setOption
242 function &connect($dsn, $options = false)
244 if (is_array($dsn)) {
247 $dsninfo = DB::parseDSN($dsn);
249 $type = $dsninfo["phptype"];
251 if (is_array($options) && isset($options["debug"]) &&
252 $options["debug"] >= 2) {
253 // expose php errors with sufficient debug level
254 include_once "lib/pear/DB/${type}.php";
256 @include_once "lib/pear/DB/${type}.php";
259 $classname = "DB_${type}";
260 if (!class_exists($classname)) {
261 return PEAR::raiseError(null, DB_ERROR_NOT_FOUND,
262 null, null, null, 'DB_Error', true);
265 @$obj =& new $classname;
267 if (is_array($options)) {
268 foreach ($options as $option => $value) {
269 $test = $obj->setOption($option, $value);
270 if (DB::isError($test)) {
275 $obj->setOption('persistent', $options);
277 $err = $obj->connect($dsninfo, $obj->getOption('persistent'));
279 if (DB::isError($err)) {
280 $err->addUserInfo($dsn);
288 * Return the DB API version
290 * @return int the DB API version number
294 function apiVersion()
300 * Tell whether a result code from a DB method is an error
302 * @param $value int result code
304 * @return bool whether $value is an error
308 function isError($value)
310 return (is_object($value) &&
311 (get_class($value) == 'db_error' ||
312 is_subclass_of($value, 'db_error')));
316 * Tell whether a query is a data manipulation query (insert,
317 * update or delete) or a data definition query (create, drop,
318 * alter, grant, revoke).
322 * @param string $query the query
324 * @return boolean whether $query is a data manipulation query
326 function isManip($query)
328 $manips = 'INSERT|UPDATE|DELETE|'.'REPLACE|CREATE|DROP|'.
329 'ALTER|GRANT|REVOKE|'.'LOCK|UNLOCK';
330 if (preg_match('/^\s*"?('.$manips.')\s+/i', $query)) {
337 * Tell whether a result code from a DB method is a warning.
338 * Warnings differ from errors in that they are generated by DB,
341 * @param mixed $value result value
343 * @return boolean whether $value is a warning
347 function isWarning($value)
349 return (is_object($value) &&
350 (get_class($value) == "db_warning" ||
351 is_subclass_of($value, "db_warning")));
355 * Return a textual error message for a DB error code
357 * @param integer $value error code
359 * @return string error message, or false if the error code was
362 function errorMessage($value)
364 static $errorMessages;
365 if (!isset($errorMessages)) {
366 $errorMessages = array(
367 DB_ERROR => 'unknown error',
368 DB_ERROR_ALREADY_EXISTS => 'already exists',
369 DB_ERROR_CANNOT_CREATE => 'can not create',
370 DB_ERROR_CANNOT_DELETE => 'can not delete',
371 DB_ERROR_CANNOT_DROP => 'can not drop',
372 DB_ERROR_CONSTRAINT => 'constraint violation',
373 DB_ERROR_DIVZERO => 'division by zero',
374 DB_ERROR_INVALID => 'invalid',
375 DB_ERROR_INVALID_DATE => 'invalid date or time',
376 DB_ERROR_INVALID_NUMBER => 'invalid number',
377 DB_ERROR_MISMATCH => 'mismatch',
378 DB_ERROR_NODBSELECTED => 'no database selected',
379 DB_ERROR_NOSUCHFIELD => 'no such field',
380 DB_ERROR_NOSUCHTABLE => 'no such table',
381 DB_ERROR_NOT_CAPABLE => 'DB backend not capable',
382 DB_ERROR_NOT_FOUND => 'not found',
383 DB_ERROR_NOT_LOCKED => 'not locked',
384 DB_ERROR_SYNTAX => 'syntax error',
385 DB_ERROR_UNSUPPORTED => 'not supported',
386 DB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
387 DB_ERROR_INVALID_DSN => 'invalid DSN',
388 DB_ERROR_CONNECT_FAILED => 'connect failed',
390 DB_WARNING => 'unknown warning',
391 DB_WARNING_READ_ONLY => 'read only',
392 DB_ERROR_NEED_MORE_DATA => 'insufficient data supplied',
393 DB_ERROR_EXTENSION_NOT_FOUND=> 'extension not found'
397 if (DB::isError($value)) {
398 $value = $value->getCode();
401 return isset($errorMessages[$value]) ? $errorMessages[$value] : $errorMessages[DB_ERROR];
405 * Parse a data source name
407 * A array with the following keys will be returned:
408 * phptype: Database backend used in PHP (mysql, odbc etc.)
409 * dbsyntax: Database used with regards to SQL syntax etc.
410 * protocol: Communication protocol to use (tcp, unix etc.)
411 * hostspec: Host specification (hostname[:port])
412 * database: Database to use on the DBMS server
413 * username: User name for login
414 * password: Password for login
416 * The format of the supplied DSN is in its fullest form:
418 * phptype(dbsyntax)://username:password@protocol+hostspec/database
420 * Most variations are allowed:
422 * phptype://username:password@protocol+hostspec:110//usr/db_file.db
423 * phptype://username:password@hostspec/database_name
424 * phptype://username:password@hostspec
425 * phptype://username@hostspec
426 * phptype://hostspec/database
431 * @param string $dsn Data Source Name to be parsed
433 * @return array an associative array
435 * @author Tomas V.V.Cox <cox@idecnet.com>
437 function parseDSN($dsn)
439 if (is_array($dsn)) {
455 // Find phptype and dbsyntax
456 if (($pos = strpos($dsn, '://')) !== false) {
457 $str = substr($dsn, 0, $pos);
458 $dsn = substr($dsn, $pos + 3);
464 // Get phptype and dbsyntax
465 // $str => phptype(dbsyntax)
466 if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
467 $parsed['phptype'] = $arr[1];
468 $parsed['dbsyntax'] = (empty($arr[2])) ? $arr[1] : $arr[2];
470 $parsed['phptype'] = $str;
471 $parsed['dbsyntax'] = $str;
478 // Get (if found): username and password
479 // $dsn => username:password@protocol+hostspec/database
480 if (($at = strrpos($dsn,'@')) !== false) {
481 $str = substr($dsn, 0, $at);
482 $dsn = substr($dsn, $at + 1);
483 if (($pos = strpos($str, ':')) !== false) {
484 $parsed['username'] = urldecode(substr($str, 0, $pos));
485 $parsed['password'] = urldecode(substr($str, $pos + 1));
487 $parsed['username'] = urldecode($str);
491 // Find protocol and hostspec
493 // $dsn => proto(proto_opts)/database
494 if (preg_match('|^(.+?)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
496 $proto_opts = (!empty($match[2])) ? $match[2] : false;
499 // $dsn => protocol+hostspec/database (old format)
501 if (strpos($dsn, '+') !== false) {
502 list($proto, $dsn) = explode('+', $dsn, 2);
504 if (strpos($dsn, '/') !== false) {
505 list($proto_opts, $dsn) = explode('/', $dsn, 2);
512 // process the different protocol options
513 $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
514 $proto_opts = urldecode($proto_opts);
515 if ($parsed['protocol'] == 'tcp') {
516 if (strpos($proto_opts, ':') !== false) {
517 list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
519 $parsed['hostspec'] = $proto_opts;
521 } elseif ($parsed['protocol'] == 'unix') {
522 $parsed['socket'] = $proto_opts;
528 $parsed['database'] = $dsn;
535 * Load a PHP database extension if it is not loaded already.
539 * @param string $name the base name of the extension (without the .so or
542 * @return boolean true if the extension was already or successfully
543 * loaded, false if it could not be loaded
545 function assertExtension($name)
547 if (!extension_loaded($name)) {
548 $dlext = OS_WINDOWS ? '.dll' : '.so';
551 return extension_loaded($name);
556 * DB_Error implements a class for reporting portable database error
560 * @author Stig Bakken <ssb@fast.no>
562 class DB_Error extends PEAR_Error
565 * DB_Error constructor.
567 * @param mixed $code DB error code, or string with error message.
568 * @param integer $mode what "error mode" to operate in
569 * @param integer $level what error level to use for $mode & PEAR_ERROR_TRIGGER
570 * @param smixed $debuginfo additional debug info, such as the last query
577 function DB_Error($code = DB_ERROR, $mode = PEAR_ERROR_RETURN,
578 $level = E_USER_NOTICE, $debuginfo = null)
581 $this->PEAR_Error('DB Error: ' . DB::errorMessage($code), $code, $mode, $level, $debuginfo);
583 $this->PEAR_Error("DB Error: $code", DB_ERROR, $mode, $level, $debuginfo);
589 * DB_Warning implements a class for reporting portable database
593 * @author Stig Bakken <ssb@fast.no>
595 class DB_Warning extends PEAR_Error
598 * DB_Warning constructor.
600 * @param mixed $code DB error code, or string with error message.
601 * @param integer $mode what "error mode" to operate in
602 * @param integer $level what error level to use for $mode == PEAR_ERROR_TRIGGER
603 * @param mmixed $debuginfo additional debug info, such as the last query
610 function DB_Warning($code = DB_WARNING, $mode = PEAR_ERROR_RETURN,
611 $level = E_USER_NOTICE, $debuginfo = null)
614 $this->PEAR_Error('DB Warning: ' . DB::errorMessage($code), $code, $mode, $level, $debuginfo);
616 $this->PEAR_Error("DB Warning: $code", 0, $mode, $level, $debuginfo);
622 * This class implements a wrapper for a DB result set.
623 * A new instance of this class will be returned by the DB implementation
624 * after processing a query that returns data.
627 * @author Stig Bakken <ssb@fast.no>
634 var $row_counter = null;
636 * for limit queries, the row to start fetching
639 var $limit_from = null;
642 * for limit queries, the number of rows to fetch
645 var $limit_count = null;
648 * DB_result constructor.
649 * @param resource $dbh DB object reference
650 * @param resource $result result resource id
653 function DB_result(&$dbh, $result)
656 $this->result = $result;
660 * Fetch and return a row of data (it uses driver->fetchInto for that)
661 * @param int $fetchmode format of fetched row
662 * @param int $rownum the row number to fetch
664 * @return array a row of data, NULL on no more rows or PEAR_Error on error
668 function fetchRow($fetchmode = DB_FETCHMODE_DEFAULT, $rownum=null)
670 if ($fetchmode === DB_FETCHMODE_DEFAULT) {
671 $fetchmode = $this->dbh->fetchmode;
673 if ($fetchmode === DB_FETCHMODE_OBJECT) {
674 $fetchmode = DB_FETCHMODE_ASSOC;
675 $object_class = $this->dbh->fetchmode_object_class;
677 if ($this->limit_from !== null) {
678 if ($this->row_counter === null) {
679 $this->row_counter = $this->limit_from;
681 if ($this->dbh->features['limit'] == false) {
683 while ($i++ < $this->limit_from) {
684 $this->dbh->fetchInto($this->result, $arr, $fetchmode);
688 if ($this->row_counter >= (
689 $this->limit_from + $this->limit_count))
693 if ($this->dbh->features['limit'] == 'emulate') {
694 $rownum = $this->row_counter;
697 $this->row_counter++;
699 $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
700 if ($res !== DB_OK) {
703 if (isset($object_class)) {
704 // default mode specified in DB_common::fetchmode_object_class property
705 if ($object_class == 'stdClass') {
706 $ret = (object) $arr;
708 $ret =& new $object_class($arr);
716 * Fetch a row of data into an existing variable.
718 * @param mixed $arr reference to data containing the row
719 * @param integer $fetchmode format of fetched row
720 * @param integer $rownum the row number to fetch
722 * @return mixed DB_OK on success, NULL on no more rows or
723 * a DB_Error object on error
727 function fetchInto(&$arr, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum=null)
729 if ($fetchmode === DB_FETCHMODE_DEFAULT) {
730 $fetchmode = $this->dbh->fetchmode;
732 if ($fetchmode === DB_FETCHMODE_OBJECT) {
733 $fetchmode = DB_FETCHMODE_ASSOC;
734 $object_class = $this->dbh->fetchmode_object_class;
736 if ($this->limit_from !== null) {
737 if ($this->row_counter === null) {
738 $this->row_counter = $this->limit_from;
740 if ($this->dbh->features['limit'] == false) {
742 while ($i++ < $this->limit_from) {
743 $this->dbh->fetchInto($this->result, $arr, $fetchmode);
747 if ($this->row_counter >= (
748 $this->limit_from + $this->limit_count))
752 if ($this->dbh->features['limit'] == 'emulate') {
753 $rownum = $this->row_counter;
756 $this->row_counter++;
758 $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
759 if (($res === DB_OK) && isset($object_class)) {
760 // default mode specified in DB_common::fetchmode_object_class property
761 if ($object_class == 'stdClass') {
762 $arr = (object) $arr;
764 $arr = new $object_class($arr);
771 * Get the the number of columns in a result set.
773 * @return int the number of columns, or a DB error
779 return $this->dbh->numCols($this->result);
783 * Get the number of rows in a result set.
785 * @return int the number of rows, or a DB error
791 return $this->dbh->numRows($this->result);
795 * Get the next result if a batch of queries was executed.
797 * @return bool true if a new result is available or false if not.
801 function nextResult()
803 return $this->dbh->nextResult($this->result);
807 * Frees the resources allocated for this result set.
808 * @return int error code
814 $err = $this->dbh->freeResult($this->result);
815 if(DB::isError($err)) {
818 $this->result = false;
825 function tableInfo($mode = null)
827 return $this->dbh->tableInfo($this->result, $mode);
831 * returns the actual rows number
834 function getRowCounter()
836 return $this->row_counter;
842 * @see DB_common::setFetchMode()
849 * @param resource row data as array
851 function DB_row(&$arr)
853 for (reset($arr); $key = key($arr); next($arr)) {
854 $this->$key = &$arr[$key];