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 success970
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          print_R($dsninfo);exit;
527         $type = $dsninfo['phptype'];
528
529         if (!is_array($options)) {
530             /*
531              * For backwards compatibility.  $options used to be boolean,
532              * indicating whether the connection should be persistent.
533              */
534             $options = array('persistent' => $options);
535         }
536
537         if (isset($options['debug']) && $options['debug'] >= 2) {
538             // expose php errors with sufficient debug level
539             include_once "DB/${type}.php";
540         } else {
541             @include_once "DB/${type}.php";
542         }
543
544         $classname = "DB_${type}";
545         if (!class_exists($classname)) {
546             $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
547                                     "Unable to include the DB/{$type}.php"
548                                     . " file for '$dsn'",
549                                     'DB_Error', true);
550             return $tmp;
551         }
552
553         $obj = new $classname;
554
555         foreach ($options as $option => $value) {
556             $test = $obj->setOption($option, $value);
557             if (DB::isError($test)) {
558                 return $test;
559             }
560         }
561
562         $err = $obj->connect($dsninfo, $obj->getOption('persistent'));
563         if (DB::isError($err)) {
564             if (is_array($dsn)) {
565                 $err->addUserInfo(DB::getDSNString($dsn, true));
566             } else {
567                 $err->addUserInfo($dsn);
568             }
569             return $err;
570         }
571
572         return $obj;
573     }
574
575     // }}}
576     // {{{ apiVersion()
577
578     /**
579      * Return the DB API version
580      *
581      * @return string  the DB API version number
582      */
583     function apiVersion()
584     {
585         return '1.7.14';
586     }
587
588     // }}}
589     // {{{ isError()
590
591     /**
592      * Determines if a variable is a DB_Error object
593      *
594      * @param mixed $value  the variable to check
595      *
596      * @return bool  whether $value is DB_Error object
597      */
598     static function isError($value)
599     {
600         return is_object($value) && is_a($value, 'DB_Error');           
601     }
602
603     // }}}
604     // {{{ isConnection()
605
606     /**
607      * Determines if a value is a DB_<driver> object
608      *
609      * @param mixed $value  the value to test
610      *
611      * @return bool  whether $value is a DB_<driver> object
612      */
613     function isConnection($value)
614     {
615         return (is_object($value) &&
616                 is_subclass_of($value, 'db_common') &&
617                 method_exists($value, 'simpleQuery'));
618     }
619
620     // }}}
621     // {{{ isManip()
622
623     /**
624      * Tell whether a query is a data manipulation or data definition query
625      *
626      * Examples of data manipulation queries are INSERT, UPDATE and DELETE.
627      * Examples of data definition queries are CREATE, DROP, ALTER, GRANT,
628      * REVOKE.
629      *
630      * @param string $query  the query
631      *
632      * @return boolean  whether $query is a data manipulation query
633      */
634     static function isManip($query)
635     {
636         $manips = 'INSERT|UPDATE|DELETE|REPLACE|'
637                 . 'CREATE|DROP|'
638                 . 'LOAD DATA|SELECT .* INTO .* FROM|COPY|'
639                 . 'ALTER|GRANT|REVOKE|'
640                 . 'LOCK|UNLOCK';
641         if (preg_match('/^\s*"?(' . $manips . ')\s+/i', $query)) {
642             return true;
643         }
644         return false;
645     }
646
647     // }}}
648     // {{{ errorMessage()
649
650     /**
651      * Return a textual error message for a DB error code
652      *
653      * @param integer $value  the DB error code
654      *
655      * @return string  the error message or false if the error code was
656      *                  not recognized
657      */
658     static function errorMessage($value)
659     {
660         static $errorMessages;
661         if (!isset($errorMessages)) {
662             $errorMessages = array(
663                 DB_ERROR                    => 'unknown error',
664                 DB_ERROR_ACCESS_VIOLATION   => 'insufficient permissions',
665                 DB_ERROR_ALREADY_EXISTS     => 'already exists',
666                 DB_ERROR_CANNOT_CREATE      => 'can not create',
667                 DB_ERROR_CANNOT_DROP        => 'can not drop',
668                 DB_ERROR_CONNECT_FAILED     => 'connect failed',
669                 DB_ERROR_CONSTRAINT         => 'constraint violation',
670                 DB_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',
671                 DB_ERROR_DIVZERO            => 'division by zero',
672                 DB_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
673                 DB_ERROR_INVALID            => 'invalid',
674                 DB_ERROR_INVALID_DATE       => 'invalid date or time',
675                 DB_ERROR_INVALID_DSN        => 'invalid DSN',
676                 DB_ERROR_INVALID_NUMBER     => 'invalid number',
677                 DB_ERROR_MISMATCH           => 'mismatch',
678                 DB_ERROR_NEED_MORE_DATA     => 'insufficient data supplied',
679                 DB_ERROR_NODBSELECTED       => 'no database selected',
680                 DB_ERROR_NOSUCHDB           => 'no such database',
681                 DB_ERROR_NOSUCHFIELD        => 'no such field',
682                 DB_ERROR_NOSUCHTABLE        => 'no such table',
683                 DB_ERROR_NOT_CAPABLE        => 'DB backend not capable',
684                 DB_ERROR_NOT_FOUND          => 'not found',
685                 DB_ERROR_NOT_LOCKED         => 'not locked',
686                 DB_ERROR_SYNTAX             => 'syntax error',
687                 DB_ERROR_UNSUPPORTED        => 'not supported',
688                 DB_ERROR_TRUNCATED          => 'truncated',
689                 DB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
690                 DB_OK                       => 'no error',
691             );
692         }
693
694         if (DB::isError($value)) {
695             $value = $value->getCode();
696         }
697
698         return isset($errorMessages[$value]) ? $errorMessages[$value]
699                      : $errorMessages[DB_ERROR];
700     }
701
702     // }}}
703     // {{{ parseDSN()
704
705     /**
706      * Parse a data source name
707      *
708      * Additional keys can be added by appending a URI query string to the
709      * end of the DSN.
710      *
711      * The format of the supplied DSN is in its fullest form:
712      * <code>
713      *  phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
714      * </code>
715      *
716      * Most variations are allowed:
717      * <code>
718      *  phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
719      *  phptype://username:password@hostspec/database_name
720      *  phptype://username:password@hostspec
721      *  phptype://username@hostspec
722      *  phptype://hostspec/database
723      *  phptype://hostspec
724      *  phptype(dbsyntax)
725      *  phptype
726      * </code>
727      *
728      * @param string $dsn Data Source Name to be parsed
729      *
730      * @return array an associative array with the following keys:
731      *  + phptype:  Database backend used in PHP (mysql, odbc etc.)
732      *  + dbsyntax: Database used with regards to SQL syntax etc.
733      *  + protocol: Communication protocol to use (tcp, unix etc.)
734      *  + hostspec: Host specification (hostname[:port])
735      *  + database: Database to use on the DBMS server
736      *  + username: User name for login
737      *  + password: Password for login
738      */
739     static function parseDSN($dsn)
740     {
741         $parsed = array(
742             'phptype'  => false,
743             'dbsyntax' => false,
744             'username' => false,
745             'password' => false,
746             'protocol' => false,
747             'hostspec' => false,
748             'port'     => false,
749             'socket'   => false,
750             'database' => false,
751         );
752
753         if (is_array($dsn)) {
754             $dsn = array_merge($parsed, $dsn);
755             if (!$dsn['dbsyntax']) {
756                 $dsn['dbsyntax'] = $dsn['phptype'];
757             }
758             return $dsn;
759         }
760
761         // Find phptype and dbsyntax
762         if (($pos = strpos($dsn, '://')) !== false) {
763             $str = substr($dsn, 0, $pos);
764             $dsn = substr($dsn, $pos + 3);
765         } else {
766             $str = $dsn;
767             $dsn = null;
768         }
769
770         // Get phptype and dbsyntax
771         // $str => phptype(dbsyntax)
772         if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
773             $parsed['phptype']  = $arr[1];
774             $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
775         } else {
776             $parsed['phptype']  = $str;
777             $parsed['dbsyntax'] = $str;
778         }
779
780         if (!count($dsn)) {
781             return $parsed;
782         }
783
784         // Get (if found): username and password
785         // $dsn => username:password@protocol+hostspec/database
786         if (($at = strrpos($dsn,'@')) !== false) {
787             $str = substr($dsn, 0, $at);
788             $dsn = substr($dsn, $at + 1);
789             if (($pos = strpos($str, ':')) !== false) {
790                 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
791                 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
792             } else {
793                 $parsed['username'] = rawurldecode($str);
794             }
795         }
796
797         // Find protocol and hostspec
798
799         if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
800             // $dsn => proto(proto_opts)/database
801             $proto       = $match[1];
802             $proto_opts  = $match[2] ? $match[2] : false;
803             $dsn         = $match[3];
804
805         } else {
806             // $dsn => protocol+hostspec/database (old format)
807             if (strpos($dsn, '+') !== false) {
808                 list($proto, $dsn) = explode('+', $dsn, 2);
809             }
810             if (strpos($dsn, '/') !== false) {
811                 list($proto_opts, $dsn) = explode('/', $dsn, 2);
812             } else {
813                 $proto_opts = $dsn;
814                 $dsn = null;
815             }
816         }
817
818         // process the different protocol options
819         $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
820         $proto_opts = rawurldecode($proto_opts);
821         if (strpos($proto_opts, ':') !== false) {
822             list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
823         }
824         if ($parsed['protocol'] == 'tcp') {
825             $parsed['hostspec'] = $proto_opts;
826         } elseif ($parsed['protocol'] == 'unix') {
827             $parsed['socket'] = $proto_opts;
828         }
829
830         // Get dabase if any
831         // $dsn => database
832         if ($dsn) {
833             if (($pos = strpos($dsn, '?')) === false) {
834                 // /database
835                 $parsed['database'] = rawurldecode($dsn);
836             } else {
837                 // /database?param1=value1&param2=value2
838                 $parsed['database'] = rawurldecode(substr($dsn, 0, $pos));
839                 $dsn = substr($dsn, $pos + 1);
840                 if (strpos($dsn, '&') !== false) {
841                     $opts = explode('&', $dsn);
842                 } else { // database?param1=value1
843                     $opts = array($dsn);
844                 }
845                 foreach ($opts as $opt) {
846                     list($key, $value) = explode('=', $opt);
847                     if (!isset($parsed[$key])) {
848                         // don't allow params overwrite
849                         $parsed[$key] = rawurldecode($value);
850                     }
851                 }
852             }
853         }
854
855         return $parsed;
856     }
857
858     // }}}
859     // {{{ getDSNString()
860
861     /**
862      * Returns the given DSN in a string format suitable for output.
863      *
864      * @param array|string the DSN to parse and format
865      * @param boolean true to hide the password, false to include it
866      * @return string
867      */
868     function getDSNString($dsn, $hidePassword) {
869         /* Calling parseDSN will ensure that we have all the array elements
870          * defined, and means that we deal with strings and array in the same
871          * manner. */
872         $dsnArray = DB::parseDSN($dsn);
873         
874         if ($hidePassword) {
875             $dsnArray['password'] = 'PASSWORD';
876         }
877
878         /* Protocol is special-cased, as using the default "tcp" along with an
879          * Oracle TNS connection string fails. */
880         if (is_string($dsn) && strpos($dsn, 'tcp') === false && $dsnArray['protocol'] == 'tcp') {
881             $dsnArray['protocol'] = false;
882         }
883         
884         // Now we just have to construct the actual string. This is ugly.
885         $dsnString = $dsnArray['phptype'];
886         if ($dsnArray['dbsyntax']) {
887             $dsnString .= '('.$dsnArray['dbsyntax'].')';
888         }
889         $dsnString .= '://'
890                      .$dsnArray['username']
891                      .':'
892                      .$dsnArray['password']
893                      .'@'
894                      .$dsnArray['protocol'];
895         if ($dsnArray['socket']) {
896             $dsnString .= '('.$dsnArray['socket'].')';
897         }
898         if ($dsnArray['protocol'] && $dsnArray['hostspec']) {
899             $dsnString .= '+';
900         }
901         $dsnString .= $dsnArray['hostspec'];
902         if ($dsnArray['port']) {
903             $dsnString .= ':'.$dsnArray['port'];
904         }
905         $dsnString .= '/'.$dsnArray['database'];
906         
907         /* Option handling. Unfortunately, parseDSN simply places options into
908          * the top-level array, so we'll first get rid of the fields defined by
909          * DB and see what's left. */
910         unset($dsnArray['phptype'],
911               $dsnArray['dbsyntax'],
912               $dsnArray['username'],
913               $dsnArray['password'],
914               $dsnArray['protocol'],
915               $dsnArray['socket'],
916               $dsnArray['hostspec'],
917               $dsnArray['port'],
918               $dsnArray['database']
919         );
920         if (count($dsnArray) > 0) {
921             $dsnString .= '?';
922             $i = 0;
923             foreach ($dsnArray as $key => $value) {
924                 if (++$i > 1) {
925                     $dsnString .= '&';
926                 }
927                 $dsnString .= $key.'='.$value;
928             }
929         }
930
931         return $dsnString;
932     }
933     
934     // }}}
935 }
936
937 // }}}
938 // {{{ class DB_Error
939
940 /**
941  * DB_Error implements a class for reporting portable database error
942  * messages
943  *
944  * @category   Database
945  * @package    DB
946  * @author     Stig Bakken <ssb@php.net>
947  * @copyright  1997-2007 The PHP Group
948  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
949  * @version    Release: 1.7.14
950  * @link       http://pear.php.net/package/DB
951  */
952 class DB_Error extends PEAR_Error
953 {
954     // {{{ constructor
955
956     /**
957      * DB_Error constructor
958      *
959      * @param mixed $code       DB error code, or string with error message
960      * @param int   $mode       what "error mode" to operate in
961      * @param int   $level      what error level to use for $mode &
962      *                           PEAR_ERROR_TRIGGER
963      * @param mixed $debuginfo  additional debug info, such as the last query
964      *
965      * @see PEAR_Error
966      */
967     function __construct($code = DB_ERROR, $mode = PEAR_ERROR_RETURN,
968                       $level = E_USER_NOTICE, $debuginfo = null)
969     {
970         if (is_int($code)) {
971             parent::__construct('DB Error: ' . DB::errorMessage($code), $code,
972                               $mode, $level, $debuginfo);
973         } else {
974             parent::__construct("DB Error: $code", DB_ERROR,
975                               $mode, $level, $debuginfo);
976         }
977     }
978
979     // }}}
980 }
981
982 // }}}
983 // {{{ class DB_result
984
985 /**
986  * This class implements a wrapper for a DB result set
987  *
988  * A new instance of this class will be returned by the DB implementation
989  * after processing a query that returns data.
990  *
991  * @category   Database
992  * @package    DB
993  * @author     Stig Bakken <ssb@php.net>
994  * @copyright  1997-2007 The PHP Group
995  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
996  * @version    Release: 1.7.14
997  * @link       http://pear.php.net/package/DB
998  */
999 class DB_result
1000 {
1001     // {{{ properties
1002
1003     /**
1004      * Should results be freed automatically when there are no more rows?
1005      * @var boolean
1006      * @see DB_common::$options
1007      */
1008     var $autofree;
1009
1010     /**
1011      * A reference to the DB_<driver> object
1012      * @var object
1013      */
1014     var $dbh;
1015
1016     /**
1017      * The current default fetch mode
1018      * @var integer
1019      * @see DB_common::$fetchmode
1020      */
1021     var $fetchmode;
1022
1023     /**
1024      * The name of the class into which results should be fetched when
1025      * DB_FETCHMODE_OBJECT is in effect
1026      *
1027      * @var string
1028      * @see DB_common::$fetchmode_object_class
1029      */
1030     var $fetchmode_object_class;
1031
1032     /**
1033      * The number of rows to fetch from a limit query
1034      * @var integer
1035      */
1036     var $limit_count = null;
1037
1038     /**
1039      * The row to start fetching from in limit queries
1040      * @var integer
1041      */
1042     var $limit_from = null;
1043
1044     /**
1045      * The execute parameters that created this result
1046      * @var array
1047      * @since Property available since Release 1.7.0
1048      */
1049     var $parameters;
1050
1051     /**
1052      * The query string that created this result
1053      *
1054      * Copied here incase it changes in $dbh, which is referenced
1055      *
1056      * @var string
1057      * @since Property available since Release 1.7.0
1058      */
1059     var $query;
1060
1061     /**
1062      * The query result resource id created by PHP
1063      * @var resource
1064      */
1065     var $result;
1066
1067     /**
1068      * The present row being dealt with
1069      * @var integer
1070      */
1071     var $row_counter = null;
1072
1073     /**
1074      * The prepared statement resource id created by PHP in $dbh
1075      *
1076      * This resource is only available when the result set was created using
1077      * a driver's native execute() method, not PEAR DB's emulated one.
1078      *
1079      * Copied here incase it changes in $dbh, which is referenced
1080      *
1081      * {@internal  Mainly here because the InterBase/Firebird API is only
1082      * able to retrieve data from result sets if the statemnt handle is
1083      * still in scope.}}
1084      *
1085      * @var resource
1086      * @since Property available since Release 1.7.0
1087      */
1088     var $statement;
1089
1090
1091     // }}}
1092     // {{{ constructor
1093
1094     /**
1095      * This constructor sets the object's properties
1096      *
1097      * @param object   &$dbh     the DB object reference
1098      * @param resource $result   the result resource id
1099      * @param array    $options  an associative array with result options
1100      *
1101      * @return void
1102      */
1103     function __construct(&$dbh, $result, $options = array())
1104     {
1105         $this->autofree    = $dbh->options['autofree'];
1106         $this->dbh         = &$dbh;
1107         $this->fetchmode   = $dbh->fetchmode;
1108         $this->fetchmode_object_class = $dbh->fetchmode_object_class;
1109         $this->parameters  = $dbh->last_parameters;
1110         $this->query       = $dbh->last_query;
1111         $this->result      = $result;
1112         $this->statement   = empty($dbh->last_stmt) ? null : $dbh->last_stmt;
1113         foreach ($options as $key => $value) {
1114             $this->setOption($key, $value);
1115         }
1116     }
1117
1118     /**
1119      * Set options for the DB_result object
1120      *
1121      * @param string $key    the option to set
1122      * @param mixed  $value  the value to set the option to
1123      *
1124      * @return void
1125      */
1126     function setOption($key, $value = null)
1127     {
1128         switch ($key) {
1129             case 'limit_from':
1130                 $this->limit_from = $value;
1131                 break;
1132             case 'limit_count':
1133                 $this->limit_count = $value;
1134         }
1135     }
1136
1137     // }}}
1138     // {{{ fetchRow()
1139
1140     /**
1141      * Fetch a row of data and return it by reference into an array
1142      *
1143      * The type of array returned can be controlled either by setting this
1144      * method's <var>$fetchmode</var> parameter or by changing the default
1145      * fetch mode setFetchMode() before calling this method.
1146      *
1147      * There are two options for standardizing the information returned
1148      * from databases, ensuring their values are consistent when changing
1149      * DBMS's.  These portability options can be turned on when creating a
1150      * new DB object or by using setOption().
1151      *
1152      *   + <var>DB_PORTABILITY_LOWERCASE</var>
1153      *     convert names of fields to lower case
1154      *
1155      *   + <var>DB_PORTABILITY_RTRIM</var>
1156      *     right trim the data
1157      *
1158      * @param int $fetchmode  the constant indicating how to format the data
1159      * @param int $rownum     the row number to fetch (index starts at 0)
1160      *
1161      * @return mixed  an array or object containing the row's data,
1162      *                 NULL when the end of the result set is reached
1163      *                 or a DB_Error object on failure.
1164      *
1165      * @see DB_common::setOption(), DB_common::setFetchMode()
1166      */
1167     function &fetchRow($fetchmode = DB_FETCHMODE_DEFAULT, $rownum = null)
1168     {
1169         if ($fetchmode === DB_FETCHMODE_DEFAULT) {
1170             $fetchmode = $this->fetchmode;
1171         }
1172         if ($fetchmode === DB_FETCHMODE_OBJECT) {
1173             $fetchmode = DB_FETCHMODE_ASSOC;
1174             $object_class = $this->fetchmode_object_class;
1175         }
1176         if (is_null($rownum) && $this->limit_from !== null) {
1177             if ($this->row_counter === null) {
1178                 $this->row_counter = $this->limit_from;
1179                 // Skip rows
1180                 if ($this->dbh->features['limit'] === false) {
1181                     $i = 0;
1182                     while ($i++ < $this->limit_from) {
1183                         $this->dbh->fetchInto($this->result, $arr, $fetchmode);
1184                     }
1185                 }
1186             }
1187             if ($this->row_counter >= ($this->limit_from + $this->limit_count))
1188             {
1189                 if ($this->autofree) {
1190                     $this->free();
1191                 }
1192                 $tmp = null;
1193                 return $tmp;
1194             }
1195             if ($this->dbh->features['limit'] === 'emulate') {
1196                 $rownum = $this->row_counter;
1197             }
1198             $this->row_counter++;
1199         }
1200         $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
1201         if ($res === DB_OK) {
1202             if (isset($object_class)) {
1203                 // The default mode is specified in the
1204                 // DB_common::fetchmode_object_class property
1205                 if ($object_class == 'stdClass') {
1206                     $arr = (object) $arr;
1207                 } else {
1208                     $arr = new $object_class($arr);
1209                 }
1210             }
1211             return $arr;
1212         }
1213         if ($res == null && $this->autofree) {
1214             $this->free();
1215         }
1216         return $res;
1217     }
1218
1219     // }}}
1220     // {{{ fetchInto()
1221
1222     /**
1223      * Fetch a row of data into an array which is passed by reference
1224      *
1225      * The type of array returned can be controlled either by setting this
1226      * method's <var>$fetchmode</var> parameter or by changing the default
1227      * fetch mode setFetchMode() before calling this method.
1228      *
1229      * There are two options for standardizing the information returned
1230      * from databases, ensuring their values are consistent when changing
1231      * DBMS's.  These portability options can be turned on when creating a
1232      * new DB object or by using setOption().
1233      *
1234      *   + <var>DB_PORTABILITY_LOWERCASE</var>
1235      *     convert names of fields to lower case
1236      *
1237      *   + <var>DB_PORTABILITY_RTRIM</var>
1238      *     right trim the data
1239      *
1240      * @param array &$arr       the variable where the data should be placed
1241      * @param int   $fetchmode  the constant indicating how to format the data
1242      * @param int   $rownum     the row number to fetch (index starts at 0)
1243      *
1244      * @return mixed  DB_OK if a row is processed, NULL when the end of the
1245      *                 result set is reached or a DB_Error object on failure
1246      *
1247      * @see DB_common::setOption(), DB_common::setFetchMode()
1248      */
1249     function fetchInto(&$arr, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum = null)
1250     {
1251         if ($fetchmode === DB_FETCHMODE_DEFAULT) {
1252             $fetchmode = $this->fetchmode;
1253         }
1254         if ($fetchmode === DB_FETCHMODE_OBJECT) {
1255             $fetchmode = DB_FETCHMODE_ASSOC;
1256             $object_class = $this->fetchmode_object_class;
1257         }
1258         if (is_null($rownum) && $this->limit_from !== null) {
1259             if ($this->row_counter === null) {
1260                 $this->row_counter = $this->limit_from;
1261                 // Skip rows
1262                 if ($this->dbh->features['limit'] === false) {
1263                     $i = 0;
1264                     while ($i++ < $this->limit_from) {
1265                         $this->dbh->fetchInto($this->result, $arr, $fetchmode);
1266                     }
1267                 }
1268             }
1269             if ($this->row_counter >= (
1270                     $this->limit_from + $this->limit_count))
1271             {
1272                 if ($this->autofree) {
1273                     $this->free();
1274                 }
1275                 return null;
1276             }
1277             if ($this->dbh->features['limit'] === 'emulate') {
1278                 $rownum = $this->row_counter;
1279             }
1280
1281             $this->row_counter++;
1282         }
1283         $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
1284         if ($res === DB_OK) {
1285             if (isset($object_class)) {
1286                 // default mode specified in the
1287                 // DB_common::fetchmode_object_class property
1288                 if ($object_class == 'stdClass') {
1289                     $arr = (object) $arr;
1290                 } else {
1291                     $arr = new $object_class($arr);
1292                 }
1293             }
1294             return DB_OK;
1295         }
1296         if ($res == null && $this->autofree) {
1297             $this->free();
1298         }
1299         return $res;
1300     }
1301
1302     // }}}
1303     // {{{ numCols()
1304
1305     /**
1306      * Get the the number of columns in a result set
1307      *
1308      * @return int  the number of columns.  A DB_Error object on failure.
1309      */
1310     function numCols()
1311     {
1312         return $this->dbh->numCols($this->result);
1313     }
1314
1315     // }}}
1316     // {{{ numRows()
1317
1318     /**
1319      * Get the number of rows in a result set
1320      *
1321      * @return int  the number of rows.  A DB_Error object on failure.
1322      */
1323     function numRows()
1324     {
1325         if ($this->dbh->features['numrows'] === 'emulate'
1326             && $this->dbh->options['portability'] & DB_PORTABILITY_NUMROWS)
1327         {
1328             if ($this->dbh->features['prepare']) {
1329                 $res = $this->dbh->query($this->query, $this->parameters);
1330             } else {
1331                 $res = $this->dbh->query($this->query);
1332             }
1333             if (DB::isError($res)) {
1334                 return $res;
1335             }
1336             $i = 0;
1337             while ($res->fetchInto($tmp, DB_FETCHMODE_ORDERED)) {
1338                 $i++;
1339             }
1340             $count = $i;
1341         } else {
1342             $count = $this->dbh->numRows($this->result);
1343         }
1344
1345         /* fbsql is checked for here because limit queries are implemented
1346          * using a TOP() function, which results in fbsql_num_rows still
1347          * returning the total number of rows that would have been returned,
1348          * rather than the real number. As a result, we'll just do the limit
1349          * calculations for fbsql in the same way as a database with emulated
1350          * limits. Unfortunately, we can't just do this in DB_fbsql::numRows()
1351          * because that only gets the result resource, rather than the full
1352          * DB_Result object. */
1353         if (($this->dbh->features['limit'] === 'emulate'
1354              && $this->limit_from !== null)
1355             || $this->dbh->phptype == 'fbsql') {
1356             $limit_count = is_null($this->limit_count) ? $count : $this->limit_count;
1357             if ($count < $this->limit_from) {
1358                 $count = 0;
1359             } elseif ($count < ($this->limit_from + $limit_count)) {
1360                 $count -= $this->limit_from;
1361             } else {
1362                 $count = $limit_count;
1363             }
1364         }
1365
1366         return $count;
1367     }
1368
1369     // }}}
1370     // {{{ nextResult()
1371
1372     /**
1373      * Get the next result if a batch of queries was executed
1374      *
1375      * @return bool  true if a new result is available or false if not
1376      */
1377     function nextResult()
1378     {
1379         return $this->dbh->nextResult($this->result);
1380     }
1381
1382     // }}}
1383     // {{{ free()
1384
1385     /**
1386      * Frees the resources allocated for this result set
1387      *
1388      * @return bool  true on success.  A DB_Error object on failure.
1389      */
1390     function free()
1391     {
1392         $err = $this->dbh->freeResult($this->result);
1393         if (DB::isError($err)) {
1394             return $err;
1395         }
1396         $this->result = false;
1397         $this->statement = false;
1398         return true;
1399     }
1400
1401     // }}}
1402     // {{{ tableInfo()
1403
1404     /**
1405      * @see DB_common::tableInfo()
1406      * @deprecated Method deprecated some time before Release 1.2
1407      */
1408     function tableInfo($mode = null)
1409     {
1410         if (is_string($mode)) {
1411             return $this->dbh->raiseError(DB_ERROR_NEED_MORE_DATA);
1412         }
1413         return $this->dbh->tableInfo($this, $mode);
1414     }
1415
1416     // }}}
1417     // {{{ getQuery()
1418
1419     /**
1420      * Determine the query string that created this result
1421      *
1422      * @return string  the query string
1423      *
1424      * @since Method available since Release 1.7.0
1425      */
1426     function getQuery()
1427     {
1428         return $this->query;
1429     }
1430
1431     // }}}
1432     // {{{ getRowCounter()
1433
1434     /**
1435      * Tells which row number is currently being processed
1436      *
1437      * @return integer  the current row being looked at.  Starts at 1.
1438      */
1439     function getRowCounter()
1440     {
1441         return $this->row_counter;
1442     }
1443
1444     // }}}
1445 }
1446
1447 // }}}
1448 // {{{ class DB_row
1449
1450 /**
1451  * PEAR DB Row Object
1452  *
1453  * The object contains a row of data from a result set.  Each column's data
1454  * is placed in a property named for the column.
1455  *
1456  * @category   Database
1457  * @package    DB
1458  * @author     Stig Bakken <ssb@php.net>
1459  * @copyright  1997-2007 The PHP Group
1460  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
1461  * @version    Release: 1.7.14
1462  * @link       http://pear.php.net/package/DB
1463  * @see        DB_common::setFetchMode()
1464  */
1465 class DB_row
1466 {
1467     // {{{ constructor
1468
1469     /**
1470      * The constructor places a row's data into properties of this object
1471      *
1472      * @param array  the array containing the row's data
1473      *
1474      * @return void
1475      */
1476     function __construct(&$arr)
1477     {
1478         foreach ($arr as $key => $value) {
1479             $this->$key = &$arr[$key];
1480         }
1481     }
1482
1483     // }}}
1484 }
1485
1486 // }}}
1487
1488 /*
1489  * Local variables:
1490  * tab-width: 4
1491  * c-basic-offset: 4
1492  * End:
1493  */
1494
1495 ?>