DB.php
[pear] / DB.php
1 <?php
2
3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4
5 /**
6  * Database independent query interface
7  *
8  * PHP versions 4 and 5
9  *
10  * LICENSE: This source file is subject to version 3.0 of the PHP license
11  * that is available through the world-wide-web at the following URI:
12  * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
13  * the PHP License and are unable to obtain it through the web, please
14  * send a note to license@php.net so we can mail you a copy immediately.
15  *
16  * @category   Database
17  * @package    DB
18  * @author     Stig Bakken <ssb@php.net>
19  * @author     Tomas V.V.Cox <cox@idecnet.com>
20  * @author     Daniel Convissor <danielc@php.net>
21  * @copyright  1997-2007 The PHP Group
22  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
23  * @version    CVS: $Id: DB.php 315557 2011-08-26 14:32:35Z danielc $
24  * @link       http://pear.php.net/package/DB
25  */
26
27 /**
28  * Obtain the PEAR class so it can be extended from
29  */
30 require_once 'PEAR.php';
31
32
33 // {{{ constants
34 // {{{ error codes
35
36 /**#@+
37  * One of PEAR DB's portable error codes.
38  * @see DB_common::errorCode(), DB::errorMessage()
39  *
40  * {@internal If you add an error code here, make sure you also add a textual
41  * version of it in DB::errorMessage().}}
42  */
43
44 /**
45  * The code returned by many methods upon success
46  */
47 define('DB_OK', 1);
48
49 /**
50  * Unkown error
51  */
52 define('DB_ERROR', -1);
53
54 /**
55  * Syntax error
56  */
57 define('DB_ERROR_SYNTAX', -2);
58
59 /**
60  * Tried to insert a duplicate value into a primary or unique index
61  */
62 define('DB_ERROR_CONSTRAINT', -3);
63
64 /**
65  * An identifier in the query refers to a non-existant object
66  */
67 define('DB_ERROR_NOT_FOUND', -4);
68
69 /**
70  * Tried to create a duplicate object
71  */
72 define('DB_ERROR_ALREADY_EXISTS', -5);
73
74 /**
75  * The current driver does not support the action you attempted
76  */
77 define('DB_ERROR_UNSUPPORTED', -6);
78
79 /**
80  * The number of parameters does not match the number of placeholders
81  */
82 define('DB_ERROR_MISMATCH', -7);
83
84 /**
85  * A literal submitted did not match the data type expected
86  */
87 define('DB_ERROR_INVALID', -8);
88
89 /**
90  * The current DBMS does not support the action you attempted
91  */
92 define('DB_ERROR_NOT_CAPABLE', -9);
93
94 /**
95  * A literal submitted was too long so the end of it was removed
96  */
97 define('DB_ERROR_TRUNCATED', -10);
98
99 /**
100  * A literal number submitted did not match the data type expected
101  */
102 define('DB_ERROR_INVALID_NUMBER', -11);
103
104 /**
105  * A literal date submitted did not match the data type expected
106  */
107 define('DB_ERROR_INVALID_DATE', -12);
108
109 /**
110  * Attempt to divide something by zero
111  */
112 define('DB_ERROR_DIVZERO', -13);
113
114 /**
115  * A database needs to be selected
116  */
117 define('DB_ERROR_NODBSELECTED', -14);
118
119 /**
120  * Could not create the object requested
121  */
122 define('DB_ERROR_CANNOT_CREATE', -15);
123
124 /**
125  * Could not drop the database requested because it does not exist
126  */
127 define('DB_ERROR_CANNOT_DROP', -17);
128
129 /**
130  * An identifier in the query refers to a non-existant table
131  */
132 define('DB_ERROR_NOSUCHTABLE', -18);
133
134 /**
135  * An identifier in the query refers to a non-existant column
136  */
137 define('DB_ERROR_NOSUCHFIELD', -19);
138
139 /**
140  * The data submitted to the method was inappropriate
141  */
142 define('DB_ERROR_NEED_MORE_DATA', -20);
143
144 /**
145  * The attempt to lock the table failed
146  */
147 define('DB_ERROR_NOT_LOCKED', -21);
148
149 /**
150  * The number of columns doesn't match the number of values
151  */
152 define('DB_ERROR_VALUE_COUNT_ON_ROW', -22);
153
154 /**
155  * The DSN submitted has problems
156  */
157 define('DB_ERROR_INVALID_DSN', -23);
158
159 /**
160  * Could not connect to the database
161  */
162 define('DB_ERROR_CONNECT_FAILED', -24);
163
164 /**
165  * The PHP extension needed for this DBMS could not be found
166  */
167 define('DB_ERROR_EXTENSION_NOT_FOUND',-25);
168
169 /**
170  * The present user has inadequate permissions to perform the task requestd
171  */
172 define('DB_ERROR_ACCESS_VIOLATION', -26);
173
174 /**
175  * The database requested does not exist
176  */
177 define('DB_ERROR_NOSUCHDB', -27);
178
179 /**
180  * Tried to insert a null value into a column that doesn't allow nulls
181  */
182 define('DB_ERROR_CONSTRAINT_NOT_NULL',-29);
183 /**#@-*/
184
185
186 // }}}
187 // {{{ prepared statement-related
188
189
190 /**#@+
191  * Identifiers for the placeholders used in prepared statements.
192  * @see DB_common::prepare()
193  */
194
195 /**
196  * Indicates a scalar (<kbd>?</kbd>) placeholder was used
197  *
198  * Quote and escape the value as necessary.
199  */
200 define('DB_PARAM_SCALAR', 1);
201
202 /**
203  * Indicates an opaque (<kbd>&</kbd>) placeholder was used
204  *
205  * The value presented is a file name.  Extract the contents of that file
206  * and place them in this column.
207  */
208 define('DB_PARAM_OPAQUE', 2);
209
210 /**
211  * Indicates a misc (<kbd>!</kbd>) placeholder was used
212  *
213  * The value should not be quoted or escaped.
214  */
215 define('DB_PARAM_MISC',   3);
216 /**#@-*/
217
218
219 // }}}
220 // {{{ binary data-related
221
222
223 /**#@+
224  * The different ways of returning binary data from queries.
225  */
226
227 /**
228  * Sends the fetched data straight through to output
229  */
230 define('DB_BINMODE_PASSTHRU', 1);
231
232 /**
233  * Lets you return data as usual
234  */
235 define('DB_BINMODE_RETURN', 2);
236
237 /**
238  * Converts the data to hex format before returning it
239  *
240  * For example the string "123" would become "313233".
241  */
242 define('DB_BINMODE_CONVERT', 3);
243 /**#@-*/
244
245
246 // }}}
247 // {{{ fetch modes
248
249
250 /**#@+
251  * Fetch Modes.
252  * @see DB_common::setFetchMode()
253  */
254
255 /**
256  * Indicates the current default fetch mode should be used
257  * @see DB_common::$fetchmode
258  */
259 define('DB_FETCHMODE_DEFAULT', 0);
260
261 /**
262  * Column data indexed by numbers, ordered from 0 and up
263  */
264 define('DB_FETCHMODE_ORDERED', 1);
265
266 /**
267  * Column data indexed by column names
268  */
269 define('DB_FETCHMODE_ASSOC', 2);
270
271 /**
272  * Column data as object properties
273  */
274 define('DB_FETCHMODE_OBJECT', 3);
275
276 /**
277  * For multi-dimensional results, make the column name the first level
278  * of the array and put the row number in the second level of the array
279  *
280  * This is flipped from the normal behavior, which puts the row numbers
281  * in the first level of the array and the column names in the second level.
282  */
283 define('DB_FETCHMODE_FLIPPED', 4);
284 /**#@-*/
285
286 /**#@+
287  * Old fetch modes.  Left here for compatibility.
288  */
289 define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED);
290 define('DB_GETMODE_ASSOC',   DB_FETCHMODE_ASSOC);
291 define('DB_GETMODE_FLIPPED', DB_FETCHMODE_FLIPPED);
292 /**#@-*/
293
294
295 // }}}
296 // {{{ tableInfo() && autoPrepare()-related
297
298
299 /**#@+
300  * The type of information to return from the tableInfo() method.
301  *
302  * Bitwised constants, so they can be combined using <kbd>|</kbd>
303  * and removed using <kbd>^</kbd>.
304  *
305  * @see DB_common::tableInfo()
306  *
307  * {@internal Since the TABLEINFO constants are bitwised, if more of them are
308  * added in the future, make sure to adjust DB_TABLEINFO_FULL accordingly.}}
309  */
310 define('DB_TABLEINFO_ORDER', 1);
311 define('DB_TABLEINFO_ORDERTABLE', 2);
312 define('DB_TABLEINFO_FULL', 3);
313 /**#@-*/
314
315
316 /**#@+
317  * The type of query to create with the automatic query building methods.
318  * @see DB_common::autoPrepare(), DB_common::autoExecute()
319  */
320 define('DB_AUTOQUERY_INSERT', 1);
321 define('DB_AUTOQUERY_UPDATE', 2);
322 /**#@-*/
323
324
325 // }}}
326 // {{{ portability modes
327
328
329 /**#@+
330  * Portability Modes.
331  *
332  * Bitwised constants, so they can be combined using <kbd>|</kbd>
333  * and removed using <kbd>^</kbd>.
334  *
335  * @see DB_common::setOption()
336  *
337  * {@internal Since the PORTABILITY constants are bitwised, if more of them are
338  * added in the future, make sure to adjust DB_PORTABILITY_ALL accordingly.}}
339  */
340
341 /**
342  * Turn off all portability features
343  */
344 define('DB_PORTABILITY_NONE', 0);
345
346 /**
347  * Convert names of tables and fields to lower case
348  * when using the get*(), fetch*() and tableInfo() methods
349  */
350 define('DB_PORTABILITY_LOWERCASE', 1);
351
352 /**
353  * Right trim the data output by get*() and fetch*()
354  */
355 define('DB_PORTABILITY_RTRIM', 2);
356
357 /**
358  * Force reporting the number of rows deleted
359  */
360 define('DB_PORTABILITY_DELETE_COUNT', 4);
361
362 /**
363  * Enable hack that makes numRows() work in Oracle
364  */
365 define('DB_PORTABILITY_NUMROWS', 8);
366
367 /**
368  * Makes certain error messages in certain drivers compatible
369  * with those from other DBMS's
370  *
371  * + mysql, mysqli:  change unique/primary key constraints
372  *   DB_ERROR_ALREADY_EXISTS -> DB_ERROR_CONSTRAINT
373  *
374  * + odbc(access):  MS's ODBC driver reports 'no such field' as code
375  *   07001, which means 'too few parameters.'  When this option is on
376  *   that code gets mapped to DB_ERROR_NOSUCHFIELD.
377  */
378 define('DB_PORTABILITY_ERRORS', 16);
379
380 /**
381  * Convert null values to empty strings in data output by
382  * get*() and fetch*()
383  */
384 define('DB_PORTABILITY_NULL_TO_EMPTY', 32);
385
386 /**
387  * Convert boolean values to true/false (normally with postgres)
388  */
389 define('DB_PORTABILITY_BOOLEAN', 64);
390
391 /**
392  * Turn on all portability features
393  */
394 define('DB_PORTABILITY_ALL', 127);
395 /**#@-*/
396
397 // }}}
398
399
400 // }}}
401 // {{{ class DB
402
403 /**
404  * Database independent query interface
405  *
406  * The main "DB" class is simply a container class with some static
407  * methods for creating DB objects as well as some utility functions
408  * common to all parts of DB.
409  *
410  * The object model of DB is as follows (indentation means inheritance):
411  * <pre>
412  * DB           The main DB class.  This is simply a utility class
413  *              with some "static" methods for creating DB objects as
414  *              well as common utility functions for other DB classes.
415  *
416  * DB_common    The base for each DB implementation.  Provides default
417  * |            implementations (in OO lingo virtual methods) for
418  * |            the actual DB implementations as well as a bunch of
419  * |            query utility functions.
420  * |
421  * +-DB_mysql   The DB implementation for MySQL.  Inherits DB_common.
422  *              When calling DB::factory or DB::connect for MySQL
423  *              connections, the object returned is an instance of this
424  *              class.
425  * </pre>
426  *
427  * @category   Database
428  * @package    DB
429  * @author     Stig Bakken <ssb@php.net>
430  * @author     Tomas V.V.Cox <cox@idecnet.com>
431  * @author     Daniel Convissor <danielc@php.net>
432  * @copyright  1997-2007 The PHP Group
433  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
434  * @version    Release: 1.7.14
435  * @link       http://pear.php.net/package/DB
436  */
437 class DB
438 {
439     // {{{ &factory()
440
441     /**
442      * Create a new DB object for the specified database type but don't
443      * connect to the database
444      *
445      * @param string $type     the database type (eg "mysql")
446      * @param array  $options  an associative array of option names and values
447      *
448      * @return object  a new DB object.  A DB_Error object on failure.
449      *
450      * @see DB_common::setOption()
451      */
452     function &factory($type, $options = false)
453     {
454         if (!is_array($options)) {
455             $options = array('persistent' => $options);
456         }
457
458         if (isset($options['debug']) && $options['debug'] >= 2) {
459             // expose php errors with sufficient debug level
460             include_once "DB/{$type}.php";
461         } else {
462             @include_once "DB/{$type}.php";
463         }
464
465         $classname = "DB_${type}";
466
467         if (!class_exists($classname)) {
468             $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
469                                     "Unable to include the DB/{$type}.php"
470                                     . " file for '$dsn'",
471                                     'DB_Error', true);
472             return $tmp;
473         }
474
475         @$obj = new $classname;
476
477         foreach ($options as $option => $value) {
478             $test = $obj->setOption($option, $value);
479             if (DB::isError($test)) {
480                 return $test;
481             }
482         }
483
484         return $obj;
485     }
486
487     // }}}
488     // {{{ &connect()
489
490     /**
491      * Create a new DB object including a connection to the specified database
492      *
493      * Example 1.
494      * <code>
495      * require_once 'DB.php';
496      *
497      * $dsn = 'pgsql://user:password@host/database';
498      * $options = array(
499      *     'debug'       => 2,
500      *     'portability' => DB_PORTABILITY_ALL,
501      * );
502      *
503      * $db =& DB::connect($dsn, $options);
504      * if (PEAR::isError($db)) {
505      *     die($db->getMessage());
506      * }
507      * </code>
508      *
509      * @param mixed $dsn      the string "data source name" or array in the
510      *                         format returned by DB::parseDSN()
511      * @param array $options  an associative array of option names and values
512      *
513      * @return object  a new DB object.  A DB_Error object on failure.
514      *
515      * @uses DB_dbase::connect(), DB_fbsql::connect(), DB_ibase::connect(),
516      *       DB_ifx::connect(), DB_msql::connect(), DB_mssql::connect(),
517      *       DB_mysql::connect(), DB_mysqli::connect(), DB_oci8::connect(),
518      *       DB_odbc::connect(), DB_pgsql::connect(), DB_sqlite::connect(),
519      *       DB_sybase::connect()
520      *
521      * @uses DB::parseDSN(), DB_common::setOption(), PEAR::isError()
522      */
523     static function &connect($dsn, $options = array())
524     {
525         $dsninfo = DB::parseDSN($dsn);
526         $type = $dsninfo['phptype'];
527
528         if (!is_array($options)) {
529             /*
530              * For backwards compatibility.  $options used to be boolean,
531              * indicating whether the connection should be persistent.
532              */
533             $options = array('persistent' => $options);
534         }
535
536         if (isset($options['debug']) && $options['debug'] >= 2) {
537             // expose php errors with sufficient debug level
538             include_once "DB/${type}.php";
539         } else {
540             @include_once "DB/${type}.php";
541         }
542
543         $classname = "DB_${type}";
544         if (!class_exists($classname)) {
545             $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
546                                     "Unable to include the DB/{$type}.php"
547                                     . " file for '$dsn'",
548                                     'DB_Error', true);
549             return $tmp;
550         }
551
552         @$obj = new $classname;
553
554         foreach ($options as $option => $value) {
555             $test = $obj->setOption($option, $value);
556             if (DB::isError($test)) {
557                 return $test;
558             }
559         }
560
561         $err = $obj->connect($dsninfo, $obj->getOption('persistent'));
562         if (DB::isError($err)) {
563             if (is_array($dsn)) {
564                 $err->addUserInfo(DB::getDSNString($dsn, true));
565             } else {
566                 $err->addUserInfo($dsn);
567             }
568             return $err;
569         }
570
571         return $obj;
572     }
573
574     // }}}
575     // {{{ apiVersion()
576
577     /**
578      * Return the DB API version
579      *
580      * @return string  the DB API version number
581      */
582     function apiVersion()
583     {
584         return '1.7.14';
585     }
586
587     // }}}
588     // {{{ isError()
589
590     /**
591      * Determines if a variable is a DB_Error object
592      *
593      * @param mixed $value  the variable to check
594      *
595      * @return bool  whether $value is DB_Error object
596      */
597     function isError($value)
598     {
599         return is_object($value) && is_a($value, 'DB_Error');           
600     }
601
602     // }}}
603     // {{{ isConnection()
604
605     /**
606      * Determines if a value is a DB_<driver> object
607      *
608      * @param mixed $value  the value to test
609      *
610      * @return bool  whether $value is a DB_<driver> object
611      */
612     function isConnection($value)
613     {
614         return (is_object($value) &&
615                 is_subclass_of($value, 'db_common') &&
616                 method_exists($value, 'simpleQuery'));
617     }
618
619     // }}}
620     // {{{ isManip()
621
622     /**
623      * Tell whether a query is a data manipulation or data definition query
624      *
625      * Examples of data manipulation queries are INSERT, UPDATE and DELETE.
626      * Examples of data definition queries are CREATE, DROP, ALTER, GRANT,
627      * REVOKE.
628      *
629      * @param string $query  the query
630      *
631      * @return boolean  whether $query is a data manipulation query
632      */
633     function isManip($query)
634     {
635         $manips = 'INSERT|UPDATE|DELETE|REPLACE|'
636                 . 'CREATE|DROP|'
637                 . 'LOAD DATA|SELECT .* INTO .* FROM|COPY|'
638                 . 'ALTER|GRANT|REVOKE|'
639                 . 'LOCK|UNLOCK';
640         if (preg_match('/^\s*"?(' . $manips . ')\s+/i', $query)) {
641             return true;
642         }
643         return false;
644     }
645
646     // }}}
647     // {{{ errorMessage()
648
649     /**
650      * Return a textual error message for a DB error code
651      *
652      * @param integer $value  the DB error code
653      *
654      * @return string  the error message or false if the error code was
655      *                  not recognized
656      */
657     function errorMessage($value)
658     {
659         static $errorMessages;
660         if (!isset($errorMessages)) {
661             $errorMessages = array(
662                 DB_ERROR                    => 'unknown error',
663                 DB_ERROR_ACCESS_VIOLATION   => 'insufficient permissions',
664                 DB_ERROR_ALREADY_EXISTS     => 'already exists',
665                 DB_ERROR_CANNOT_CREATE      => 'can not create',
666                 DB_ERROR_CANNOT_DROP        => 'can not drop',
667                 DB_ERROR_CONNECT_FAILED     => 'connect failed',
668                 DB_ERROR_CONSTRAINT         => 'constraint violation',
669                 DB_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',
670                 DB_ERROR_DIVZERO            => 'division by zero',
671                 DB_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
672                 DB_ERROR_INVALID            => 'invalid',
673                 DB_ERROR_INVALID_DATE       => 'invalid date or time',
674                 DB_ERROR_INVALID_DSN        => 'invalid DSN',
675                 DB_ERROR_INVALID_NUMBER     => 'invalid number',
676                 DB_ERROR_MISMATCH           => 'mismatch',
677                 DB_ERROR_NEED_MORE_DATA     => 'insufficient data supplied',
678                 DB_ERROR_NODBSELECTED       => 'no database selected',
679                 DB_ERROR_NOSUCHDB           => 'no such database',
680                 DB_ERROR_NOSUCHFIELD        => 'no such field',
681                 DB_ERROR_NOSUCHTABLE        => 'no such table',
682                 DB_ERROR_NOT_CAPABLE        => 'DB backend not capable',
683                 DB_ERROR_NOT_FOUND          => 'not found',
684                 DB_ERROR_NOT_LOCKED         => 'not locked',
685                 DB_ERROR_SYNTAX             => 'syntax error',
686                 DB_ERROR_UNSUPPORTED        => 'not supported',
687                 DB_ERROR_TRUNCATED          => 'truncated',
688                 DB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
689                 DB_OK                       => 'no error',
690             );
691         }
692
693         if (DB::isError($value)) {
694             $value = $value->getCode();
695         }
696
697         return isset($errorMessages[$value]) ? $errorMessages[$value]
698                      : $errorMessages[DB_ERROR];
699     }
700
701     // }}}
702     // {{{ parseDSN()
703
704     /**
705      * Parse a data source name
706      *
707      * Additional keys can be added by appending a URI query string to the
708      * end of the DSN.
709      *
710      * The format of the supplied DSN is in its fullest form:
711      * <code>
712      *  phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
713      * </code>
714      *
715      * Most variations are allowed:
716      * <code>
717      *  phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
718      *  phptype://username:password@hostspec/database_name
719      *  phptype://username:password@hostspec
720      *  phptype://username@hostspec
721      *  phptype://hostspec/database
722      *  phptype://hostspec
723      *  phptype(dbsyntax)
724      *  phptype
725      * </code>
726      *
727      * @param string $dsn Data Source Name to be parsed
728      *
729      * @return array an associative array with the following keys:
730      *  + phptype:  Database backend used in PHP (mysql, odbc etc.)
731      *  + dbsyntax: Database used with regards to SQL syntax etc.
732      *  + protocol: Communication protocol to use (tcp, unix etc.)
733      *  + hostspec: Host specification (hostname[:port])
734      *  + database: Database to use on the DBMS server
735      *  + username: User name for login
736      *  + password: Password for login
737      */
738     function parseDSN($dsn)
739     {
740         $parsed = array(
741             'phptype'  => false,
742             'dbsyntax' => false,
743             'username' => false,
744             'password' => false,
745             'protocol' => false,
746             'hostspec' => false,
747             'port'     => false,
748             'socket'   => false,
749             'database' => false,
750         );
751
752         if (is_array($dsn)) {
753             $dsn = array_merge($parsed, $dsn);
754             if (!$dsn['dbsyntax']) {
755                 $dsn['dbsyntax'] = $dsn['phptype'];
756             }
757             return $dsn;
758         }
759
760         // Find phptype and dbsyntax
761         if (($pos = strpos($dsn, '://')) !== false) {
762             $str = substr($dsn, 0, $pos);
763             $dsn = substr($dsn, $pos + 3);
764         } else {
765             $str = $dsn;
766             $dsn = null;
767         }
768
769         // Get phptype and dbsyntax
770         // $str => phptype(dbsyntax)
771         if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
772             $parsed['phptype']  = $arr[1];
773             $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
774         } else {
775             $parsed['phptype']  = $str;
776             $parsed['dbsyntax'] = $str;
777         }
778
779         if (!count($dsn)) {
780             return $parsed;
781         }
782
783         // Get (if found): username and password
784         // $dsn => username:password@protocol+hostspec/database
785         if (($at = strrpos($dsn,'@')) !== false) {
786             $str = substr($dsn, 0, $at);
787             $dsn = substr($dsn, $at + 1);
788             if (($pos = strpos($str, ':')) !== false) {
789                 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
790                 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
791             } else {
792                 $parsed['username'] = rawurldecode($str);
793             }
794         }
795
796         // Find protocol and hostspec
797
798         if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
799             // $dsn => proto(proto_opts)/database
800             $proto       = $match[1];
801             $proto_opts  = $match[2] ? $match[2] : false;
802             $dsn         = $match[3];
803
804         } else {
805             // $dsn => protocol+hostspec/database (old format)
806             if (strpos($dsn, '+') !== false) {
807                 list($proto, $dsn) = explode('+', $dsn, 2);
808             }
809             if (strpos($dsn, '/') !== false) {
810                 list($proto_opts, $dsn) = explode('/', $dsn, 2);
811             } else {
812                 $proto_opts = $dsn;
813                 $dsn = null;
814             }
815         }
816
817         // process the different protocol options
818         $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
819         $proto_opts = rawurldecode($proto_opts);
820         if (strpos($proto_opts, ':') !== false) {
821             list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
822         }
823         if ($parsed['protocol'] == 'tcp') {
824             $parsed['hostspec'] = $proto_opts;
825         } elseif ($parsed['protocol'] == 'unix') {
826             $parsed['socket'] = $proto_opts;
827         }
828
829         // Get dabase if any
830         // $dsn => database
831         if ($dsn) {
832             if (($pos = strpos($dsn, '?')) === false) {
833                 // /database
834                 $parsed['database'] = rawurldecode($dsn);
835             } else {
836                 // /database?param1=value1&param2=value2
837                 $parsed['database'] = rawurldecode(substr($dsn, 0, $pos));
838                 $dsn = substr($dsn, $pos + 1);
839                 if (strpos($dsn, '&') !== false) {
840                     $opts = explode('&', $dsn);
841                 } else { // database?param1=value1
842                     $opts = array($dsn);
843                 }
844                 foreach ($opts as $opt) {
845                     list($key, $value) = explode('=', $opt);
846                     if (!isset($parsed[$key])) {
847                         // don't allow params overwrite
848                         $parsed[$key] = rawurldecode($value);
849                     }
850                 }
851             }
852         }
853
854         return $parsed;
855     }
856
857     // }}}
858     // {{{ getDSNString()
859
860     /**
861      * Returns the given DSN in a string format suitable for output.
862      *
863      * @param array|string the DSN to parse and format
864      * @param boolean true to hide the password, false to include it
865      * @return string
866      */
867     function getDSNString($dsn, $hidePassword) {
868         /* Calling parseDSN will ensure that we have all the array elements
869          * defined, and means that we deal with strings and array in the same
870          * manner. */
871         $dsnArray = DB::parseDSN($dsn);
872         
873         if ($hidePassword) {
874             $dsnArray['password'] = 'PASSWORD';
875         }
876
877         /* Protocol is special-cased, as using the default "tcp" along with an
878          * Oracle TNS connection string fails. */
879         if (is_string($dsn) && strpos($dsn, 'tcp') === false && $dsnArray['protocol'] == 'tcp') {
880             $dsnArray['protocol'] = false;
881         }
882         
883         // Now we just have to construct the actual string. This is ugly.
884         $dsnString = $dsnArray['phptype'];
885         if ($dsnArray['dbsyntax']) {
886             $dsnString .= '('.$dsnArray['dbsyntax'].')';
887         }
888         $dsnString .= '://'
889                      .$dsnArray['username']
890                      .':'
891                      .$dsnArray['password']
892                      .'@'
893                      .$dsnArray['protocol'];
894         if ($dsnArray['socket']) {
895             $dsnString .= '('.$dsnArray['socket'].')';
896         }
897         if ($dsnArray['protocol'] && $dsnArray['hostspec']) {
898             $dsnString .= '+';
899         }
900         $dsnString .= $dsnArray['hostspec'];
901         if ($dsnArray['port']) {
902             $dsnString .= ':'.$dsnArray['port'];
903         }
904         $dsnString .= '/'.$dsnArray['database'];
905         
906         /* Option handling. Unfortunately, parseDSN simply places options into
907          * the top-level array, so we'll first get rid of the fields defined by
908          * DB and see what's left. */
909         unset($dsnArray['phptype'],
910               $dsnArray['dbsyntax'],
911               $dsnArray['username'],
912               $dsnArray['password'],
913               $dsnArray['protocol'],
914               $dsnArray['socket'],
915               $dsnArray['hostspec'],
916               $dsnArray['port'],
917               $dsnArray['database']
918         );
919         if (count($dsnArray) > 0) {
920             $dsnString .= '?';
921             $i = 0;
922             foreach ($dsnArray as $key => $value) {
923                 if (++$i > 1) {
924                     $dsnString .= '&';
925                 }
926                 $dsnString .= $key.'='.$value;
927             }
928         }
929
930         return $dsnString;
931     }
932     
933     // }}}
934 }
935
936 // }}}
937 // {{{ class DB_Error
938
939 /**
940  * DB_Error implements a class for reporting portable database error
941  * messages
942  *
943  * @category   Database
944  * @package    DB
945  * @author     Stig Bakken <ssb@php.net>
946  * @copyright  1997-2007 The PHP Group
947  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
948  * @version    Release: 1.7.14
949  * @link       http://pear.php.net/package/DB
950  */
951 class DB_Error extends PEAR_Error
952 {
953     // {{{ constructor
954
955     /**
956      * DB_Error constructor
957      *
958      * @param mixed $code       DB error code, or string with error message
959      * @param int   $mode       what "error mode" to operate in
960      * @param int   $level      what error level to use for $mode &
961      *                           PEAR_ERROR_TRIGGER
962      * @param mixed $debuginfo  additional debug info, such as the last query
963      *
964      * @see PEAR_Error
965      */
966     function DB_Error($code = DB_ERROR, $mode = PEAR_ERROR_RETURN,
967                       $level = E_USER_NOTICE, $debuginfo = null)
968     {
969         if (is_int($code)) {
970             $this->PEAR_Error('DB Error: ' . DB::errorMessage($code), $code,
971                               $mode, $level, $debuginfo);
972         } else {
973             $this->PEAR_Error("DB Error: $code", DB_ERROR,
974                               $mode, $level, $debuginfo);
975         }
976     }
977
978     // }}}
979 }
980
981 // }}}
982 // {{{ class DB_result
983
984 /**
985  * This class implements a wrapper for a DB result set
986  *
987  * A new instance of this class will be returned by the DB implementation
988  * after processing a query that returns data.
989  *
990  * @category   Database
991  * @package    DB
992  * @author     Stig Bakken <ssb@php.net>
993  * @copyright  1997-2007 The PHP Group
994  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
995  * @version    Release: 1.7.14
996  * @link       http://pear.php.net/package/DB
997  */
998 class DB_result
999 {
1000     // {{{ properties
1001
1002     /**
1003      * Should results be freed automatically when there are no more rows?
1004      * @var boolean
1005      * @see DB_common::$options
1006      */
1007     var $autofree;
1008
1009     /**
1010      * A reference to the DB_<driver> object
1011      * @var object
1012      */
1013     var $dbh;
1014
1015     /**
1016      * The current default fetch mode
1017      * @var integer
1018      * @see DB_common::$fetchmode
1019      */
1020     var $fetchmode;
1021
1022     /**
1023      * The name of the class into which results should be fetched when
1024      * DB_FETCHMODE_OBJECT is in effect
1025      *
1026      * @var string
1027      * @see DB_common::$fetchmode_object_class
1028      */
1029     var $fetchmode_object_class;
1030
1031     /**
1032      * The number of rows to fetch from a limit query
1033      * @var integer
1034      */
1035     var $limit_count = null;
1036
1037     /**
1038      * The row to start fetching from in limit queries
1039      * @var integer
1040      */
1041     var $limit_from = null;
1042
1043     /**
1044      * The execute parameters that created this result
1045      * @var array
1046      * @since Property available since Release 1.7.0
1047      */
1048     var $parameters;
1049
1050     /**
1051      * The query string that created this result
1052      *
1053      * Copied here incase it changes in $dbh, which is referenced
1054      *
1055      * @var string
1056      * @since Property available since Release 1.7.0
1057      */
1058     var $query;
1059
1060     /**
1061      * The query result resource id created by PHP
1062      * @var resource
1063      */
1064     var $result;
1065
1066     /**
1067      * The present row being dealt with
1068      * @var integer
1069      */
1070     var $row_counter = null;
1071
1072     /**
1073      * The prepared statement resource id created by PHP in $dbh
1074      *
1075      * This resource is only available when the result set was created using
1076      * a driver's native execute() method, not PEAR DB's emulated one.
1077      *
1078      * Copied here incase it changes in $dbh, which is referenced
1079      *
1080      * {@internal  Mainly here because the InterBase/Firebird API is only
1081      * able to retrieve data from result sets if the statemnt handle is
1082      * still in scope.}}
1083      *
1084      * @var resource
1085      * @since Property available since Release 1.7.0
1086      */
1087     var $statement;
1088
1089
1090     // }}}
1091     // {{{ constructor
1092
1093     /**
1094      * This constructor sets the object's properties
1095      *
1096      * @param object   &$dbh     the DB object reference
1097      * @param resource $result   the result resource id
1098      * @param array    $options  an associative array with result options
1099      *
1100      * @return void
1101      */
1102     function DB_result(&$dbh, $result, $options = array())
1103     {
1104         $this->autofree    = $dbh->options['autofree'];
1105         $this->dbh         = &$dbh;
1106         $this->fetchmode   = $dbh->fetchmode;
1107         $this->fetchmode_object_class = $dbh->fetchmode_object_class;
1108         $this->parameters  = $dbh->last_parameters;
1109         $this->query       = $dbh->last_query;
1110         $this->result      = $result;
1111         $this->statement   = empty($dbh->last_stmt) ? null : $dbh->last_stmt;
1112         foreach ($options as $key => $value) {
1113             $this->setOption($key, $value);
1114         }
1115     }
1116
1117     /**
1118      * Set options for the DB_result object
1119      *
1120      * @param string $key    the option to set
1121      * @param mixed  $value  the value to set the option to
1122      *
1123      * @return void
1124      */
1125     function setOption($key, $value = null)
1126     {
1127         switch ($key) {
1128             case 'limit_from':
1129                 $this->limit_from = $value;
1130                 break;
1131             case 'limit_count':
1132                 $this->limit_count = $value;
1133         }
1134     }
1135
1136     // }}}
1137     // {{{ fetchRow()
1138
1139     /**
1140      * Fetch a row of data and return it by reference into an array
1141      *
1142      * The type of array returned can be controlled either by setting this
1143      * method's <var>$fetchmode</var> parameter or by changing the default
1144      * fetch mode setFetchMode() before calling this method.
1145      *
1146      * There are two options for standardizing the information returned
1147      * from databases, ensuring their values are consistent when changing
1148      * DBMS's.  These portability options can be turned on when creating a
1149      * new DB object or by using setOption().
1150      *
1151      *   + <var>DB_PORTABILITY_LOWERCASE</var>
1152      *     convert names of fields to lower case
1153      *
1154      *   + <var>DB_PORTABILITY_RTRIM</var>
1155      *     right trim the data
1156      *
1157      * @param int $fetchmode  the constant indicating how to format the data
1158      * @param int $rownum     the row number to fetch (index starts at 0)
1159      *
1160      * @return mixed  an array or object containing the row's data,
1161      *                 NULL when the end of the result set is reached
1162      *                 or a DB_Error object on failure.
1163      *
1164      * @see DB_common::setOption(), DB_common::setFetchMode()
1165      */
1166     function &fetchRow($fetchmode = DB_FETCHMODE_DEFAULT, $rownum = null)
1167     {
1168         if ($fetchmode === DB_FETCHMODE_DEFAULT) {
1169             $fetchmode = $this->fetchmode;
1170         }
1171         if ($fetchmode === DB_FETCHMODE_OBJECT) {
1172             $fetchmode = DB_FETCHMODE_ASSOC;
1173             $object_class = $this->fetchmode_object_class;
1174         }
1175         if (is_null($rownum) && $this->limit_from !== null) {
1176             if ($this->row_counter === null) {
1177                 $this->row_counter = $this->limit_from;
1178                 // Skip rows
1179                 if ($this->dbh->features['limit'] === false) {
1180                     $i = 0;
1181                     while ($i++ < $this->limit_from) {
1182                         $this->dbh->fetchInto($this->result, $arr, $fetchmode);
1183                     }
1184                 }
1185             }
1186             if ($this->row_counter >= ($this->limit_from + $this->limit_count))
1187             {
1188                 if ($this->autofree) {
1189                     $this->free();
1190                 }
1191                 $tmp = null;
1192                 return $tmp;
1193             }
1194             if ($this->dbh->features['limit'] === 'emulate') {
1195                 $rownum = $this->row_counter;
1196             }
1197             $this->row_counter++;
1198         }
1199         $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
1200         if ($res === DB_OK) {
1201             if (isset($object_class)) {
1202                 // The default mode is specified in the
1203                 // DB_common::fetchmode_object_class property
1204                 if ($object_class == 'stdClass') {
1205                     $arr = (object) $arr;
1206                 } else {
1207                     $arr = new $object_class($arr);
1208                 }
1209             }
1210             return $arr;
1211         }
1212         if ($res == null && $this->autofree) {
1213             $this->free();
1214         }
1215         return $res;
1216     }
1217
1218     // }}}
1219     // {{{ fetchInto()
1220
1221     /**
1222      * Fetch a row of data into an array which is passed by reference
1223      *
1224      * The type of array returned can be controlled either by setting this
1225      * method's <var>$fetchmode</var> parameter or by changing the default
1226      * fetch mode setFetchMode() before calling this method.
1227      *
1228      * There are two options for standardizing the information returned
1229      * from databases, ensuring their values are consistent when changing
1230      * DBMS's.  These portability options can be turned on when creating a
1231      * new DB object or by using setOption().
1232      *
1233      *   + <var>DB_PORTABILITY_LOWERCASE</var>
1234      *     convert names of fields to lower case
1235      *
1236      *   + <var>DB_PORTABILITY_RTRIM</var>
1237      *     right trim the data
1238      *
1239      * @param array &$arr       the variable where the data should be placed
1240      * @param int   $fetchmode  the constant indicating how to format the data
1241      * @param int   $rownum     the row number to fetch (index starts at 0)
1242      *
1243      * @return mixed  DB_OK if a row is processed, NULL when the end of the
1244      *                 result set is reached or a DB_Error object on failure
1245      *
1246      * @see DB_common::setOption(), DB_common::setFetchMode()
1247      */
1248     function fetchInto(&$arr, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum = null)
1249     {
1250         if ($fetchmode === DB_FETCHMODE_DEFAULT) {
1251             $fetchmode = $this->fetchmode;
1252         }
1253         if ($fetchmode === DB_FETCHMODE_OBJECT) {
1254             $fetchmode = DB_FETCHMODE_ASSOC;
1255             $object_class = $this->fetchmode_object_class;
1256         }
1257         if (is_null($rownum) && $this->limit_from !== null) {
1258             if ($this->row_counter === null) {
1259                 $this->row_counter = $this->limit_from;
1260                 // Skip rows
1261                 if ($this->dbh->features['limit'] === false) {
1262                     $i = 0;
1263                     while ($i++ < $this->limit_from) {
1264                         $this->dbh->fetchInto($this->result, $arr, $fetchmode);
1265                     }
1266                 }
1267             }
1268             if ($this->row_counter >= (
1269                     $this->limit_from + $this->limit_count))
1270             {
1271                 if ($this->autofree) {
1272                     $this->free();
1273                 }
1274                 return null;
1275             }
1276             if ($this->dbh->features['limit'] === 'emulate') {
1277                 $rownum = $this->row_counter;
1278             }
1279
1280             $this->row_counter++;
1281         }
1282         $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
1283         if ($res === DB_OK) {
1284             if (isset($object_class)) {
1285                 // default mode specified in the
1286                 // DB_common::fetchmode_object_class property
1287                 if ($object_class == 'stdClass') {
1288                     $arr = (object) $arr;
1289                 } else {
1290                     $arr = new $object_class($arr);
1291                 }
1292             }
1293             return DB_OK;
1294         }
1295         if ($res == null && $this->autofree) {
1296             $this->free();
1297         }
1298         return $res;
1299     }
1300
1301     // }}}
1302     // {{{ numCols()
1303
1304     /**
1305      * Get the the number of columns in a result set
1306      *
1307      * @return int  the number of columns.  A DB_Error object on failure.
1308      */
1309     function numCols()
1310     {
1311         return $this->dbh->numCols($this->result);
1312     }
1313
1314     // }}}
1315     // {{{ numRows()
1316
1317     /**
1318      * Get the number of rows in a result set
1319      *
1320      * @return int  the number of rows.  A DB_Error object on failure.
1321      */
1322     function numRows()
1323     {
1324         if ($this->dbh->features['numrows'] === 'emulate'
1325             && $this->dbh->options['portability'] & DB_PORTABILITY_NUMROWS)
1326         {
1327             if ($this->dbh->features['prepare']) {
1328                 $res = $this->dbh->query($this->query, $this->parameters);
1329             } else {
1330                 $res = $this->dbh->query($this->query);
1331             }
1332             if (DB::isError($res)) {
1333                 return $res;
1334             }
1335             $i = 0;
1336             while ($res->fetchInto($tmp, DB_FETCHMODE_ORDERED)) {
1337                 $i++;
1338             }
1339             $count = $i;
1340         } else {
1341             $count = $this->dbh->numRows($this->result);
1342         }
1343
1344         /* fbsql is checked for here because limit queries are implemented
1345          * using a TOP() function, which results in fbsql_num_rows still
1346          * returning the total number of rows that would have been returned,
1347          * rather than the real number. As a result, we'll just do the limit
1348          * calculations for fbsql in the same way as a database with emulated
1349          * limits. Unfortunately, we can't just do this in DB_fbsql::numRows()
1350          * because that only gets the result resource, rather than the full
1351          * DB_Result object. */
1352         if (($this->dbh->features['limit'] === 'emulate'
1353              && $this->limit_from !== null)
1354             || $this->dbh->phptype == 'fbsql') {
1355             $limit_count = is_null($this->limit_count) ? $count : $this->limit_count;
1356             if ($count < $this->limit_from) {
1357                 $count = 0;
1358             } elseif ($count < ($this->limit_from + $limit_count)) {
1359                 $count -= $this->limit_from;
1360             } else {
1361                 $count = $limit_count;
1362             }
1363         }
1364
1365         return $count;
1366     }
1367
1368     // }}}
1369     // {{{ nextResult()
1370
1371     /**
1372      * Get the next result if a batch of queries was executed
1373      *
1374      * @return bool  true if a new result is available or false if not
1375      */
1376     function nextResult()
1377     {
1378         return $this->dbh->nextResult($this->result);
1379     }
1380
1381     // }}}
1382     // {{{ free()
1383
1384     /**
1385      * Frees the resources allocated for this result set
1386      *
1387      * @return bool  true on success.  A DB_Error object on failure.
1388      */
1389     function free()
1390     {
1391         $err = $this->dbh->freeResult($this->result);
1392         if (DB::isError($err)) {
1393             return $err;
1394         }
1395         $this->result = false;
1396         $this->statement = false;
1397         return true;
1398     }
1399
1400     // }}}
1401     // {{{ tableInfo()
1402
1403     /**
1404      * @see DB_common::tableInfo()
1405      * @deprecated Method deprecated some time before Release 1.2
1406      */
1407     function tableInfo($mode = null)
1408     {
1409         if (is_string($mode)) {
1410             return $this->dbh->raiseError(DB_ERROR_NEED_MORE_DATA);
1411         }
1412         return $this->dbh->tableInfo($this, $mode);
1413     }
1414
1415     // }}}
1416     // {{{ getQuery()
1417
1418     /**
1419      * Determine the query string that created this result
1420      *
1421      * @return string  the query string
1422      *
1423      * @since Method available since Release 1.7.0
1424      */
1425     function getQuery()
1426     {
1427         return $this->query;
1428     }
1429
1430     // }}}
1431     // {{{ getRowCounter()
1432
1433     /**
1434      * Tells which row number is currently being processed
1435      *
1436      * @return integer  the current row being looked at.  Starts at 1.
1437      */
1438     function getRowCounter()
1439     {
1440         return $this->row_counter;
1441     }
1442
1443     // }}}
1444 }
1445
1446 // }}}
1447 // {{{ class DB_row
1448
1449 /**
1450  * PEAR DB Row Object
1451  *
1452  * The object contains a row of data from a result set.  Each column's data
1453  * is placed in a property named for the column.
1454  *
1455  * @category   Database
1456  * @package    DB
1457  * @author     Stig Bakken <ssb@php.net>
1458  * @copyright  1997-2007 The PHP Group
1459  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
1460  * @version    Release: 1.7.14
1461  * @link       http://pear.php.net/package/DB
1462  * @see        DB_common::setFetchMode()
1463  */
1464 class DB_row
1465 {
1466     // {{{ constructor
1467
1468     /**
1469      * The constructor places a row's data into properties of this object
1470      *
1471      * @param array  the array containing the row's data
1472      *
1473      * @return void
1474      */
1475     function DB_row(&$arr)
1476     {
1477         foreach ($arr as $key => $value) {
1478             $this->$key = &$arr[$key];
1479         }
1480     }
1481
1482     // }}}
1483 }
1484
1485 // }}}
1486
1487 /*
1488  * Local variables:
1489  * tab-width: 4
1490  * c-basic-offset: 4
1491  * End:
1492  */
1493
1494 ?>