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