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

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