source: temp/trunk/data/module/DB.php @ 2338

Revision 2338, 38.2 KB checked in by naka, 20 years ago (diff)

* empty log message *

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