source: temp/trunk/html/test/kakinaka/DB.php @ 4657

Revision 4657, 38.2 KB checked in by kakinaka, 20 years ago (diff)

blank

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