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

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