]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/pear/DB.php
Remove $Id$
[SourceForge/phpwiki.git] / lib / pear / DB.php
1 <?php
2 /* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
3 // +----------------------------------------------------------------------+
4 // | PHP Version 4                                                        |
5 // +----------------------------------------------------------------------+
6 // | Copyright (c) 1997-2004 The PHP Group                                |
7 // +----------------------------------------------------------------------+
8 // | This source file is subject to version 2.02 of the PHP license,      |
9 // | that is bundled with this package in the file LICENSE, and is        |
10 // | available at through the world-wide-web at                           |
11 // | http://www.php.net/license/2_02.txt.                                 |
12 // | If you did not receive a copy of the PHP license and are unable to   |
13 // | obtain it through the world-wide-web, please send a note to          |
14 // | license@php.net so we can mail you a copy immediately.               |
15 // +----------------------------------------------------------------------+
16 // | Authors: Stig Bakken <ssb@php.net>                                   |
17 // |          Tomas V.V.Cox <cox@idecnet.com>                             |
18 // | Maintainer: Daniel Convissor <danielc@php.net>                       |
19 // +----------------------------------------------------------------------+
20 //
21 // Database independent query interface.
22
23 require_once 'PEAR.php';
24
25 // {{{ constants
26 // {{{ error codes
27
28 /*
29  * The method mapErrorCode in each DB_dbtype implementation maps
30  * native error codes to one of these.
31  *
32  * If you add an error code here, make sure you also add a textual
33  * version of it in DB::errorMessage().
34  */
35 define('DB_OK',                         1);
36 define('DB_ERROR',                     -1);
37 define('DB_ERROR_SYNTAX',              -2);
38 define('DB_ERROR_CONSTRAINT',          -3);
39 define('DB_ERROR_NOT_FOUND',           -4);
40 define('DB_ERROR_ALREADY_EXISTS',      -5);
41 define('DB_ERROR_UNSUPPORTED',         -6);
42 define('DB_ERROR_MISMATCH',            -7);
43 define('DB_ERROR_INVALID',             -8);
44 define('DB_ERROR_NOT_CAPABLE',         -9);
45 define('DB_ERROR_TRUNCATED',          -10);
46 define('DB_ERROR_INVALID_NUMBER',     -11);
47 define('DB_ERROR_INVALID_DATE',       -12);
48 define('DB_ERROR_DIVZERO',            -13);
49 define('DB_ERROR_NODBSELECTED',       -14);
50 define('DB_ERROR_CANNOT_CREATE',      -15);
51 define('DB_ERROR_CANNOT_DELETE',      -16);
52 define('DB_ERROR_CANNOT_DROP',        -17);
53 define('DB_ERROR_NOSUCHTABLE',        -18);
54 define('DB_ERROR_NOSUCHFIELD',        -19);
55 define('DB_ERROR_NEED_MORE_DATA',     -20);
56 define('DB_ERROR_NOT_LOCKED',         -21);
57 define('DB_ERROR_VALUE_COUNT_ON_ROW', -22);
58 define('DB_ERROR_INVALID_DSN',        -23);
59 define('DB_ERROR_CONNECT_FAILED',     -24);
60 define('DB_ERROR_EXTENSION_NOT_FOUND',-25);
61 define('DB_ERROR_ACCESS_VIOLATION',   -26);
62 define('DB_ERROR_NOSUCHDB',           -27);
63 define('DB_ERROR_CONSTRAINT_NOT_NULL',-29);
64
65 // }}}
66 // {{{ prepared statement-related
67
68 /*
69  * These constants are used when storing information about prepared
70  * statements (using the "prepare" method in DB_dbtype).
71  *
72  * The prepare/execute model in DB is mostly borrowed from the ODBC
73  * extension, in a query the "?" character means a scalar parameter.
74  * There are two extensions though, a "&" character means an opaque
75  * parameter.  An opaque parameter is simply a file name, the real
76  * data are in that file (useful for putting uploaded files into your
77  * database and such). The "!" char means a parameter that must be
78  * left as it is.
79  * They modify the quote behavoir:
80  * DB_PARAM_SCALAR (?) => 'original string quoted'
81  * DB_PARAM_OPAQUE (&) => 'string from file quoted'
82  * DB_PARAM_MISC   (!) => original string
83  */
84 define('DB_PARAM_SCALAR', 1);
85 define('DB_PARAM_OPAQUE', 2);
86 define('DB_PARAM_MISC',   3);
87
88 // }}}
89 // {{{ binary data-related
90
91 /*
92  * These constants define different ways of returning binary data
93  * from queries.  Again, this model has been borrowed from the ODBC
94  * extension.
95  *
96  * DB_BINMODE_PASSTHRU sends the data directly through to the browser
97  * when data is fetched from the database.
98  * DB_BINMODE_RETURN lets you return data as usual.
99  * DB_BINMODE_CONVERT returns data as well, only it is converted to
100  * hex format, for example the string "123" would become "313233".
101  */
102 define('DB_BINMODE_PASSTHRU', 1);
103 define('DB_BINMODE_RETURN',   2);
104 define('DB_BINMODE_CONVERT',  3);
105
106 // }}}
107 // {{{ fetch modes
108
109 /**
110  * This is a special constant that tells DB the user hasn't specified
111  * any particular get mode, so the default should be used.
112  */
113 define('DB_FETCHMODE_DEFAULT', 0);
114
115 /**
116  * Column data indexed by numbers, ordered from 0 and up
117  */
118 define('DB_FETCHMODE_ORDERED', 1);
119
120 /**
121  * Column data indexed by column names
122  */
123 define('DB_FETCHMODE_ASSOC', 2);
124
125 /**
126  * Column data as object properties
127  */
128 define('DB_FETCHMODE_OBJECT', 3);
129
130 /**
131  * For multi-dimensional results: normally the first level of arrays
132  * is the row number, and the second level indexed by column number or name.
133  * DB_FETCHMODE_FLIPPED switches this order, so the first level of arrays
134  * is the column name, and the second level the row number.
135  */
136 define('DB_FETCHMODE_FLIPPED', 4);
137
138 /* for compatibility */
139 define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED);
140 define('DB_GETMODE_ASSOC',   DB_FETCHMODE_ASSOC);
141 define('DB_GETMODE_FLIPPED', DB_FETCHMODE_FLIPPED);
142
143
144 // }}}
145 // {{{ tableInfo() && autoPrepare()-related
146
147
148 /**
149  * these are constants for the tableInfo-function
150  * they are bitwised or'ed. so if there are more constants to be defined
151  * in the future, adjust DB_TABLEINFO_FULL accordingly
152  */
153 define('DB_TABLEINFO_ORDER', 1);
154 define('DB_TABLEINFO_ORDERTABLE', 2);
155 define('DB_TABLEINFO_FULL', 3);
156
157 /*
158  * Used by autoPrepare()
159  */
160 define('DB_AUTOQUERY_INSERT', 1);
161 define('DB_AUTOQUERY_UPDATE', 2);
162
163 // }}}
164 // {{{ portability modes
165
166 /**
167  * Portability: turn off all portability features.
168  * @see DB_common::setOption()
169  */
170 define('DB_PORTABILITY_NONE', 0);
171
172 /**
173  * Portability: convert names of tables and fields to lower case
174  * when using the get*(), fetch*() and tableInfo() methods.
175  * @see DB_common::setOption()
176  */
177 define('DB_PORTABILITY_LOWERCASE', 1);
178
179 /**
180  * Portability: right trim the data output by get*() and fetch*().
181  * @see DB_common::setOption()
182  */
183 define('DB_PORTABILITY_RTRIM', 2);
184
185 /**
186  * Portability: force reporting the number of rows deleted.
187  * @see DB_common::setOption()
188  */
189 define('DB_PORTABILITY_DELETE_COUNT', 4);
190
191 /**
192  * Portability: enable hack that makes numRows() work in Oracle.
193  * @see DB_common::setOption()
194  */
195 define('DB_PORTABILITY_NUMROWS', 8);
196
197 /**
198  * Portability: makes certain error messages in certain drivers compatible
199  * with those from other DBMS's.
200  *
201  * + mysql, mysqli:  change unique/primary key constraints
202  *   DB_ERROR_ALREADY_EXISTS -> DB_ERROR_CONSTRAINT
203  *
204  * + odbc(access):  MS's ODBC driver reports 'no such field' as code
205  *   07001, which means 'too few parameters.'  When this option is on
206  *   that code gets mapped to DB_ERROR_NOSUCHFIELD.
207  *
208  * @see DB_common::setOption()
209  */
210 define('DB_PORTABILITY_ERRORS', 16);
211
212 /**
213  * Portability: convert null values to empty strings in data output by
214  * get*() and fetch*().
215  * @see DB_common::setOption()
216  */
217 define('DB_PORTABILITY_NULL_TO_EMPTY', 32);
218
219 /**
220  * Portability: turn on all portability features.
221  * @see DB_common::setOption()
222  */
223 define('DB_PORTABILITY_ALL', 63);
224
225 // }}}
226
227 // }}}
228 // {{{ class DB
229
230 /**
231  * The main "DB" class is simply a container class with some static
232  * methods for creating DB objects as well as some utility functions
233  * common to all parts of DB.
234  *
235  * The object model of DB is as follows (indentation means inheritance):
236  *
237  * DB           The main DB class.  This is simply a utility class
238  *              with some "static" methods for creating DB objects as
239  *              well as common utility functions for other DB classes.
240  *
241  * DB_common    The base for each DB implementation.  Provides default
242  * |            implementations (in OO lingo virtual methods) for
243  * |            the actual DB implementations as well as a bunch of
244  * |            query utility functions.
245  * |
246  * +-DB_mysql   The DB implementation for MySQL.  Inherits DB_common.
247  *              When calling DB::factory or DB::connect for MySQL
248  *              connections, the object returned is an instance of this
249  *              class.
250  *
251  * @package  DB
252  * @author   Stig Bakken <ssb@php.net>
253  * @author   Tomas V.V.Cox <cox@idecnet.com>
254  * @since    PHP 4.0
255  * @version  
256  * @category Database
257  */
258 class DB
259 {
260     // {{{ &factory()
261
262     /**
263      * Create a new DB object for the specified database type.
264      *
265      * Allows creation of a DB_<driver> object from which the object's
266      * methods can be utilized without actually connecting to a database.
267      *
268      * @param string $type    database type, for example "mysql"
269      * @param array  $options associative array of option names and values
270      *
271      * @return object a new DB object.  On error, an error object.
272      *
273      * @see DB_common::setOption()
274      * @access public
275      */
276     function &factory($type, $options = false)
277     {
278         if (!is_array($options)) {
279             $options = array('persistent' => $options);
280         }
281
282         if (isset($options['debug']) && $options['debug'] >= 2) {
283             // expose php errors with sufficient debug level
284             include_once "DB/{$type}.php";
285         } else {
286             @include_once "DB/{$type}.php";
287         }
288
289         $classname = "DB_${type}";
290
291         if (!class_exists($classname)) {
292             $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
293                                     "Unable to include the DB/{$type}.php file",
294                                     'DB_Error', true);
295             return $tmp;
296         }
297
298         @$obj = new $classname;
299
300         foreach ($options as $option => $value) {
301             $test = $obj->setOption($option, $value);
302             if (DB::isError($test)) {
303                 return $test;
304             }
305         }
306
307         return $obj;
308     }
309
310     // }}}
311     // {{{ &connect()
312
313     /**
314      * Create a new DB object and connect to the specified database.
315      *
316      * Example 1.
317      * <code> <?php
318      * require_once 'DB.php';
319      *
320      * $dsn = 'mysql://user:password@host/database'
321      * $options = array(
322      *     'debug'       => 2,
323      *     'portability' => DB_PORTABILITY_ALL,
324      * );
325      *
326      * $dbh =& DB::connect($dsn, $options);
327      * if (DB::isError($dbh)) {
328      *     die($dbh->getMessage());
329      * }
330      * ?></code>
331      *
332      * @param mixed $dsn string "data source name" or an array in the
333      *                        format returned by DB::parseDSN()
334      *
335      * @param array $options an associative array of option names and
336      *                        their values
337      *
338      * @return object a newly created DB connection object, or a DB
339      *                 error object on error
340      *
341      * @see DB::parseDSN(), DB_common::setOption(), DB::isError()
342      * @access public
343      */
344     function &connect($dsn, $options = array())
345     {
346         $dsninfo = DB::parseDSN($dsn);
347         $type = $dsninfo['phptype'];
348
349         if (!is_array($options)) {
350             /*
351              * For backwards compatibility.  $options used to be boolean,
352              * indicating whether the connection should be persistent.
353              */
354             $options = array('persistent' => $options);
355         }
356
357         if (isset($options['debug']) && $options['debug'] >= 2) {
358             // expose php errors with sufficient debug level
359             include_once "DB/${type}.php";
360         } else {
361             @include_once "DB/${type}.php";
362         }
363
364         $classname = "DB_${type}";
365         if (!class_exists($classname)) {
366             $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
367                                     "Unable to include the DB/{$type}.php file for `$dsn'",
368                                     'DB_Error', true);
369             return $tmp;
370         }
371
372         @$obj = new $classname;
373
374         foreach ($options as $option => $value) {
375             $test = $obj->setOption($option, $value);
376             if (DB::isError($test)) {
377                 return $test;
378             }
379         }
380
381         $err = $obj->connect($dsninfo, $obj->getOption('persistent'));
382         if (DB::isError($err)) {
383             $err->addUserInfo($dsn);
384             return $err;
385         }
386
387         return $obj;
388     }
389
390     // }}}
391     // {{{ apiVersion()
392
393     /**
394      * Return the DB API version
395      *
396      * @return int the DB API version number
397      *
398      * @access public
399      */
400     function apiVersion()
401     {
402         return 2;
403     }
404
405     // }}}
406     // {{{ isError()
407
408     /**
409      * Tell whether a result code from a DB method is an error
410      *
411      * @param int $value result code
412      *
413      * @return bool whether $value is an error
414      *
415      * @access public
416      */
417     function isError($value)
418     {
419         return is_a($value, 'DB_Error');
420     }
421
422     // }}}
423     // {{{ isConnection()
424
425     /**
426      * Tell whether a value is a DB connection
427      *
428      * @param mixed $value value to test
429      *
430      * @return bool whether $value is a DB connection
431      *
432      * @access public
433      */
434     function isConnection($value)
435     {
436         return (is_object($value) &&
437                 is_subclass_of($value, 'db_common') &&
438                 method_exists($value, 'simpleQuery'));
439     }
440
441     // }}}
442     // {{{ isManip()
443
444     /**
445      * Tell whether a query is a data manipulation query (insert,
446      * update or delete) or a data definition query (create, drop,
447      * alter, grant, revoke).
448      *
449      * @access public
450      *
451      * @param string $query the query
452      *
453      * @return boolean whether $query is a data manipulation query
454      */
455     function isManip($query)
456     {
457         $manips = 'INSERT|UPDATE|DELETE|LOAD DATA|'.'REPLACE|CREATE|DROP|'.
458                   'ALTER|GRANT|REVOKE|'.'LOCK|UNLOCK';
459         if (preg_match('/^\s*"?('.$manips.')\s+/i', $query)) {
460             return true;
461         }
462         return false;
463     }
464
465     // }}}
466     // {{{ errorMessage()
467
468     /**
469      * Return a textual error message for a DB error code
470      *
471      * @param integer $value error code
472      *
473      * @return string error message, or false if the error code was
474      * not recognized
475      */
476     function errorMessage($value)
477     {
478         static $errorMessages;
479         if (!isset($errorMessages)) {
480             $errorMessages = array(
481                 DB_ERROR                    => 'unknown error',
482                 DB_ERROR_ALREADY_EXISTS     => 'already exists',
483                 DB_ERROR_CANNOT_CREATE      => 'can not create',
484                 DB_ERROR_CANNOT_DELETE      => 'can not delete',
485                 DB_ERROR_CANNOT_DROP        => 'can not drop',
486                 DB_ERROR_CONSTRAINT         => 'constraint violation',
487                 DB_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',
488                 DB_ERROR_DIVZERO            => 'division by zero',
489                 DB_ERROR_INVALID            => 'invalid',
490                 DB_ERROR_INVALID_DATE       => 'invalid date or time',
491                 DB_ERROR_INVALID_NUMBER     => 'invalid number',
492                 DB_ERROR_MISMATCH           => 'mismatch',
493                 DB_ERROR_NODBSELECTED       => 'no database selected',
494                 DB_ERROR_NOSUCHFIELD        => 'no such field',
495                 DB_ERROR_NOSUCHTABLE        => 'no such table',
496                 DB_ERROR_NOT_CAPABLE        => 'DB backend not capable',
497                 DB_ERROR_NOT_FOUND          => 'not found',
498                 DB_ERROR_NOT_LOCKED         => 'not locked',
499                 DB_ERROR_SYNTAX             => 'syntax error',
500                 DB_ERROR_UNSUPPORTED        => 'not supported',
501                 DB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
502                 DB_ERROR_INVALID_DSN        => 'invalid DSN',
503                 DB_ERROR_CONNECT_FAILED     => 'connect failed',
504                 DB_OK                       => 'no error',
505                 DB_ERROR_NEED_MORE_DATA     => 'insufficient data supplied',
506                 DB_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
507                 DB_ERROR_NOSUCHDB           => 'no such database',
508                 DB_ERROR_ACCESS_VIOLATION   => 'insufficient permissions',
509                 DB_ERROR_TRUNCATED          => 'truncated'
510             );
511         }
512
513         if (DB::isError($value)) {
514             $value = $value->getCode();
515         }
516
517         return isset($errorMessages[$value]) ? $errorMessages[$value] : $errorMessages[DB_ERROR];
518     }
519
520     // }}}
521     // {{{ parseDSN()
522
523     /**
524      * Parse a data source name.
525      *
526      * Additional keys can be added by appending a URI query string to the
527      * end of the DSN.
528      *
529      * The format of the supplied DSN is in its fullest form:
530      * <code>
531      *  phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
532      * </code>
533      *
534      * Most variations are allowed:
535      * <code>
536      *  phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
537      *  phptype://username:password@hostspec/database_name
538      *  phptype://username:password@hostspec
539      *  phptype://username@hostspec
540      *  phptype://hostspec/database
541      *  phptype://hostspec
542      *  phptype(dbsyntax)
543      *  phptype
544      * </code>
545      *
546      * @param string $dsn Data Source Name to be parsed
547      *
548      * @return array an associative array with the following keys:
549      *  + phptype:  Database backend used in PHP (mysql, odbc etc.)
550      *  + dbsyntax: Database used with regards to SQL syntax etc.
551      *  + protocol: Communication protocol to use (tcp, unix etc.)
552      *  + hostspec: Host specification (hostname[:port])
553      *  + database: Database to use on the DBMS server
554      *  + username: User name for login
555      *  + password: Password for login
556      *
557      * @author Tomas V.V.Cox <cox@idecnet.com>
558      */
559     function parseDSN($dsn)
560     {
561         $parsed = array(
562             'phptype'  => false,
563             'dbsyntax' => false,
564             'username' => false,
565             'password' => false,
566             'protocol' => false,
567             'hostspec' => false,
568             'port'     => false,
569             'socket'   => false,
570             'database' => false,
571         );
572
573         if (is_array($dsn)) {
574             $dsn = array_merge($parsed, $dsn);
575             if (!$dsn['dbsyntax']) {
576                 $dsn['dbsyntax'] = $dsn['phptype'];
577             }
578             return $dsn;
579         }
580
581         // Find phptype and dbsyntax
582         if (($pos = strpos($dsn, '://')) !== false) {
583             $str = substr($dsn, 0, $pos);
584             $dsn = substr($dsn, $pos + 3);
585         } else {
586             $str = $dsn;
587             $dsn = null;
588         }
589
590         // Get phptype and dbsyntax
591         // $str => phptype(dbsyntax)
592         if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
593             $parsed['phptype']  = $arr[1];
594             $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
595         } else {
596             $parsed['phptype']  = $str;
597             $parsed['dbsyntax'] = $str;
598         }
599
600         if (!count($dsn)) {
601             return $parsed;
602         }
603
604         // Get (if found): username and password
605         // $dsn => username:password@protocol+hostspec/database
606         if (($at = strrpos($dsn,'@')) !== false) {
607             $str = substr($dsn, 0, $at);
608             $dsn = substr($dsn, $at + 1);
609             if (($pos = strpos($str, ':')) !== false) {
610                 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
611                 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
612             } else {
613                 $parsed['username'] = rawurldecode($str);
614             }
615         }
616
617         // Find protocol and hostspec
618
619         // $dsn => proto(proto_opts)/database
620         if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
621             $proto       = $match[1];
622             $proto_opts  = $match[2] ? $match[2] : false;
623             $dsn         = $match[3];
624
625         // $dsn => protocol+hostspec/database (old format)
626         } else {
627             if (strpos($dsn, '+') !== false) {
628                 list($proto, $dsn) = explode('+', $dsn, 2);
629             }
630             if (strpos($dsn, '/') !== false) {
631                 list($proto_opts, $dsn) = explode('/', $dsn, 2);
632             } else {
633                 $proto_opts = $dsn;
634                 $dsn = null;
635             }
636         }
637
638         // process the different protocol options
639         $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
640         $proto_opts = rawurldecode($proto_opts);
641         if ($parsed['protocol'] == 'tcp') {
642             if (strpos($proto_opts, ':') !== false) {
643                 list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
644             } else {
645                 $parsed['hostspec'] = $proto_opts;
646             }
647         } elseif ($parsed['protocol'] == 'unix') {
648             $parsed['socket'] = $proto_opts;
649         }
650
651         // Get dabase if any
652         // $dsn => database
653         if ($dsn) {
654             // /database
655             if (($pos = strpos($dsn, '?')) === false) {
656                 $parsed['database'] = $dsn;
657             // /database?param1=value1&param2=value2
658             } else {
659                 $parsed['database'] = substr($dsn, 0, $pos);
660                 $dsn = substr($dsn, $pos + 1);
661                 if (strpos($dsn, '&') !== false) {
662                     $opts = explode('&', $dsn);
663                 } else { // database?param1=value1
664                     $opts = array($dsn);
665                 }
666                 foreach ($opts as $opt) {
667                     list($key, $value) = explode('=', $opt);
668                     if (!isset($parsed[$key])) {
669                         // don't allow params overwrite
670                         $parsed[$key] = rawurldecode($value);
671                     }
672                 }
673             }
674         }
675
676         return $parsed;
677     }
678
679     // }}}
680     // {{{ assertExtension()
681
682     /**
683      * Load a PHP database extension if it is not loaded already.
684      *
685      * @access public
686      *
687      * @param string $name the base name of the extension (without the .so or
688      *                     .dll suffix)
689      *
690      * @return boolean true if the extension was already or successfully
691      *                 loaded, false if it could not be loaded
692      */
693     function assertExtension($name)
694     {
695         if (!extension_loaded($name)) {
696             $dlext = OS_WINDOWS ? '.dll' : '.so';
697             $dlprefix = OS_WINDOWS ? 'php_' : '';
698             @dl($dlprefix . $name . $dlext);
699             return extension_loaded($name);
700         }
701         return true;
702     }
703     // }}}
704 }
705
706 // }}}
707 // {{{ class DB_Error
708
709 /**
710  * DB_Error implements a class for reporting portable database error
711  * messages.
712  *
713  * @package  DB
714  * @author Stig Bakken <ssb@php.net>
715  */
716 class DB_Error extends PEAR_Error
717 {
718     // {{{ constructor
719
720     /**
721      * DB_Error constructor.
722      *
723      * @param mixed   $code      DB error code, or string with error message.
724      * @param integer $mode      what "error mode" to operate in
725      * @param integer $level     what error level to use for $mode & PEAR_ERROR_TRIGGER
726      * @param mixed   $debuginfo additional debug info, such as the last query
727      *
728      * @access public
729      *
730      * @see PEAR_Error
731      */
732     function DB_Error($code = DB_ERROR, $mode = PEAR_ERROR_RETURN,
733               $level = E_USER_NOTICE, $debuginfo = null)
734     {
735         if (is_int($code)) {
736             $this->PEAR_Error('DB Error: ' . DB::errorMessage($code), $code, $mode, $level, $debuginfo);
737         } else {
738             $this->PEAR_Error("DB Error: $code", DB_ERROR, $mode, $level, $debuginfo);
739         }
740     }
741     // }}}
742 }
743
744 // }}}
745 // {{{ class DB_result
746
747 /**
748  * This class implements a wrapper for a DB result set.
749  * A new instance of this class will be returned by the DB implementation
750  * after processing a query that returns data.
751  *
752  * @package  DB
753  * @author Stig Bakken <ssb@php.net>
754  */
755 class DB_result
756 {
757     // {{{ properties
758
759     var $dbh;
760     var $result;
761     var $row_counter = null;
762
763     /**
764      * for limit queries, the row to start fetching
765      * @var integer
766      */
767     var $limit_from  = null;
768
769     /**
770      * for limit queries, the number of rows to fetch
771      * @var integer
772      */
773     var $limit_count = null;
774
775     // }}}
776     // {{{ constructor
777
778     /**
779      * DB_result constructor.
780      * @param resource &$dbh   DB object reference
781      * @param resource $result  result resource id
782      * @param array    $options assoc array with optional result options
783      */
784     function DB_result(&$dbh, $result, $options = array())
785     {
786         $this->dbh = &$dbh;
787         $this->result = $result;
788         foreach ($options as $key => $value) {
789             $this->setOption($key, $value);
790         }
791         $this->limit_type  = $dbh->features['limit'];
792         $this->autofree    = $dbh->options['autofree'];
793         $this->fetchmode   = $dbh->fetchmode;
794         $this->fetchmode_object_class = $dbh->fetchmode_object_class;
795     }
796
797     function setOption($key, $value = null)
798     {
799         switch ($key) {
800             case 'limit_from':
801                 $this->limit_from = $value; break;
802             case 'limit_count':
803                 $this->limit_count = $value; break;
804         }
805     }
806
807     // }}}
808     // {{{ fetchRow()
809
810     /**
811      * Fetch a row of data and return it by reference into an array.
812      *
813      * The type of array returned can be controlled either by setting this
814      * method's <var>$fetchmode</var> parameter or by changing the default
815      * fetch mode setFetchMode() before calling this method.
816      *
817      * There are two options for standardizing the information returned
818      * from databases, ensuring their values are consistent when changing
819      * DBMS's.  These portability options can be turned on when creating a
820      * new DB object or by using setOption().
821      *
822      *   + <samp>DB_PORTABILITY_LOWERCASE</samp>
823      *     convert names of fields to lower case
824      *
825      *   + <samp>DB_PORTABILITY_RTRIM</samp>
826      *     right trim the data
827      *
828      * @param int $fetchmode how the resulting array should be indexed
829      * @param int $rownum    the row number to fetch
830      *
831      * @return array a row of data, null on no more rows or PEAR_Error
832      *                object on error
833      *
834      * @see DB_common::setOption(), DB_common::setFetchMode()
835      * @access public
836      */
837     function &fetchRow($fetchmode = DB_FETCHMODE_DEFAULT, $rownum=null)
838     {
839         if ($fetchmode === DB_FETCHMODE_DEFAULT) {
840             $fetchmode = $this->fetchmode;
841         }
842         if ($fetchmode === DB_FETCHMODE_OBJECT) {
843             $fetchmode = DB_FETCHMODE_ASSOC;
844             $object_class = $this->fetchmode_object_class;
845         }
846         if ($this->limit_from !== null) {
847             if ($this->row_counter === null) {
848                 $this->row_counter = $this->limit_from;
849                 // Skip rows
850                 if ($this->limit_type == false) {
851                     $i = 0;
852                     while ($i++ < $this->limit_from) {
853                         $this->dbh->fetchInto($this->result, $arr, $fetchmode);
854                     }
855                 }
856             }
857             if ($this->row_counter >= (
858                     $this->limit_from + $this->limit_count))
859             {
860                 if ($this->autofree) {
861                     $this->free();
862                 }
863                 $tmp = null;
864                 return $tmp;
865             }
866             if ($this->limit_type == 'emulate') {
867                 $rownum = $this->row_counter;
868             }
869             $this->row_counter++;
870         }
871         $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
872         if ($res === DB_OK) {
873             if (isset($object_class)) {
874                 // default mode specified in DB_common::fetchmode_object_class property
875                 if ($object_class == 'stdClass') {
876                     $arr = (object) $arr;
877                 } else {
878                     $arr = new $object_class($arr);
879                 }
880             }
881             return $arr;
882         }
883         if ($res == null && $this->autofree) {
884             $this->free();
885         }
886         return $res;
887     }
888
889     // }}}
890     // {{{ fetchInto()
891
892     /**
893      * Fetch a row of data into an array which is passed by reference.
894      *
895      * The type of array returned can be controlled either by setting this
896      * method's <var>$fetchmode</var> parameter or by changing the default
897      * fetch mode setFetchMode() before calling this method.
898      *
899      * There are two options for standardizing the information returned
900      * from databases, ensuring their values are consistent when changing
901      * DBMS's.  These portability options can be turned on when creating a
902      * new DB object or by using setOption().
903      *
904      *   + <samp>DB_PORTABILITY_LOWERCASE</samp>
905      *     convert names of fields to lower case
906      *
907      *   + <samp>DB_PORTABILITY_RTRIM</samp>
908      *     right trim the data
909      *
910      * @param array &$arr       (reference) array where data from the row
911      *                          should be placed
912      * @param int $fetchmode how the resulting array should be indexed
913      * @param int $rownum    the row number to fetch
914      *
915      * @return mixed DB_OK on success, null on no more rows or
916      *                a DB_Error object on error
917      *
918      * @see DB_common::setOption(), DB_common::setFetchMode()
919      * @access public
920      */
921     function fetchInto(&$arr, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum=null)
922     {
923         if ($fetchmode === DB_FETCHMODE_DEFAULT) {
924             $fetchmode = $this->fetchmode;
925         }
926         if ($fetchmode === DB_FETCHMODE_OBJECT) {
927             $fetchmode = DB_FETCHMODE_ASSOC;
928             $object_class = $this->fetchmode_object_class;
929         }
930         if ($this->limit_from !== null) {
931             if ($this->row_counter === null) {
932                 $this->row_counter = $this->limit_from;
933                 // Skip rows
934                 if ($this->limit_type == false) {
935                     $i = 0;
936                     while ($i++ < $this->limit_from) {
937                         $this->dbh->fetchInto($this->result, $arr, $fetchmode);
938                     }
939                 }
940             }
941             if ($this->row_counter >= (
942                     $this->limit_from + $this->limit_count))
943             {
944                 if ($this->autofree) {
945                     $this->free();
946                 }
947                 return null;
948             }
949             if ($this->limit_type == 'emulate') {
950                 $rownum = $this->row_counter;
951             }
952
953             $this->row_counter++;
954         }
955         $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
956         if ($res === DB_OK) {
957             if (isset($object_class)) {
958                 // default mode specified in DB_common::fetchmode_object_class property
959                 if ($object_class == 'stdClass') {
960                     $arr = (object) $arr;
961                 } else {
962                     $arr = new $object_class($arr);
963                 }
964             }
965             return DB_OK;
966         }
967         if ($res == null && $this->autofree) {
968             $this->free();
969         }
970         return $res;
971     }
972
973     // }}}
974     // {{{ numCols()
975
976     /**
977      * Get the the number of columns in a result set.
978      *
979      * @return int the number of columns, or a DB error
980      *
981      * @access public
982      */
983     function numCols()
984     {
985         return $this->dbh->numCols($this->result);
986     }
987
988     // }}}
989     // {{{ numRows()
990
991     /**
992      * Get the number of rows in a result set.
993      *
994      * @return int the number of rows, or a DB error
995      *
996      * @access public
997      */
998     function numRows()
999     {
1000         return $this->dbh->numRows($this->result);
1001     }
1002
1003     // }}}
1004     // {{{ nextResult()
1005
1006     /**
1007      * Get the next result if a batch of queries was executed.
1008      *
1009      * @return bool true if a new result is available or false if not.
1010      *
1011      * @access public
1012      */
1013     function nextResult()
1014     {
1015         return $this->dbh->nextResult($this->result);
1016     }
1017
1018     // }}}
1019     // {{{ free()
1020
1021     /**
1022      * Frees the resources allocated for this result set.
1023      * @return int error code
1024      *
1025      * @access public
1026      */
1027     function free()
1028     {
1029         $err = $this->dbh->freeResult($this->result);
1030         if (DB::isError($err)) {
1031             return $err;
1032         }
1033         $this->result = false;
1034         return true;
1035     }
1036
1037     // }}}
1038     // {{{ tableInfo()
1039
1040     /**
1041      * @deprecated
1042      * @internal
1043      * @see DB_common::tableInfo()
1044      */
1045     function tableInfo($mode = null)
1046     {
1047         if (is_string($mode)) {
1048             return $this->dbh->raiseError(DB_ERROR_NEED_MORE_DATA);
1049         }
1050         return $this->dbh->tableInfo($this, $mode);
1051     }
1052
1053     // }}}
1054     // {{{ getRowCounter()
1055
1056     /**
1057      * returns the actual row number
1058      * @return integer
1059      */
1060     function getRowCounter()
1061     {
1062         return $this->row_counter;
1063     }
1064     // }}}
1065 }
1066
1067 // }}}
1068 // {{{ class DB_row
1069
1070 /**
1071  * Pear DB Row Object
1072  * @see DB_common::setFetchMode()
1073  */
1074 class DB_row
1075 {
1076     // {{{ constructor
1077
1078     /**
1079      * constructor
1080      *
1081      * @param resource row data as array
1082      */
1083     function DB_row(&$arr)
1084     {
1085         foreach ($arr as $key => $value) {
1086             $this->$key = &$arr[$key];
1087         }
1088     }
1089
1090     // }}}
1091 }
1092
1093 // }}}
1094
1095 /*
1096  * Local variables:
1097  * tab-width: 8
1098  * c-basic-offset: 4
1099  * End:
1100  */
1101
1102 ?>