fix image text
[pear] / MDB2.php
1 <?php
2 // vim: set et ts=4 sw=4 fdm=marker:
3 // +----------------------------------------------------------------------+
4 // | PHP versions 4 and 5                                                 |
5 // +----------------------------------------------------------------------+
6 // | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox,                 |
7 // | Stig. S. Bakken, Lukas Smith                                         |
8 // | All rights reserved.                                                 |
9 // +----------------------------------------------------------------------+
10 // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
11 // | API as well as database abstraction for PHP applications.            |
12 // | This LICENSE is in the BSD license style.                            |
13 // |                                                                      |
14 // | Redistribution and use in source and binary forms, with or without   |
15 // | modification, are permitted provided that the following conditions   |
16 // | are met:                                                             |
17 // |                                                                      |
18 // | Redistributions of source code must retain the above copyright       |
19 // | notice, this list of conditions and the following disclaimer.        |
20 // |                                                                      |
21 // | Redistributions in binary form must reproduce the above copyright    |
22 // | notice, this list of conditions and the following disclaimer in the  |
23 // | documentation and/or other materials provided with the distribution. |
24 // |                                                                      |
25 // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
26 // | Lukas Smith nor the names of his contributors may be used to endorse |
27 // | or promote products derived from this software without specific prior|
28 // | written permission.                                                  |
29 // |                                                                      |
30 // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
31 // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
32 // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
33 // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
34 // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
35 // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
36 // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
37 // |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
38 // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
39 // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
40 // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
41 // | POSSIBILITY OF SUCH DAMAGE.                                          |
42 // +----------------------------------------------------------------------+
43 // | Author: Lukas Smith <smith@pooteeweet.org>                           |
44 // +----------------------------------------------------------------------+
45 //
46 // $Id$
47 //
48
49 /**
50  * @package     MDB2
51  * @category    Database
52  * @author      Lukas Smith <smith@pooteeweet.org>
53  */
54
55 require_once 'PEAR.php';
56
57 // {{{ Error constants
58
59 /**
60  * The method mapErrorCode in each MDB2_dbtype implementation maps
61  * native error codes to one of these.
62  *
63  * If you add an error code here, make sure you also add a textual
64  * version of it in MDB2::errorMessage().
65  */
66
67 define('MDB2_OK',                      true);
68 define('MDB2_ERROR',                     -1);
69 define('MDB2_ERROR_SYNTAX',              -2);
70 define('MDB2_ERROR_CONSTRAINT',          -3);
71 define('MDB2_ERROR_NOT_FOUND',           -4);
72 define('MDB2_ERROR_ALREADY_EXISTS',      -5);
73 define('MDB2_ERROR_UNSUPPORTED',         -6);
74 define('MDB2_ERROR_MISMATCH',            -7);
75 define('MDB2_ERROR_INVALID',             -8);
76 define('MDB2_ERROR_NOT_CAPABLE',         -9);
77 define('MDB2_ERROR_TRUNCATED',          -10);
78 define('MDB2_ERROR_INVALID_NUMBER',     -11);
79 define('MDB2_ERROR_INVALID_DATE',       -12);
80 define('MDB2_ERROR_DIVZERO',            -13);
81 define('MDB2_ERROR_NODBSELECTED',       -14);
82 define('MDB2_ERROR_CANNOT_CREATE',      -15);
83 define('MDB2_ERROR_CANNOT_DELETE',      -16);
84 define('MDB2_ERROR_CANNOT_DROP',        -17);
85 define('MDB2_ERROR_NOSUCHTABLE',        -18);
86 define('MDB2_ERROR_NOSUCHFIELD',        -19);
87 define('MDB2_ERROR_NEED_MORE_DATA',     -20);
88 define('MDB2_ERROR_NOT_LOCKED',         -21);
89 define('MDB2_ERROR_VALUE_COUNT_ON_ROW', -22);
90 define('MDB2_ERROR_INVALID_DSN',        -23);
91 define('MDB2_ERROR_CONNECT_FAILED',     -24);
92 define('MDB2_ERROR_EXTENSION_NOT_FOUND',-25);
93 define('MDB2_ERROR_NOSUCHDB',           -26);
94 define('MDB2_ERROR_ACCESS_VIOLATION',   -27);
95 define('MDB2_ERROR_CANNOT_REPLACE',     -28);
96 define('MDB2_ERROR_CONSTRAINT_NOT_NULL',-29);
97 define('MDB2_ERROR_DEADLOCK',           -30);
98 define('MDB2_ERROR_CANNOT_ALTER',       -31);
99 define('MDB2_ERROR_MANAGER',            -32);
100 define('MDB2_ERROR_MANAGER_PARSE',      -33);
101 define('MDB2_ERROR_LOADMODULE',         -34);
102 define('MDB2_ERROR_INSUFFICIENT_DATA',  -35);
103 define('MDB2_ERROR_NO_PERMISSION',      -36);
104 define('MDB2_ERROR_DISCONNECT_FAILED',  -37);
105
106 // }}}
107 // {{{ Verbose constants
108 /**
109  * These are just helper constants to more verbosely express parameters to prepare()
110  */
111
112 define('MDB2_PREPARE_MANIP', false);
113 define('MDB2_PREPARE_RESULT', null);
114
115 // }}}
116 // {{{ Fetchmode constants
117
118 /**
119  * This is a special constant that tells MDB2 the user hasn't specified
120  * any particular get mode, so the default should be used.
121  */
122 define('MDB2_FETCHMODE_DEFAULT', 0);
123
124 /**
125  * Column data indexed by numbers, ordered from 0 and up
126  */
127 define('MDB2_FETCHMODE_ORDERED', 1);
128
129 /**
130  * Column data indexed by column names
131  */
132 define('MDB2_FETCHMODE_ASSOC', 2);
133
134 /**
135  * Column data as object properties
136  */
137 define('MDB2_FETCHMODE_OBJECT', 3);
138
139 /**
140  * For multi-dimensional results: normally the first level of arrays
141  * is the row number, and the second level indexed by column number or name.
142  * MDB2_FETCHMODE_FLIPPED switches this order, so the first level of arrays
143  * is the column name, and the second level the row number.
144  */
145 define('MDB2_FETCHMODE_FLIPPED', 4);
146
147 // }}}
148 // {{{ Portability mode constants
149
150 /**
151  * Portability: turn off all portability features.
152  * @see MDB2_Driver_Common::setOption()
153  */
154 define('MDB2_PORTABILITY_NONE', 0);
155
156 /**
157  * Portability: convert names of tables and fields to case defined in the
158  * "field_case" option when using the query*(), fetch*() and tableInfo() methods.
159  * @see MDB2_Driver_Common::setOption()
160  */
161 define('MDB2_PORTABILITY_FIX_CASE', 1);
162
163 /**
164  * Portability: right trim the data output by query*() and fetch*().
165  * @see MDB2_Driver_Common::setOption()
166  */
167 define('MDB2_PORTABILITY_RTRIM', 2);
168
169 /**
170  * Portability: force reporting the number of rows deleted.
171  * @see MDB2_Driver_Common::setOption()
172  */
173 define('MDB2_PORTABILITY_DELETE_COUNT', 4);
174
175 /**
176  * Portability: not needed in MDB2 (just left here for compatibility to DB)
177  * @see MDB2_Driver_Common::setOption()
178  */
179 define('MDB2_PORTABILITY_NUMROWS', 8);
180
181 /**
182  * Portability: makes certain error messages in certain drivers compatible
183  * with those from other DBMS's.
184  *
185  * + mysql, mysqli:  change unique/primary key constraints
186  *   MDB2_ERROR_ALREADY_EXISTS -> MDB2_ERROR_CONSTRAINT
187  *
188  * + odbc(access):  MS's ODBC driver reports 'no such field' as code
189  *   07001, which means 'too few parameters.'  When this option is on
190  *   that code gets mapped to MDB2_ERROR_NOSUCHFIELD.
191  *
192  * @see MDB2_Driver_Common::setOption()
193  */
194 define('MDB2_PORTABILITY_ERRORS', 16);
195
196 /**
197  * Portability: convert empty values to null strings in data output by
198  * query*() and fetch*().
199  * @see MDB2_Driver_Common::setOption()
200  */
201 define('MDB2_PORTABILITY_EMPTY_TO_NULL', 32);
202
203 /**
204  * Portability: removes database/table qualifiers from associative indexes
205  * @see MDB2_Driver_Common::setOption()
206  */
207 define('MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES', 64);
208
209 /**
210  * Portability: turn on all portability features.
211  * @see MDB2_Driver_Common::setOption()
212  */
213 define('MDB2_PORTABILITY_ALL', 127);
214
215 // }}}
216 // {{{ Globals for class instance tracking
217
218 /**
219  * These are global variables that are used to track the various class instances
220  */
221
222 $GLOBALS['_MDB2_databases'] = array();
223 $GLOBALS['_MDB2_dsninfo_default'] = array(
224     'phptype'  => false,
225     'dbsyntax' => false,
226     'username' => false,
227     'password' => false,
228     'protocol' => false,
229     'hostspec' => false,
230     'port'     => false,
231     'socket'   => false,
232     'database' => false,
233     'mode'     => false,
234 );
235
236 // }}}
237 // {{{ class MDB2
238
239 /**
240  * The main 'MDB2' class is simply a container class with some static
241  * methods for creating DB objects as well as some utility functions
242  * common to all parts of DB.
243  *
244  * The object model of MDB2 is as follows (indentation means inheritance):
245  *
246  * MDB2          The main MDB2 class.  This is simply a utility class
247  *              with some 'static' methods for creating MDB2 objects as
248  *              well as common utility functions for other MDB2 classes.
249  *
250  * MDB2_Driver_Common   The base for each MDB2 implementation.  Provides default
251  * |            implementations (in OO lingo virtual methods) for
252  * |            the actual DB implementations as well as a bunch of
253  * |            query utility functions.
254  * |
255  * +-MDB2_Driver_mysql  The MDB2 implementation for MySQL. Inherits MDB2_Driver_Common.
256  *              When calling MDB2::factory or MDB2::connect for MySQL
257  *              connections, the object returned is an instance of this
258  *              class.
259  * +-MDB2_Driver_pgsql  The MDB2 implementation for PostGreSQL. Inherits MDB2_Driver_Common.
260  *              When calling MDB2::factory or MDB2::connect for PostGreSQL
261  *              connections, the object returned is an instance of this
262  *              class.
263  *
264  * @package     MDB2
265  * @category    Database
266  * @author      Lukas Smith <smith@pooteeweet.org>
267  */
268 class MDB2
269 {
270     // {{{ function setOptions($db, $options)
271
272     /**
273      * set option array   in an exiting database object
274      *
275      * @param   MDB2_Driver_Common  MDB2 object
276      * @param   array   An associative array of option names and their values.
277      *
278      * @return mixed   MDB2_OK or a PEAR Error object
279      *
280      * @access  public
281      */
282     static function setOptions($db, $options)
283     {
284         if (is_array($options)) {
285             foreach ($options as $option => $value) {
286                 $test = $db->setOption($option, $value);
287                 if (PEAR::isError($test)) {
288                     return $test;
289                 }
290             }
291         }
292         return MDB2_OK;
293     }
294
295     // }}}
296     // {{{ function classExists($classname)
297
298     /**
299      * Checks if a class exists without triggering __autoload
300      *
301      * @param   string  classname
302      *
303      * @return  bool    true success and false on error
304      * @static
305      * @access  public
306      */
307     static function classExists($classname)
308     {
309         return class_exists($classname, false);
310     }
311
312     // }}}
313     // {{{ function loadClass($class_name, $debug)
314
315     /**
316      * Loads a PEAR class.
317      *
318      * @param   string  classname to load
319      * @param   bool    if errors should be suppressed
320      *
321      * @return  mixed   true success or PEAR_Error on failure
322      *
323      * @access  public
324      */
325     static function loadClass($class_name, $debug)
326     {
327         if (!MDB2::classExists($class_name)) {
328             $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
329             if ($debug) {
330                 $include = include_once($file_name);
331             } else {
332                 $include = @include_once($file_name);
333             }
334             if (!$include) {
335                 if (!MDB2::fileExists($file_name)) {
336                     $msg = "unable to find package '$class_name' file '$file_name'";
337                 } else {
338                     $msg = "unable to load class '$class_name' from file '$file_name'";
339                 }
340                 $err = MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null, $msg);
341                 return $err;
342             }
343             if (!MDB2::classExists($class_name)) {
344                 $msg = "unable to load class '$class_name' from file '$file_name'";
345                 $err = MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null, $msg);
346                 return $err;
347             }
348         }
349         return MDB2_OK;
350     }
351
352     // }}}
353     // {{{ function factory($dsn, $options = false)
354
355     /**
356      * Create a new MDB2 object for the specified database type
357      *
358      * @param   mixed   'data source name', see the MDB2::parseDSN
359      *                      method for a description of the dsn format.
360      *                      Can also be specified as an array of the
361      *                      format returned by MDB2::parseDSN.
362      * @param   array   An associative array of option names and
363      *                            their values.
364      *
365      * @return  mixed   a newly created MDB2 object, or false on error
366      *
367      * @access  public
368      */
369     static function factory($dsn, $options = false)
370     {
371         $dsninfo = MDB2::parseDSN($dsn);
372         if (empty($dsninfo['phptype'])) {
373             $err = MDB2::raiseError(MDB2_ERROR_NOT_FOUND,
374                 null, null, 'no RDBMS driver specified');
375             return $err;
376         }
377         $class_name = 'MDB2_Driver_'.$dsninfo['phptype'];
378
379         $debug = (!empty($options['debug']));
380         $err = MDB2::loadClass($class_name, $debug);
381         if (PEAR::isError($err)) {
382             return $err;
383         }
384
385         $db = new $class_name();
386         $db->setDSN($dsninfo);
387         $err = MDB2::setOptions($db, $options);
388         if (PEAR::isError($err)) {
389             return $err;
390         }
391
392         return $db;
393     }
394
395     // }}}
396     // {{{ function connect($dsn, $options = false)
397
398     /**
399      * Create a new MDB2_Driver_* connection object and connect to the specified
400      * database
401      *
402      * @param mixed $dsn     'data source name', see the MDB2::parseDSN
403      *                       method for a description of the dsn format.
404      *                       Can also be specified as an array of the
405      *                       format returned by MDB2::parseDSN.
406      * @param array $options An associative array of option names and
407      *                       their values.
408      *
409      * @return mixed a newly created MDB2 connection object, or a MDB2
410      *               error object on error
411      *
412      * @access  public
413      * @see     MDB2::parseDSN
414      */
415     static function connect($dsn, $options = false)
416     {
417         $db = MDB2::factory($dsn, $options);
418         if (PEAR::isError($db)) {
419             return $db;
420         }
421
422         $err = $db->connect();
423         if (PEAR::isError($err)) {
424             $dsn = $db->getDSN('string', 'xxx');
425             $db->disconnect();
426             $err->addUserInfo($dsn);
427             return $err;
428         }
429
430         return $db;
431     }
432
433     // }}}
434     // {{{ function singleton($dsn = null, $options = false)
435
436     /**
437      * Returns a MDB2 connection with the requested DSN.
438      * A new MDB2 connection object is only created if no object with the
439      * requested DSN exists yet.
440      *
441      * @param   mixed   'data source name', see the MDB2::parseDSN
442      *                            method for a description of the dsn format.
443      *                            Can also be specified as an array of the
444      *                            format returned by MDB2::parseDSN.
445      * @param   array   An associative array of option names and
446      *                            their values.
447      *
448      * @return  mixed   a newly created MDB2 connection object, or a MDB2
449      *                  error object on error
450      *
451      * @access  public
452      * @see     MDB2::parseDSN
453      */
454     static function singleton($dsn = null, $options = false)
455     {
456         if ($dsn) {
457             $dsninfo = MDB2::parseDSN($dsn);
458             $dsninfo = array_merge($GLOBALS['_MDB2_dsninfo_default'], $dsninfo);
459             $keys = array_keys($GLOBALS['_MDB2_databases']);
460             for ($i=0, $j=count($keys); $i<$j; ++$i) {
461                 if (isset($GLOBALS['_MDB2_databases'][$keys[$i]])) {
462                     $tmp_dsn = $GLOBALS['_MDB2_databases'][$keys[$i]]->getDSN('array');
463                     if (count(array_diff_assoc($tmp_dsn, $dsninfo)) == 0) {
464                         MDB2::setOptions($GLOBALS['_MDB2_databases'][$keys[$i]], $options);
465                         return $GLOBALS['_MDB2_databases'][$keys[$i]];
466                     }
467                 }
468             }
469         } elseif (is_array($GLOBALS['_MDB2_databases']) && reset($GLOBALS['_MDB2_databases'])) {
470             return $GLOBALS['_MDB2_databases'][key($GLOBALS['_MDB2_databases'])];
471         }
472         $db = MDB2::factory($dsn, $options);
473         return $db;
474     }
475
476     // }}}
477     // {{{ function areEquals()
478
479     /**
480      * It looks like there's a memory leak in array_diff() in PHP 5.1.x,
481      * so use this method instead.
482      * @see http://pear.php.net/bugs/bug.php?id=11790
483      *
484      * @param array $arr1
485      * @param array $arr2
486      * @return boolean
487      */
488     static function areEquals($arr1, $arr2)
489     {
490         if (count($arr1) != count($arr2)) {
491             return false;
492         }
493         foreach (array_keys($arr1) as $k) {
494             if (!array_key_exists($k, $arr2) || $arr1[$k] != $arr2[$k]) {
495                 return false;
496             }
497         }
498         return true;
499     }
500
501     // }}}
502     // {{{ function loadFile($file)
503
504     /**
505      * load a file (like 'Date')
506      *
507      * @param string $file name of the file in the MDB2 directory (without '.php')
508      *
509      * @return string name of the file that was included
510      *
511      * @access  public
512      */
513     static function loadFile($file)
514     {
515         $file_name = 'MDB2'.DIRECTORY_SEPARATOR.$file.'.php';
516         if (!MDB2::fileExists($file_name)) {
517             return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
518                 'unable to find: '.$file_name);
519         }
520         if (!include_once($file_name)) {
521             return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
522                 'unable to load driver class: '.$file_name);
523         }
524         return $file_name;
525     }
526
527     // }}}
528     // {{{ function apiVersion()
529
530     /**
531      * Return the MDB2 API version
532      *
533      * @return  string  the MDB2 API version number
534      *
535      * @access  public
536      */
537     function apiVersion()
538     {
539         return '@package_version@';
540     }
541
542     // }}}
543     // {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
544
545     /**
546      * This method is used to communicate an error and invoke error
547      * callbacks etc.  Basically a wrapper for PEAR::raiseError
548      * without the message string.
549      *
550      * @param   mixed  int error code
551      *
552      * @param   int    error mode, see PEAR_Error docs
553      *
554      * @param   mixed  If error mode is PEAR_ERROR_TRIGGER, this is the
555      *                 error level (E_USER_NOTICE etc).  If error mode is
556      *                 PEAR_ERROR_CALLBACK, this is the callback function,
557      *                 either as a function name, or as an array of an
558      *                 object and method name.  For other error modes this
559      *                 parameter is ignored.
560      *
561      * @param   string Extra debug information.  Defaults to the last
562      *                 query and native error code.
563      *
564      * @return PEAR_Error instance of a PEAR Error object
565      *
566      * @access  private
567      * @see     PEAR_Error
568      */
569     function &raiseError($code = null,
570                          $mode = null,
571                          $options = null,
572                          $userinfo = null,
573                          $dummy1 = null,
574                          $dummy2 = null,
575                          $dummy3 = false)
576     {
577         $err =& PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
578         return $err;
579     }
580
581     // }}}
582     // {{{ function isError($data, $code = null)
583
584     /**
585      * Tell whether a value is a MDB2 error.
586      *
587      * @param   mixed   the value to test
588      * @param   int     if is an error object, return true
589      *                        only if $code is a string and
590      *                        $db->getMessage() == $code or
591      *                        $code is an integer and $db->getCode() == $code
592      *
593      * @return  bool    true if parameter is an error
594      *
595      * @access  public
596      */
597     static function isError($data, $code = null)
598     {
599         if ($data instanceof MDB2_Error) {
600             if (null === $code) {
601                 return true;
602             }
603             if (is_string($code)) {
604                 return $data->getMessage() === $code;
605             }
606             return in_array($data->getCode(), (array)$code);
607         }
608         return false;
609     }
610
611     // }}}
612     // {{{ function isConnection($value)
613
614     /**
615      * Tell whether a value is a MDB2 connection
616      *
617      * @param   mixed   value to test
618      *
619      * @return  bool    whether $value is a MDB2 connection
620      * @access  public
621      */
622     function isConnection($value)
623     {
624         return ($value instanceof MDB2_Driver_Common);
625     }
626
627     // }}}
628     // {{{ function isResult($value)
629
630     /**
631      * Tell whether a value is a MDB2 result
632      *
633      * @param mixed $value value to test
634      *
635      * @return bool whether $value is a MDB2 result
636      *
637      * @access public
638      */
639     function isResult($value)
640     {
641         return ($value instanceof MDB2_Result);
642     }
643
644     // }}}
645     // {{{ function isResultCommon($value)
646
647     /**
648      * Tell whether a value is a MDB2 result implementing the common interface
649      *
650      * @param mixed $value value to test
651      *
652      * @return bool whether $value is a MDB2 result implementing the common interface
653      *
654      * @access  public
655      */
656     static function isResultCommon($value)
657     {
658         return ($value instanceof MDB2_Result_Common);
659     }
660
661     // }}}
662     // {{{ function isStatement($value)
663
664     /**
665      * Tell whether a value is a MDB2 statement interface
666      *
667      * @param   mixed   value to test
668      *
669      * @return  bool    whether $value is a MDB2 statement interface
670      *
671      * @access  public
672      */
673     function isStatement($value)
674     {
675         return ($value instanceof MDB2_Statement_Common);
676     }
677
678     // }}}
679     // {{{ function errorMessage($value = null)
680
681     /**
682      * Return a textual error message for a MDB2 error code
683      *
684      * @param   int|array   integer error code,
685                                 null to get the current error code-message map,
686                                 or an array with a new error code-message map
687      *
688      * @return  string  error message, or false if the error code was
689      *                  not recognized
690      *
691      * @access  public
692      */
693     static function errorMessage($value = null)
694     {
695         static $errorMessages;
696
697         if (is_array($value)) {
698             $errorMessages = $value;
699             return MDB2_OK;
700         }
701
702         if (!isset($errorMessages)) {
703             $errorMessages = array(
704                 MDB2_OK                       => 'no error',
705                 MDB2_ERROR                    => 'unknown error',
706                 MDB2_ERROR_ALREADY_EXISTS     => 'already exists',
707                 MDB2_ERROR_CANNOT_CREATE      => 'can not create',
708                 MDB2_ERROR_CANNOT_ALTER       => 'can not alter',
709                 MDB2_ERROR_CANNOT_REPLACE     => 'can not replace',
710                 MDB2_ERROR_CANNOT_DELETE      => 'can not delete',
711                 MDB2_ERROR_CANNOT_DROP        => 'can not drop',
712                 MDB2_ERROR_CONSTRAINT         => 'constraint violation',
713                 MDB2_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',
714                 MDB2_ERROR_DIVZERO            => 'division by zero',
715                 MDB2_ERROR_INVALID            => 'invalid',
716                 MDB2_ERROR_INVALID_DATE       => 'invalid date or time',
717                 MDB2_ERROR_INVALID_NUMBER     => 'invalid number',
718                 MDB2_ERROR_MISMATCH           => 'mismatch',
719                 MDB2_ERROR_NODBSELECTED       => 'no database selected',
720                 MDB2_ERROR_NOSUCHFIELD        => 'no such field',
721                 MDB2_ERROR_NOSUCHTABLE        => 'no such table',
722                 MDB2_ERROR_NOT_CAPABLE        => 'MDB2 backend not capable',
723                 MDB2_ERROR_NOT_FOUND          => 'not found',
724                 MDB2_ERROR_NOT_LOCKED         => 'not locked',
725                 MDB2_ERROR_SYNTAX             => 'syntax error',
726                 MDB2_ERROR_UNSUPPORTED        => 'not supported',
727                 MDB2_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
728                 MDB2_ERROR_INVALID_DSN        => 'invalid DSN',
729                 MDB2_ERROR_CONNECT_FAILED     => 'connect failed',
730                 MDB2_ERROR_NEED_MORE_DATA     => 'insufficient data supplied',
731                 MDB2_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
732                 MDB2_ERROR_NOSUCHDB           => 'no such database',
733                 MDB2_ERROR_ACCESS_VIOLATION   => 'insufficient permissions',
734                 MDB2_ERROR_LOADMODULE         => 'error while including on demand module',
735                 MDB2_ERROR_TRUNCATED          => 'truncated',
736                 MDB2_ERROR_DEADLOCK           => 'deadlock detected',
737                 MDB2_ERROR_NO_PERMISSION      => 'no permission',
738                 MDB2_ERROR_DISCONNECT_FAILED  => 'disconnect failed',
739             );
740         }
741
742         if (null === $value) {
743             return $errorMessages;
744         }
745
746         if (PEAR::isError($value)) {
747             $value = $value->getCode();
748         }
749
750         return isset($errorMessages[$value]) ?
751            $errorMessages[$value] : $errorMessages[MDB2_ERROR];
752     }
753
754     // }}}
755     // {{{ function parseDSN($dsn)
756
757     /**
758      * Parse a data source name.
759      *
760      * Additional keys can be added by appending a URI query string to the
761      * end of the DSN.
762      *
763      * The format of the supplied DSN is in its fullest form:
764      * <code>
765      *  phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
766      * </code>
767      *
768      * Most variations are allowed:
769      * <code>
770      *  phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
771      *  phptype://username:password@hostspec/database_name
772      *  phptype://username:password@hostspec
773      *  phptype://username@hostspec
774      *  phptype://hostspec/database
775      *  phptype://hostspec
776      *  phptype(dbsyntax)
777      *  phptype
778      * </code>
779      *
780      * @param   string  Data Source Name to be parsed
781      *
782      * @return  array   an associative array with the following keys:
783      *  + phptype:  Database backend used in PHP (mysql, odbc etc.)
784      *  + dbsyntax: Database used with regards to SQL syntax etc.
785      *  + protocol: Communication protocol to use (tcp, unix etc.)
786      *  + hostspec: Host specification (hostname[:port])
787      *  + database: Database to use on the DBMS server
788      *  + username: User name for login
789      *  + password: Password for login
790      *
791      * @access  public
792      * @author  Tomas V.V.Cox <cox@idecnet.com>
793      */
794     static function parseDSN($dsn)
795     {
796         $parsed = $GLOBALS['_MDB2_dsninfo_default'];
797
798         if (is_array($dsn)) {
799             $dsn = array_merge($parsed, $dsn);
800             if (!$dsn['dbsyntax']) {
801                 $dsn['dbsyntax'] = $dsn['phptype'];
802             }
803             return $dsn;
804         }
805
806         // Find phptype and dbsyntax
807         if (($pos = strpos($dsn, '://')) !== false) {
808             $str = substr($dsn, 0, $pos);
809             $dsn = substr($dsn, $pos + 3);
810         } else {
811             $str = $dsn;
812             $dsn = null;
813         }
814
815         // Get phptype and dbsyntax
816         // $str => phptype(dbsyntax)
817         if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
818             $parsed['phptype']  = $arr[1];
819             $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
820         } else {
821             $parsed['phptype']  = $str;
822             $parsed['dbsyntax'] = $str;
823         }
824
825         if (!count($dsn)) {
826             return $parsed;
827         }
828
829         // Get (if found): username and password
830         // $dsn => username:password@protocol+hostspec/database
831         if (($at = strrpos($dsn,'@')) !== false) {
832             $str = substr($dsn, 0, $at);
833             $dsn = substr($dsn, $at + 1);
834             if (($pos = strpos($str, ':')) !== false) {
835                 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
836                 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
837             } else {
838                 $parsed['username'] = rawurldecode($str);
839             }
840         }
841
842         // Find protocol and hostspec
843
844         // $dsn => proto(proto_opts)/database
845         if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
846             $proto       = $match[1];
847             $proto_opts  = $match[2] ? $match[2] : false;
848             $dsn         = $match[3];
849
850         // $dsn => protocol+hostspec/database (old format)
851         } else {
852             if (strpos($dsn, '+') !== false) {
853                 list($proto, $dsn) = explode('+', $dsn, 2);
854             }
855             if (   strpos($dsn, '//') === 0
856                 && strpos($dsn, '/', 2) !== false
857                 && $parsed['phptype'] == 'oci8'
858             ) {
859                 //oracle's "Easy Connect" syntax:
860                 //"username/password@[//]host[:port][/service_name]"
861                 //e.g. "scott/tiger@//mymachine:1521/oracle"
862                 $proto_opts = $dsn;
863                 $pos = strrpos($proto_opts, '/');
864                 $dsn = substr($proto_opts, $pos + 1);
865                 $proto_opts = substr($proto_opts, 0, $pos);
866             } elseif (strpos($dsn, '/') !== false) {
867                 list($proto_opts, $dsn) = explode('/', $dsn, 2);
868             } else {
869                 $proto_opts = $dsn;
870                 $dsn = null;
871             }
872         }
873
874         // process the different protocol options
875         $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
876         $proto_opts = rawurldecode($proto_opts);
877         if (strpos($proto_opts, ':') !== false) {
878             list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
879         }
880         if ($parsed['protocol'] == 'tcp') {
881             $parsed['hostspec'] = $proto_opts;
882         } elseif ($parsed['protocol'] == 'unix') {
883             $parsed['socket'] = $proto_opts;
884         }
885
886         // Get dabase if any
887         // $dsn => database
888         if ($dsn) {
889             // /database
890             if (($pos = strpos($dsn, '?')) === false) {
891                 $parsed['database'] = $dsn;
892             // /database?param1=value1&param2=value2
893             } else {
894                 $parsed['database'] = substr($dsn, 0, $pos);
895                 $dsn = substr($dsn, $pos + 1);
896                 if (strpos($dsn, '&') !== false) {
897                     $opts = explode('&', $dsn);
898                 } else { // database?param1=value1
899                     $opts = array($dsn);
900                 }
901                 foreach ($opts as $opt) {
902                     list($key, $value) = explode('=', $opt);
903                     if (!array_key_exists($key, $parsed) || false === $parsed[$key]) {
904                         // don't allow params overwrite
905                         $parsed[$key] = rawurldecode($value);
906                     }
907                 }
908             }
909         }
910
911         return $parsed;
912     }
913
914     // }}}
915     // {{{ function fileExists($file)
916
917     /**
918      * Checks if a file exists in the include path
919      *
920      * @param   string  filename
921      *
922      * @return  bool    true success and false on error
923      *
924      * @access  public
925      */
926     static function fileExists($file)
927     {
928         // safe_mode does notwork with is_readable()
929         if (!@ini_get('safe_mode')) {
930              $dirs = explode(PATH_SEPARATOR, ini_get('include_path'));
931              foreach ($dirs as $dir) {
932                  if (is_readable($dir . DIRECTORY_SEPARATOR . $file)) {
933                      return true;
934                  }
935             }
936         } else {
937             $fp = @fopen($file, 'r', true);
938             if (is_resource($fp)) {
939                 @fclose($fp);
940                 return true;
941             }
942         }
943         return false;
944     }
945     // }}}
946 }
947
948 // }}}
949 // {{{ class MDB2_Error extends PEAR_Error
950
951 /**
952  * MDB2_Error implements a class for reporting portable database error
953  * messages.
954  *
955  * @package     MDB2
956  * @category    Database
957  * @author Stig Bakken <ssb@fast.no>
958  */
959 class MDB2_Error extends PEAR_Error
960 {
961     // {{{ constructor: function MDB2_Error($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN, $level = E_USER_NOTICE, $debuginfo = null)
962
963     /**
964      * MDB2_Error constructor.
965      *
966      * @param   mixed   MDB2 error code, or string with error message.
967      * @param   int     what 'error mode' to operate in
968      * @param   int     what error level to use for $mode & PEAR_ERROR_TRIGGER
969      * @param   mixed   additional debug info, such as the last query
970      */
971     function __construct($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN,
972               $level = E_USER_NOTICE, $debuginfo = null, $dummy = null)
973     {
974         if (null === $code) {
975             $code = MDB2_ERROR;
976         }
977         parent::__construct('MDB2 Error: '.MDB2::errorMessage($code), $code,
978             $mode, $level, $debuginfo);
979     }
980
981     // }}}
982 }
983
984 // }}}
985 // {{{ class MDB2_Driver_Common extends PEAR
986
987 /**
988  * MDB2_Driver_Common: Base class that is extended by each MDB2 driver
989  *
990  * @package     MDB2
991  * @category    Database
992  * @author      Lukas Smith <smith@pooteeweet.org>
993  */
994 class MDB2_Driver_Common extends PEAR
995 {
996     // {{{ Variables (Properties)
997
998     /**
999      * index of the MDB2 object within the $GLOBALS['_MDB2_databases'] array
1000      * @var     int
1001      * @access  public
1002      */
1003     public $db_index = 0;
1004
1005     /**
1006      * DSN used for the next query
1007      * @var     array
1008      * @access  protected
1009      */
1010     public $dsn = array();
1011
1012     /**
1013      * DSN that was used to create the current connection
1014      * @var     array
1015      * @access  protected
1016      */
1017     public $connected_dsn = array();
1018
1019     /**
1020      * connection resource
1021      * @var     mixed
1022      * @access  protected
1023      */
1024     public $connection = 0;
1025
1026     /**
1027      * if the current opened connection is a persistent connection
1028      * @var     bool
1029      * @access  protected
1030      */
1031     public $opened_persistent;
1032
1033     /**
1034      * the name of the database for the next query
1035      * @var     string
1036      * @access  public
1037      */
1038     public $database_name = '';
1039
1040     /**
1041      * the name of the database currently selected
1042      * @var     string
1043      * @access  protected
1044      */
1045     public $connected_database_name = '';
1046
1047     /**
1048      * server version information
1049      * @var     string
1050      * @access  protected
1051      */
1052     public $connected_server_info = '';
1053
1054     /**
1055      * list of all supported features of the given driver
1056      * @var     array
1057      * @access  public
1058      */
1059     public $supported = array(
1060         'sequences' => false,
1061         'indexes' => false,
1062         'affected_rows' => false,
1063         'summary_functions' => false,
1064         'order_by_text' => false,
1065         'transactions' => false,
1066         'savepoints' => false,
1067         'current_id' => false,
1068         'limit_queries' => false,
1069         'LOBs' => false,
1070         'replace' => false,
1071         'sub_selects' => false,
1072         'triggers' => false,
1073         'auto_increment' => false,
1074         'primary_key' => false,
1075         'result_introspection' => false,
1076         'prepared_statements' => false,
1077         'identifier_quoting' => false,
1078         'pattern_escaping' => false,
1079         'new_link' => false,
1080     );
1081
1082     /**
1083      * Array of supported options that can be passed to the MDB2 instance.
1084      * 
1085      * The options can be set during object creation, using
1086      * MDB2::connect(), MDB2::factory() or MDB2::singleton(). The options can 
1087      * also be set after the object is created, using MDB2::setOptions() or 
1088      * MDB2_Driver_Common::setOption().
1089      * The list of available option includes:
1090      * <ul>
1091      *  <li>$options['ssl'] -> boolean: determines if ssl should be used for connections</li>
1092      *  <li>$options['field_case'] -> CASE_LOWER|CASE_UPPER: determines what case to force on field/table names</li>
1093      *  <li>$options['disable_query'] -> boolean: determines if queries should be executed</li>
1094      *  <li>$options['result_class'] -> string: class used for result sets</li>
1095      *  <li>$options['buffered_result_class'] -> string: class used for buffered result sets</li>
1096      *  <li>$options['result_wrap_class'] -> string: class used to wrap result sets into</li>
1097      *  <li>$options['result_buffering'] -> boolean should results be buffered or not?</li>
1098      *  <li>$options['fetch_class'] -> string: class to use when fetch mode object is used</li>
1099      *  <li>$options['persistent'] -> boolean: persistent connection?</li>
1100      *  <li>$options['debug'] -> integer: numeric debug level</li>
1101      *  <li>$options['debug_handler'] -> string: function/method that captures debug messages</li>
1102      *  <li>$options['debug_expanded_output'] -> bool: BC option to determine if more context information should be send to the debug handler</li>
1103      *  <li>$options['default_text_field_length'] -> integer: default text field length to use</li>
1104      *  <li>$options['lob_buffer_length'] -> integer: LOB buffer length</li>
1105      *  <li>$options['log_line_break'] -> string: line-break format</li>
1106      *  <li>$options['idxname_format'] -> string: pattern for index name</li>
1107      *  <li>$options['seqname_format'] -> string: pattern for sequence name</li>
1108      *  <li>$options['savepoint_format'] -> string: pattern for auto generated savepoint names</li>
1109      *  <li>$options['statement_format'] -> string: pattern for prepared statement names</li>
1110      *  <li>$options['seqcol_name'] -> string: sequence column name</li>
1111      *  <li>$options['quote_identifier'] -> boolean: if identifier quoting should be done when check_option is used</li>
1112      *  <li>$options['use_transactions'] -> boolean: if transaction use should be enabled</li>
1113      *  <li>$options['decimal_places'] -> integer: number of decimal places to handle</li>
1114      *  <li>$options['portability'] -> integer: portability constant</li>
1115      *  <li>$options['modules'] -> array: short to long module name mapping for __call()</li>
1116      *  <li>$options['emulate_prepared'] -> boolean: force prepared statements to be emulated</li>
1117      *  <li>$options['datatype_map'] -> array: map user defined datatypes to other primitive datatypes</li>
1118      *  <li>$options['datatype_map_callback'] -> array: callback function/method that should be called</li>
1119      *  <li>$options['bindname_format'] -> string: regular expression pattern for named parameters</li>
1120      *  <li>$options['multi_query'] -> boolean: determines if queries returning multiple result sets should be executed</li>
1121      *  <li>$options['max_identifiers_length'] -> integer: max identifier length</li>
1122      *  <li>$options['default_fk_action_onupdate'] -> string: default FOREIGN KEY ON UPDATE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']</li>
1123      *  <li>$options['default_fk_action_ondelete'] -> string: default FOREIGN KEY ON DELETE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']</li>
1124      * </ul>
1125      *
1126      * @var     array
1127      * @access  public
1128      * @see     MDB2::connect()
1129      * @see     MDB2::factory()
1130      * @see     MDB2::singleton()
1131      * @see     MDB2_Driver_Common::setOption()
1132      */
1133     public $options = array(
1134         'ssl' => false,
1135         'field_case' => CASE_LOWER,
1136         'disable_query' => false,
1137         'result_class' => 'MDB2_Result_%s',
1138         'buffered_result_class' => 'MDB2_BufferedResult_%s',
1139         'result_wrap_class' => false,
1140         'result_buffering' => true,
1141         'fetch_class' => 'stdClass',
1142         'persistent' => false,
1143         'debug' => 0,
1144         'debug_handler' => 'MDB2_defaultDebugOutput',
1145         'debug_expanded_output' => false,
1146         'default_text_field_length' => 4096,
1147         'lob_buffer_length' => 8192,
1148         'log_line_break' => "\n",
1149         'idxname_format' => '%s_idx',
1150         'seqname_format' => '%s_seq',
1151         'savepoint_format' => 'MDB2_SAVEPOINT_%s',
1152         'statement_format' => 'MDB2_STATEMENT_%1$s_%2$s',
1153         'seqcol_name' => 'sequence',
1154         'quote_identifier' => false,
1155         'use_transactions' => true,
1156         'decimal_places' => 2,
1157         'portability' => MDB2_PORTABILITY_ALL,
1158         'modules' => array(
1159             'ex' => 'Extended',
1160             'dt' => 'Datatype',
1161             'mg' => 'Manager',
1162             'rv' => 'Reverse',
1163             'na' => 'Native',
1164             'fc' => 'Function',
1165         ),
1166         'emulate_prepared' => false,
1167         'datatype_map' => array(),
1168         'datatype_map_callback' => array(),
1169         'nativetype_map_callback' => array(),
1170         'lob_allow_url_include' => false,
1171         'bindname_format' => '(?:\d+)|(?:[a-zA-Z][a-zA-Z0-9_]*)',
1172         'max_identifiers_length' => 30,
1173         'default_fk_action_onupdate' => 'RESTRICT',
1174         'default_fk_action_ondelete' => 'RESTRICT',
1175     );
1176
1177     /**
1178      * string array
1179      * @var     string
1180      * @access  public
1181      */
1182     public $string_quoting = array(
1183         'start'  => "'",
1184         'end'    => "'",
1185         'escape' => false,
1186         'escape_pattern' => false,
1187     );
1188
1189     /**
1190      * identifier quoting
1191      * @var     array
1192      * @access  public
1193      */
1194     public $identifier_quoting = array(
1195         'start'  => '"',
1196         'end'    => '"',
1197         'escape' => '"',
1198     );
1199
1200     /**
1201      * sql comments
1202      * @var     array
1203      * @access  protected
1204      */
1205     protected $sql_comments = array(
1206         array('start' => '--', 'end' => "\n", 'escape' => false),
1207         array('start' => '/*', 'end' => '*/', 'escape' => false),
1208     );
1209
1210     /**
1211      * comparision wildcards
1212      * @var     array
1213      * @access  protected
1214      */
1215     protected $wildcards = array('%', '_');
1216
1217     /**
1218      * column alias keyword
1219      * @var     string
1220      * @access  protected
1221      */
1222     public $as_keyword = ' AS ';
1223
1224     /**
1225      * warnings
1226      * @var     array
1227      * @access  protected
1228      */
1229     public $warnings = array();
1230
1231     /**
1232      * string with the debugging information
1233      * @var     string
1234      * @access  public
1235      */
1236     public $debug_output = '';
1237
1238     /**
1239      * determine if there is an open transaction
1240      * @var     bool
1241      * @access  protected
1242      */
1243     public $in_transaction = false;
1244
1245     /**
1246      * the smart transaction nesting depth
1247      * @var     int
1248      * @access  protected
1249      */
1250     public $nested_transaction_counter = null;
1251
1252     /**
1253      * the first error that occured inside a nested transaction
1254      * @var     MDB2_Error|bool
1255      * @access  protected
1256      */
1257     protected $has_transaction_error = false;
1258
1259     /**
1260      * result offset used in the next query
1261      * @var     int
1262      * @access  public
1263      */
1264     public $offset = 0;
1265
1266     /**
1267      * result limit used in the next query
1268      * @var     int
1269      * @access  public
1270      */
1271     public $limit = 0;
1272
1273     /**
1274      * Database backend used in PHP (mysql, odbc etc.)
1275      * @var     string
1276      * @access  public
1277      */
1278     public $phptype;
1279
1280     /**
1281      * Database used with regards to SQL syntax etc.
1282      * @var     string
1283      * @access  public
1284      */
1285     public $dbsyntax;
1286
1287     /**
1288      * the last query sent to the driver
1289      * @var     string
1290      * @access  public
1291      */
1292     public $last_query;
1293
1294     /**
1295      * the default fetchmode used
1296      * @var     int
1297      * @access  public
1298      */
1299     public $fetchmode = MDB2_FETCHMODE_ORDERED;
1300
1301     /**
1302      * array of module instances
1303      * @var     array
1304      * @access  protected
1305      */
1306     protected $modules = array();
1307
1308     /**
1309      * determines of the PHP4 destructor emulation has been enabled yet
1310      * @var     array
1311      * @access  protected
1312      */
1313     protected $destructor_registered = true;
1314
1315     // }}}
1316     // {{{ constructor: function __construct()
1317
1318     /**
1319      * Constructor
1320      */
1321     function __construct()
1322     {
1323         end($GLOBALS['_MDB2_databases']);
1324         $db_index = key($GLOBALS['_MDB2_databases']) + 1;
1325         $GLOBALS['_MDB2_databases'][$db_index] = &$this;
1326         $this->db_index = $db_index;
1327     }
1328
1329     // }}}
1330     // {{{ destructor: function __destruct()
1331
1332     /**
1333      *  Destructor
1334      */
1335     function __destruct()
1336     {
1337         $this->disconnect(false);
1338     }
1339
1340     // }}}
1341     // {{{ function free()
1342
1343     /**
1344      * Free the internal references so that the instance can be destroyed
1345      *
1346      * @return  bool    true on success, false if result is invalid
1347      *
1348      * @access  public
1349      */
1350     function free()
1351     {
1352         unset($GLOBALS['_MDB2_databases'][$this->db_index]);
1353         unset($this->db_index);
1354         return MDB2_OK;
1355     }
1356
1357     // }}}
1358     // {{{ function __toString()
1359
1360     /**
1361      * String conversation
1362      *
1363      * @return  string representation of the object
1364      *
1365      * @access  public
1366      */
1367     function __toString()
1368     {
1369         $info = get_class($this);
1370         $info.= ': (phptype = '.$this->phptype.', dbsyntax = '.$this->dbsyntax.')';
1371         if ($this->connection) {
1372             $info.= ' [connected]';
1373         }
1374         return $info;
1375     }
1376
1377     // }}}
1378     // {{{ function errorInfo($error = null)
1379
1380     /**
1381      * This method is used to collect information about an error
1382      *
1383      * @param   mixed   error code or resource
1384      *
1385      * @return  array   with MDB2 errorcode, native error code, native message
1386      *
1387      * @access  public
1388      */
1389     function errorInfo($error = null)
1390     {
1391         return array($error, null, null);
1392     }
1393
1394     // }}}
1395     // {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
1396
1397     /**
1398      * This method is used to communicate an error and invoke error
1399      * callbacks etc.  Basically a wrapper for PEAR::raiseError
1400      * without the message string.
1401      *
1402      * @param mixed  $code     integer error code, or a PEAR error object (all 
1403      *                         other parameters are ignored if this parameter is
1404      *                         an object
1405      * @param int    $mode     error mode, see PEAR_Error docs
1406      * @param mixed  $options  If error mode is PEAR_ERROR_TRIGGER, this is the
1407      *                         error level (E_USER_NOTICE etc). If error mode is
1408      *                         PEAR_ERROR_CALLBACK, this is the callback function,
1409      *                         either as a function name, or as an array of an
1410      *                         object and method name. For other error modes this
1411      *                         parameter is ignored.
1412      * @param string $userinfo Extra debug information. Defaults to the last
1413      *                         query and native error code.
1414      * @param string $method   name of the method that triggered the error
1415      * @param string $dummy1   not used
1416      * @param bool   $dummy2   not used
1417      *
1418      * @return PEAR_Error instance of a PEAR Error object
1419      * @access public
1420      * @see    PEAR_Error
1421      */
1422     function &raiseError($code = null,
1423                          $mode = null,
1424                          $options = null,
1425                          $userinfo = null,
1426                          $method = null,
1427                          $dummy1 = null,
1428                          $dummy2 = false
1429     ) {
1430         $userinfo = "[Error message: $userinfo]\n";
1431         // The error is yet a MDB2 error object
1432         if (PEAR::isError($code)) {
1433             // because we use the static PEAR::raiseError, our global
1434             // handler should be used if it is set
1435             if ((null === $mode) && !empty($this->_default_error_mode)) {
1436                 $mode    = $this->_default_error_mode;
1437                 $options = $this->_default_error_options;
1438             }
1439             if (null === $userinfo) {
1440                 $userinfo = $code->getUserinfo();
1441             }
1442             $code = $code->getCode();
1443         } elseif ($code == MDB2_ERROR_NOT_FOUND) {
1444             // extension not loaded: don't call $this->errorInfo() or the script
1445             // will die
1446         } elseif (isset($this->connection)) {
1447             if (!empty($this->last_query)) {
1448                 $userinfo.= "[Last executed query: {$this->last_query}]\n";
1449             }
1450             $native_errno = $native_msg = null;
1451             list($code, $native_errno, $native_msg) = $this->errorInfo($code);
1452             if ((null !== $native_errno) && $native_errno !== '') {
1453                 $userinfo.= "[Native code: $native_errno]\n";
1454             }
1455             if ((null !== $native_msg) && $native_msg !== '') {
1456                 $userinfo.= "[Native message: ". strip_tags($native_msg) ."]\n";
1457             }
1458             if (null !== $method) {
1459                 $userinfo = $method.': '.$userinfo;
1460             }
1461         }
1462
1463         $err = PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
1464         if ($err->getMode() !== PEAR_ERROR_RETURN
1465             && isset($this->nested_transaction_counter) && !$this->has_transaction_error) {
1466             $this->has_transaction_error = $err;
1467         }
1468         return $err;
1469     }
1470
1471     // }}}
1472     // {{{ function resetWarnings()
1473
1474     /**
1475      * reset the warning array
1476      *
1477      * @return void
1478      *
1479      * @access  public
1480      */
1481     function resetWarnings()
1482     {
1483         $this->warnings = array();
1484     }
1485
1486     // }}}
1487     // {{{ function getWarnings()
1488
1489     /**
1490      * Get all warnings in reverse order.
1491      * This means that the last warning is the first element in the array
1492      *
1493      * @return  array   with warnings
1494      *
1495      * @access  public
1496      * @see     resetWarnings()
1497      */
1498     function getWarnings()
1499     {
1500         return array_reverse($this->warnings);
1501     }
1502
1503     // }}}
1504     // {{{ function setFetchMode($fetchmode, $object_class = 'stdClass')
1505
1506     /**
1507      * Sets which fetch mode should be used by default on queries
1508      * on this connection
1509      *
1510      * @param   int     MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC
1511      *                               or MDB2_FETCHMODE_OBJECT
1512      * @param   string  the class name of the object to be returned
1513      *                               by the fetch methods when the
1514      *                               MDB2_FETCHMODE_OBJECT mode is selected.
1515      *                               If no class is specified by default a cast
1516      *                               to object from the assoc array row will be
1517      *                               done.  There is also the possibility to use
1518      *                               and extend the 'MDB2_row' class.
1519      *
1520      * @return  mixed   MDB2_OK or MDB2 Error Object
1521      *
1522      * @access  public
1523      * @see     MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC, MDB2_FETCHMODE_OBJECT
1524      */
1525     function setFetchMode($fetchmode, $object_class = 'stdClass')
1526     {
1527         switch ($fetchmode) {
1528         case MDB2_FETCHMODE_OBJECT:
1529             $this->options['fetch_class'] = $object_class;
1530         case MDB2_FETCHMODE_ORDERED:
1531         case MDB2_FETCHMODE_ASSOC:
1532             $this->fetchmode = $fetchmode;
1533             break;
1534         default:
1535             return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
1536                 'invalid fetchmode mode', __FUNCTION__);
1537         }
1538
1539         return MDB2_OK;
1540     }
1541
1542     // }}}
1543     // {{{ function setOption($option, $value)
1544
1545     /**
1546      * set the option for the db class
1547      *
1548      * @param   string  option name
1549      * @param   mixed   value for the option
1550      *
1551      * @return  mixed   MDB2_OK or MDB2 Error Object
1552      *
1553      * @access  public
1554      */
1555     function setOption($option, $value)
1556     {
1557         if (array_key_exists($option, $this->options)) {
1558             $this->options[$option] = $value;
1559             return MDB2_OK;
1560         }
1561         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
1562             "unknown option $option", __FUNCTION__);
1563     }
1564
1565     // }}}
1566     // {{{ function getOption($option)
1567
1568     /**
1569      * Returns the value of an option
1570      *
1571      * @param   string  option name
1572      *
1573      * @return  mixed   the option value or error object
1574      *
1575      * @access  public
1576      */
1577     function getOption($option)
1578     {
1579         if (array_key_exists($option, $this->options)) {
1580             return $this->options[$option];
1581         }
1582         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
1583             "unknown option $option", __FUNCTION__);
1584     }
1585
1586     // }}}
1587     // {{{ function debug($message, $scope = '', $is_manip = null)
1588
1589     /**
1590      * set a debug message
1591      *
1592      * @param   string  message that should be appended to the debug variable
1593      * @param   string  usually the method name that triggered the debug call:
1594      *                  for example 'query', 'prepare', 'execute', 'parameters',
1595      *                  'beginTransaction', 'commit', 'rollback'
1596      * @param   array   contains context information about the debug() call
1597      *                  common keys are: is_manip, time, result etc.
1598      *
1599      * @return void
1600      *
1601      * @access  public
1602      */
1603     function debug($message, $scope = '', $context = array())
1604     {
1605         if ($this->options['debug'] && $this->options['debug_handler']) {
1606             if (!$this->options['debug_expanded_output']) {
1607                 if (!empty($context['when']) && $context['when'] !== 'pre') {
1608                     return null;
1609                 }
1610                 $context = empty($context['is_manip']) ? false : $context['is_manip'];
1611             }
1612             return call_user_func_array($this->options['debug_handler'], array(&$this, $scope, $message, $context));
1613         }
1614         return null;
1615     }
1616
1617     // }}}
1618     // {{{ function getDebugOutput()
1619
1620     /**
1621      * output debug info
1622      *
1623      * @return  string  content of the debug_output class variable
1624      *
1625      * @access  public
1626      */
1627     function getDebugOutput()
1628     {
1629         return $this->debug_output;
1630     }
1631
1632     // }}}
1633     // {{{ function escape($text)
1634
1635     /**
1636      * Quotes a string so it can be safely used in a query. It will quote
1637      * the text so it can safely be used within a query.
1638      *
1639      * @param   string  the input string to quote
1640      * @param   bool    escape wildcards
1641      *
1642      * @return  string  quoted string
1643      *
1644      * @access  public
1645      */
1646     function escape($text, $escape_wildcards = false)
1647     {
1648         if ($escape_wildcards) {
1649             $text = $this->escapePattern($text);
1650         }
1651
1652         $text = str_replace($this->string_quoting['end'], $this->string_quoting['escape'] . $this->string_quoting['end'], $text);
1653         return $text;
1654     }
1655
1656     // }}}
1657     // {{{ function escapePattern($text)
1658
1659     /**
1660      * Quotes pattern (% and _) characters in a string)
1661      *
1662      * @param   string  the input string to quote
1663      *
1664      * @return  string  quoted string
1665      *
1666      * @access  public
1667      */
1668     function escapePattern($text)
1669     {
1670         if ($this->string_quoting['escape_pattern']) {
1671             $text = str_replace($this->string_quoting['escape_pattern'], $this->string_quoting['escape_pattern'] . $this->string_quoting['escape_pattern'], $text);
1672             foreach ($this->wildcards as $wildcard) {
1673                 $text = str_replace($wildcard, $this->string_quoting['escape_pattern'] . $wildcard, $text);
1674             }
1675         }
1676         return $text;
1677     }
1678
1679     // }}}
1680     // {{{ function quoteIdentifier($str, $check_option = false)
1681
1682     /**
1683      * Quote a string so it can be safely used as a table or column name
1684      *
1685      * Delimiting style depends on which database driver is being used.
1686      *
1687      * NOTE: just because you CAN use delimited identifiers doesn't mean
1688      * you SHOULD use them.  In general, they end up causing way more
1689      * problems than they solve.
1690      *
1691      * NOTE: if you have table names containing periods, don't use this method
1692      * (@see bug #11906)
1693      *
1694      * Portability is broken by using the following characters inside
1695      * delimited identifiers:
1696      *   + backtick (<kbd>`</kbd>) -- due to MySQL
1697      *   + double quote (<kbd>"</kbd>) -- due to Oracle
1698      *   + brackets (<kbd>[</kbd> or <kbd>]</kbd>) -- due to Access
1699      *
1700      * Delimited identifiers are known to generally work correctly under
1701      * the following drivers:
1702      *   + mssql
1703      *   + mysql
1704      *   + mysqli
1705      *   + oci8
1706      *   + pgsql
1707      *   + sqlite
1708      *
1709      * InterBase doesn't seem to be able to use delimited identifiers
1710      * via PHP 4.  They work fine under PHP 5.
1711      *
1712      * @param   string  identifier name to be quoted
1713      * @param   bool    check the 'quote_identifier' option
1714      *
1715      * @return  string  quoted identifier string
1716      *
1717      * @access  public
1718      */
1719     function quoteIdentifier($str, $check_option = false)
1720     {
1721         if ($check_option && !$this->options['quote_identifier']) {
1722             return $str;
1723         }
1724         $str = str_replace($this->identifier_quoting['end'], $this->identifier_quoting['escape'] . $this->identifier_quoting['end'], $str);
1725         $parts = explode('.', $str);
1726         foreach (array_keys($parts) as $k) {
1727             $parts[$k] = $this->identifier_quoting['start'] . $parts[$k] . $this->identifier_quoting['end'];
1728         }
1729         return implode('.', $parts);
1730     }
1731
1732     // }}}
1733     // {{{ function getAsKeyword()
1734
1735     /**
1736      * Gets the string to alias column
1737      *
1738      * @return string to use when aliasing a column
1739      */
1740     function getAsKeyword()
1741     {
1742         return $this->as_keyword;
1743     }
1744
1745     // }}}
1746     // {{{ function getConnection()
1747
1748     /**
1749      * Returns a native connection
1750      *
1751      * @return  mixed   a valid MDB2 connection object,
1752      *                  or a MDB2 error object on error
1753      *
1754      * @access  public
1755      */
1756     function getConnection()
1757     {
1758         $result = $this->connect();
1759         if (PEAR::isError($result)) {
1760             return $result;
1761         }
1762         return $this->connection;
1763     }
1764
1765      // }}}
1766     // {{{ function _fixResultArrayValues(&$row, $mode)
1767
1768     /**
1769      * Do all necessary conversions on result arrays to fix DBMS quirks
1770      *
1771      * @param   array   the array to be fixed (passed by reference)
1772      * @param   array   bit-wise addition of the required portability modes
1773      *
1774      * @return  void
1775      *
1776      * @access  protected
1777      */
1778     function _fixResultArrayValues(&$row, $mode)
1779     {
1780         switch ($mode) {
1781         case MDB2_PORTABILITY_EMPTY_TO_NULL:
1782             foreach ($row as $key => $value) {
1783                 if ($value === '') {
1784                     $row[$key] = null;
1785                 }
1786             }
1787             break;
1788         case MDB2_PORTABILITY_RTRIM:
1789             foreach ($row as $key => $value) {
1790                 if (is_string($value)) {
1791                     $row[$key] = rtrim($value);
1792                 }
1793             }
1794             break;
1795         case MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES:
1796             $tmp_row = array();
1797             foreach ($row as $key => $value) {
1798                 $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
1799             }
1800             $row = $tmp_row;
1801             break;
1802         case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL):
1803             foreach ($row as $key => $value) {
1804                 if ($value === '') {
1805                     $row[$key] = null;
1806                 } elseif (is_string($value)) {
1807                     $row[$key] = rtrim($value);
1808                 }
1809             }
1810             break;
1811         case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
1812             $tmp_row = array();
1813             foreach ($row as $key => $value) {
1814                 if (is_string($value)) {
1815                     $value = rtrim($value);
1816                 }
1817                 $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
1818             }
1819             $row = $tmp_row;
1820             break;
1821         case (MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
1822             $tmp_row = array();
1823             foreach ($row as $key => $value) {
1824                 if ($value === '') {
1825                     $value = null;
1826                 }
1827                 $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
1828             }
1829             $row = $tmp_row;
1830             break;
1831         case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
1832             $tmp_row = array();
1833             foreach ($row as $key => $value) {
1834                 if ($value === '') {
1835                     $value = null;
1836                 } elseif (is_string($value)) {
1837                     $value = rtrim($value);
1838                 }
1839                 $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
1840             }
1841             $row = $tmp_row;
1842             break;
1843         }
1844     }
1845
1846     // }}}
1847     // {{{ function loadModule($module, $property = null, $phptype_specific = null)
1848
1849     /**
1850      * loads a module
1851      *
1852      * @param   string  name of the module that should be loaded
1853      *                  (only used for error messages)
1854      * @param   string  name of the property into which the class will be loaded
1855      * @param   bool    if the class to load for the module is specific to the
1856      *                  phptype
1857      *
1858      * @return  object  on success a reference to the given module is returned
1859      *                  and on failure a PEAR error
1860      *
1861      * @access  public
1862      */
1863     function loadModule($module, $property = null, $phptype_specific = null)
1864     {
1865         if (!$property) {
1866             $property = strtolower($module);
1867         }
1868
1869         if (!isset($this->{$property})) {
1870             $version = $phptype_specific;
1871             if ($phptype_specific !== false) {
1872                 $version = true;
1873                 $class_name = 'MDB2_Driver_'.$module.'_'.$this->phptype;
1874                 $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
1875             }
1876             if ($phptype_specific === false
1877                 || (!MDB2::classExists($class_name) && !MDB2::fileExists($file_name))
1878             ) {
1879                 $version = false;
1880                 $class_name = 'MDB2_'.$module;
1881                 $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
1882             }
1883
1884             $err = MDB2::loadClass($class_name, $this->getOption('debug'));
1885             if (PEAR::isError($err)) {
1886                 return $err;
1887             }
1888
1889             // load module in a specific version
1890             if ($version) {
1891                 if (method_exists($class_name, 'getClassName')) {
1892                     $class_name_new = call_user_func(array($class_name, 'getClassName'), $this->db_index);
1893                     if ($class_name != $class_name_new) {
1894                         $class_name = $class_name_new;
1895                         $err = MDB2::loadClass($class_name, $this->getOption('debug'));
1896                         if (PEAR::isError($err)) {
1897                             return $err;
1898                         }
1899                     }
1900                 }
1901             }
1902
1903             if (!MDB2::classExists($class_name)) {
1904                 $err = $this->raiseError(MDB2_ERROR_LOADMODULE, null, null,
1905                     "unable to load module '$module' into property '$property'", __FUNCTION__);
1906                 return $err;
1907             }
1908             $this->{$property} = new $class_name($this->db_index);
1909             $this->modules[$module] = $this->{$property};
1910             if ($version) {
1911                 // this will be used in the connect method to determine if the module
1912                 // needs to be loaded with a different version if the server
1913                 // version changed in between connects
1914                 $this->loaded_version_modules[] = $property;
1915             }
1916         }
1917
1918         return $this->{$property};
1919     }
1920
1921     // }}}
1922     // {{{ function __call($method, $params)
1923
1924     /**
1925      * Calls a module method using the __call magic method
1926      *
1927      * @param   string  Method name.
1928      * @param   array   Arguments.
1929      *
1930      * @return  mixed   Returned value.
1931      */
1932     function __call($method, $params)
1933     {
1934         $module = null;
1935         if (preg_match('/^([a-z]+)([A-Z])(.*)$/', $method, $match)
1936             && isset($this->options['modules'][$match[1]])
1937         ) {
1938             $module = $this->options['modules'][$match[1]];
1939             $method = strtolower($match[2]).$match[3];
1940             if (!isset($this->modules[$module]) || !is_object($this->modules[$module])) {
1941                 $result = $this->loadModule($module);
1942                 if (PEAR::isError($result)) {
1943                     return $result;
1944                 }
1945             }
1946         } else {
1947             foreach ($this->modules as $key => $foo) {
1948                 if (is_object($this->modules[$key])
1949                     && method_exists($this->modules[$key], $method)
1950                 ) {
1951                     $module = $key;
1952                     break;
1953                 }
1954             }
1955         }
1956         if (null !== $module) {
1957             return call_user_func_array(array(&$this->modules[$module], $method), $params);
1958         }
1959         trigger_error(sprintf('Call to undefined function: %s::%s().', get_class($this), $method), E_USER_ERROR);
1960     }
1961
1962     // }}}
1963     // {{{ function beginTransaction($savepoint = null)
1964
1965     /**
1966      * Start a transaction or set a savepoint.
1967      *
1968      * @param   string  name of a savepoint to set
1969      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
1970      *
1971      * @access  public
1972      */
1973     function beginTransaction($savepoint = null)
1974     {
1975         $this->debug('Starting transaction', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
1976         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
1977             'transactions are not supported', __FUNCTION__);
1978     }
1979
1980     // }}}
1981     // {{{ function commit($savepoint = null)
1982
1983     /**
1984      * Commit the database changes done during a transaction that is in
1985      * progress or release a savepoint. This function may only be called when
1986      * auto-committing is disabled, otherwise it will fail. Therefore, a new
1987      * transaction is implicitly started after committing the pending changes.
1988      *
1989      * @param   string  name of a savepoint to release
1990      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
1991      *
1992      * @access  public
1993      */
1994     function commit($savepoint = null)
1995     {
1996         $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
1997         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
1998             'commiting transactions is not supported', __FUNCTION__);
1999     }
2000
2001     // }}}
2002     // {{{ function rollback($savepoint = null)
2003
2004     /**
2005      * Cancel any database changes done during a transaction or since a specific
2006      * savepoint that is in progress. This function may only be called when
2007      * auto-committing is disabled, otherwise it will fail. Therefore, a new
2008      * transaction is implicitly started after canceling the pending changes.
2009      *
2010      * @param   string  name of a savepoint to rollback to
2011      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
2012      *
2013      * @access  public
2014      */
2015     function rollback($savepoint = null)
2016     {
2017         $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
2018         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2019             'rolling back transactions is not supported', __FUNCTION__);
2020     }
2021
2022     // }}}
2023     // {{{ function inTransaction($ignore_nested = false)
2024
2025     /**
2026      * If a transaction is currently open.
2027      *
2028      * @param   bool    if the nested transaction count should be ignored
2029      * @return  int|bool    - an integer with the nesting depth is returned if a
2030      *                      nested transaction is open
2031      *                      - true is returned for a normal open transaction
2032      *                      - false is returned if no transaction is open
2033      *
2034      * @access  public
2035      */
2036     function inTransaction($ignore_nested = false)
2037     {
2038         if (!$ignore_nested && isset($this->nested_transaction_counter)) {
2039             return $this->nested_transaction_counter;
2040         }
2041         return $this->in_transaction;
2042     }
2043
2044     // }}}
2045     // {{{ function setTransactionIsolation($isolation)
2046
2047     /**
2048      * Set the transacton isolation level.
2049      *
2050      * @param   string  standard isolation level
2051      *                  READ UNCOMMITTED (allows dirty reads)
2052      *                  READ COMMITTED (prevents dirty reads)
2053      *                  REPEATABLE READ (prevents nonrepeatable reads)
2054      *                  SERIALIZABLE (prevents phantom reads)
2055      * @param   array some transaction options:
2056      *                  'wait' => 'WAIT' | 'NO WAIT'
2057      *                  'rw'   => 'READ WRITE' | 'READ ONLY'
2058      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
2059      *
2060      * @access  public
2061      * @since   2.1.1
2062      */
2063     function setTransactionIsolation($isolation, $options = array())
2064     {
2065         $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
2066         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2067             'isolation level setting is not supported', __FUNCTION__);
2068     }
2069
2070     // }}}
2071     // {{{ function beginNestedTransaction($savepoint = false)
2072
2073     /**
2074      * Start a nested transaction.
2075      *
2076      * @return  mixed   MDB2_OK on success/savepoint name, a MDB2 error on failure
2077      *
2078      * @access  public
2079      * @since   2.1.1
2080      */
2081     function beginNestedTransaction()
2082     {
2083         if ($this->in_transaction) {
2084             ++$this->nested_transaction_counter;
2085             $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
2086             if ($this->supports('savepoints') && $savepoint) {
2087                 return $this->beginTransaction($savepoint);
2088             }
2089             return MDB2_OK;
2090         }
2091         $this->has_transaction_error = false;
2092         $result = $this->beginTransaction();
2093         $this->nested_transaction_counter = 1;
2094         return $result;
2095     }
2096
2097     // }}}
2098     // {{{ function completeNestedTransaction($force_rollback = false, $release = false)
2099
2100     /**
2101      * Finish a nested transaction by rolling back if an error occured or
2102      * committing otherwise.
2103      *
2104      * @param   bool    if the transaction should be rolled back regardless
2105      *                  even if no error was set within the nested transaction
2106      * @return  mixed   MDB_OK on commit/counter decrementing, false on rollback
2107      *                  and a MDB2 error on failure
2108      *
2109      * @access  public
2110      * @since   2.1.1
2111      */
2112     function completeNestedTransaction($force_rollback = false)
2113     {
2114         if ($this->nested_transaction_counter > 1) {
2115             $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
2116             if ($this->supports('savepoints') && $savepoint) {
2117                 if ($force_rollback || $this->has_transaction_error) {
2118                     $result = $this->rollback($savepoint);
2119                     if (!PEAR::isError($result)) {
2120                         $result = false;
2121                         $this->has_transaction_error = false;
2122                     }
2123                 } else {
2124                     $result = $this->commit($savepoint);
2125                 }
2126             } else {
2127                 $result = MDB2_OK;
2128             }
2129             --$this->nested_transaction_counter;
2130             return $result;
2131         }
2132
2133         $this->nested_transaction_counter = null;
2134         $result = MDB2_OK;
2135
2136         // transaction has not yet been rolled back
2137         if ($this->in_transaction) {
2138             if ($force_rollback || $this->has_transaction_error) {
2139                 $result = $this->rollback();
2140                 if (!PEAR::isError($result)) {
2141                     $result = false;
2142                 }
2143             } else {
2144                 $result = $this->commit();
2145             }
2146         }
2147         $this->has_transaction_error = false;
2148         return $result;
2149     }
2150
2151     // }}}
2152     // {{{ function failNestedTransaction($error = null, $immediately = false)
2153
2154     /**
2155      * Force setting nested transaction to failed.
2156      *
2157      * @param   mixed   value to return in getNestededTransactionError()
2158      * @param   bool    if the transaction should be rolled back immediately
2159      * @return  bool    MDB2_OK
2160      *
2161      * @access  public
2162      * @since   2.1.1
2163      */
2164     function failNestedTransaction($error = null, $immediately = false)
2165     {
2166         if (null !== $error) {
2167             $error = $this->has_transaction_error ? $this->has_transaction_error : true;
2168         } elseif (!$error) {
2169             $error = true;
2170         }
2171         $this->has_transaction_error = $error;
2172         if (!$immediately) {
2173             return MDB2_OK;
2174         }
2175         return $this->rollback();
2176     }
2177
2178     // }}}
2179     // {{{ function getNestedTransactionError()
2180
2181     /**
2182      * The first error that occured since the transaction start.
2183      *
2184      * @return  MDB2_Error|bool     MDB2 error object if an error occured or false.
2185      *
2186      * @access  public
2187      * @since   2.1.1
2188      */
2189     function getNestedTransactionError()
2190     {
2191         return $this->has_transaction_error;
2192     }
2193
2194     // }}}
2195     // {{{ connect()
2196
2197     /**
2198      * Connect to the database
2199      *
2200      * @return true on success, MDB2 Error Object on failure
2201      */
2202     function connect()
2203     {
2204         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2205             'method not implemented', __FUNCTION__);
2206     }
2207
2208     // }}}
2209     // {{{ databaseExists()
2210
2211     /**
2212      * check if given database name is exists?
2213      *
2214      * @param string $name    name of the database that should be checked
2215      *
2216      * @return mixed true/false on success, a MDB2 error on failure
2217      * @access public
2218      */
2219     function databaseExists($name)
2220     {
2221         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2222             'method not implemented', __FUNCTION__);
2223     }
2224
2225     // }}}
2226     // {{{ setCharset($charset, $connection = null)
2227
2228     /**
2229      * Set the charset on the current connection
2230      *
2231      * @param string    charset
2232      * @param resource  connection handle
2233      *
2234      * @return true on success, MDB2 Error Object on failure
2235      */
2236     function setCharset($charset, $connection = null)
2237     {
2238         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2239             'method not implemented', __FUNCTION__);
2240     }
2241
2242     // }}}
2243     // {{{ function disconnect($force = true)
2244
2245     /**
2246      * Log out and disconnect from the database.
2247      *
2248      * @param boolean $force whether the disconnect should be forced even if the
2249      *                       connection is opened persistently
2250      *
2251      * @return mixed true on success, false if not connected and error object on error
2252      *
2253      * @access  public
2254      */
2255     function disconnect($force = true)
2256     {
2257         $this->connection = 0;
2258         $this->connected_dsn = array();
2259         $this->connected_database_name = '';
2260         $this->opened_persistent = null;
2261         $this->connected_server_info = '';
2262         $this->in_transaction = null;
2263         $this->nested_transaction_counter = null;
2264         return MDB2_OK;
2265     }
2266
2267     // }}}
2268     // {{{ function setDatabase($name)
2269
2270     /**
2271      * Select a different database
2272      *
2273      * @param   string  name of the database that should be selected
2274      *
2275      * @return  string  name of the database previously connected to
2276      *
2277      * @access  public
2278      */
2279     function setDatabase($name)
2280     {
2281         $previous_database_name = (isset($this->database_name)) ? $this->database_name : '';
2282         $this->database_name = $name;
2283         if (!empty($this->connected_database_name) && ($this->connected_database_name != $this->database_name)) {
2284             $this->disconnect(false);
2285         }
2286         return $previous_database_name;
2287     }
2288
2289     // }}}
2290     // {{{ function getDatabase()
2291
2292     /**
2293      * Get the current database
2294      *
2295      * @return  string  name of the database
2296      *
2297      * @access  public
2298      */
2299     function getDatabase()
2300     {
2301         return $this->database_name;
2302     }
2303
2304     // }}}
2305     // {{{ function setDSN($dsn)
2306
2307     /**
2308      * set the DSN
2309      *
2310      * @param   mixed   DSN string or array
2311      *
2312      * @return  MDB2_OK
2313      *
2314      * @access  public
2315      */
2316     function setDSN($dsn)
2317     {
2318         $dsn_default = $GLOBALS['_MDB2_dsninfo_default'];
2319         $dsn = MDB2::parseDSN($dsn);
2320         if (array_key_exists('database', $dsn)) {
2321             $this->database_name = $dsn['database'];
2322             unset($dsn['database']);
2323         }
2324         $this->dsn = array_merge($dsn_default, $dsn);
2325         return $this->disconnect(false);
2326     }
2327
2328     // }}}
2329     // {{{ function getDSN($type = 'string', $hidepw = false)
2330
2331     /**
2332      * return the DSN as a string
2333      *
2334      * @param   string  format to return ("array", "string")
2335      * @param   string  string to hide the password with
2336      *
2337      * @return  mixed   DSN in the chosen type
2338      *
2339      * @access  public
2340      */
2341     function getDSN($type = 'string', $hidepw = false)
2342     {
2343         $dsn = array_merge($GLOBALS['_MDB2_dsninfo_default'], $this->dsn);
2344         $dsn['phptype'] = $this->phptype;
2345         $dsn['database'] = $this->database_name;
2346         if ($hidepw) {
2347             $dsn['password'] = $hidepw;
2348         }
2349         switch ($type) {
2350         // expand to include all possible options
2351         case 'string':
2352            $dsn = $dsn['phptype'].
2353                ($dsn['dbsyntax'] ? ('('.$dsn['dbsyntax'].')') : '').
2354                '://'.$dsn['username'].':'.
2355                 $dsn['password'].'@'.$dsn['hostspec'].
2356                 ($dsn['port'] ? (':'.$dsn['port']) : '').
2357                 '/'.$dsn['database'];
2358             break;
2359         case 'array':
2360         default:
2361             break;
2362         }
2363         return $dsn;
2364     }
2365
2366     // }}}
2367     // {{{ _isNewLinkSet()
2368
2369     /**
2370      * Check if the 'new_link' option is set
2371      *
2372      * @return boolean
2373      *
2374      * @access protected
2375      */
2376     function _isNewLinkSet()
2377     {
2378         return (isset($this->dsn['new_link'])
2379             && ($this->dsn['new_link'] === true
2380              || (is_string($this->dsn['new_link']) && preg_match('/^true$/i', $this->dsn['new_link']))
2381              || (is_numeric($this->dsn['new_link']) && 0 != (int)$this->dsn['new_link'])
2382             )
2383         );
2384     }
2385
2386     // }}}
2387     // {{{ function &standaloneQuery($query, $types = null, $is_manip = false)
2388
2389    /**
2390      * execute a query as database administrator
2391      *
2392      * @param   string  the SQL query
2393      * @param   mixed   array that contains the types of the columns in
2394      *                        the result set
2395      * @param   bool    if the query is a manipulation query
2396      *
2397      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
2398      *
2399      * @access  public
2400      */
2401     function standaloneQuery($query, $types = null, $is_manip = false)
2402     {
2403         $offset = $this->offset;
2404         $limit = $this->limit;
2405         $this->offset = $this->limit = 0;
2406         $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
2407
2408         $connection = $this->getConnection();
2409         if (PEAR::isError($connection)) {
2410             return $connection;
2411         }
2412
2413         $result = $this->_doQuery($query, $is_manip, $connection, false);
2414         if (PEAR::isError($result)) {
2415             return $result;
2416         }
2417
2418         if ($is_manip) {
2419             $affected_rows =  $this->_affectedRows($connection, $result);
2420             return $affected_rows;
2421         }
2422         $result = $this->_wrapResult($result, $types, true, false, $limit, $offset);
2423         return $result;
2424     }
2425
2426     // }}}
2427     // {{{ function _modifyQuery($query, $is_manip, $limit, $offset)
2428
2429     /**
2430      * Changes a query string for various DBMS specific reasons
2431      *
2432      * @param   string  query to modify
2433      * @param   bool    if it is a DML query
2434      * @param   int  limit the number of rows
2435      * @param   int  start reading from given offset
2436      *
2437      * @return  string  modified query
2438      *
2439      * @access  protected
2440      */
2441     function _modifyQuery($query, $is_manip, $limit, $offset)
2442     {
2443         return $query;
2444     }
2445
2446     // }}}
2447     // {{{ function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
2448
2449     /**
2450      * Execute a query
2451      * @param   string  query
2452      * @param   bool    if the query is a manipulation query
2453      * @param   resource connection handle
2454      * @param   string  database name
2455      *
2456      * @return  result or error object
2457      *
2458      * @access  protected
2459      */
2460     function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)
2461     {
2462         $this->last_query = $query;
2463         $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
2464         if ($result) {
2465             if (PEAR::isError($result)) {
2466                 return $result;
2467             }
2468             $query = $result;
2469         }
2470         $err = $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2471             'method not implemented', __FUNCTION__);
2472         return $err;
2473     }
2474
2475     // }}}
2476     // {{{ function _affectedRows($connection, $result = null)
2477
2478     /**
2479      * Returns the number of rows affected
2480      *
2481      * @param   resource result handle
2482      * @param   resource connection handle
2483      *
2484      * @return  mixed   MDB2 Error Object or the number of rows affected
2485      *
2486      * @access  private
2487      */
2488     function _affectedRows($connection, $result = null)
2489     {
2490         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2491             'method not implemented', __FUNCTION__);
2492     }
2493
2494     // }}}
2495     // {{{ function &exec($query)
2496
2497     /**
2498      * Execute a manipulation query to the database and return the number of affected rows
2499      *
2500      * @param   string  the SQL query
2501      *
2502      * @return  mixed   number of affected rows on success, a MDB2 error on failure
2503      *
2504      * @access  public
2505      */
2506     function exec($query)
2507     {
2508         $offset = $this->offset;
2509         $limit = $this->limit;
2510         $this->offset = $this->limit = 0;
2511         $query = $this->_modifyQuery($query, true, $limit, $offset);
2512
2513         $connection = $this->getConnection();
2514         if (PEAR::isError($connection)) {
2515             return $connection;
2516         }
2517
2518         $result = $this->_doQuery($query, true, $connection, $this->database_name);
2519         if (PEAR::isError($result)) {
2520             return $result;
2521         }
2522
2523         $affectedRows = $this->_affectedRows($connection, $result);
2524         return $affectedRows;
2525     }
2526
2527     // }}}
2528     // {{{ function &query($query, $types = null, $result_class = true, $result_wrap_class = false)
2529
2530     /**
2531      * Send a query to the database and return any results
2532      *
2533      * @param   string  the SQL query
2534      * @param   mixed   array that contains the types of the columns in
2535      *                        the result set
2536      * @param   mixed   string which specifies which result class to use
2537      * @param   mixed   string which specifies which class to wrap results in
2538      *
2539      * @return mixed   an MDB2_Result handle on success, a MDB2 error on failure
2540      *
2541      * @access  public
2542      */
2543     function query($query, $types = null, $result_class = true, $result_wrap_class = false)
2544     {
2545         $offset = $this->offset;
2546         $limit = $this->limit;
2547         $this->offset = $this->limit = 0;
2548         $query = $this->_modifyQuery($query, false, $limit, $offset);
2549
2550         $connection = $this->getConnection();
2551         if (PEAR::isError($connection)) {
2552             return $connection;
2553         }
2554
2555         $result = $this->_doQuery($query, false, $connection, $this->database_name);
2556         if (PEAR::isError($result)) {
2557             return $result;
2558         }
2559
2560         $result = $this->_wrapResult($result, $types, $result_class, $result_wrap_class, $limit, $offset);
2561         return $result;
2562     }
2563
2564     // }}}
2565     // {{{ function _wrapResult($result_resource, $types = array(), $result_class = true, $result_wrap_class = false, $limit = null, $offset = null)
2566
2567     /**
2568      * wrap a result set into the correct class
2569      *
2570      * @param   resource result handle
2571      * @param   mixed   array that contains the types of the columns in
2572      *                        the result set
2573      * @param   mixed   string which specifies which result class to use
2574      * @param   mixed   string which specifies which class to wrap results in
2575      * @param   string  number of rows to select
2576      * @param   string  first row to select
2577      *
2578      * @return mixed   an MDB2_Result, a MDB2 error on failure
2579      *
2580      * @access  protected
2581      */
2582     function _wrapResult($result_resource, $types = array(), $result_class = true,
2583         $result_wrap_class = false, $limit = null, $offset = null)
2584     {
2585         if ($types === true) {
2586             if ($this->supports('result_introspection')) {
2587                 $this->loadModule('Reverse', null, true);
2588                 $tableInfo = $this->reverse->tableInfo($result_resource);
2589                 if (PEAR::isError($tableInfo)) {
2590                     return $tableInfo;
2591                 }
2592                 $types = array();
2593                 $types_assoc = array();
2594                 foreach ($tableInfo as $field) {
2595                     $types[] = $field['mdb2type'];
2596                     $types_assoc[$field['name']] = $field['mdb2type'];
2597                 }
2598             } else {
2599                 $types = null;
2600             }
2601         }
2602
2603         if ($result_class === true) {
2604             $result_class = $this->options['result_buffering']
2605                 ? $this->options['buffered_result_class'] : $this->options['result_class'];
2606         }
2607
2608         if ($result_class) {
2609             $class_name = sprintf($result_class, $this->phptype);
2610             if (!MDB2::classExists($class_name)) {
2611                 $err = $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
2612                     'result class does not exist '.$class_name, __FUNCTION__);
2613                 return $err;
2614             }
2615             $result = new $class_name($this, $result_resource, $limit, $offset);
2616             if (!MDB2::isResultCommon($result)) {
2617                 $err = $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
2618                     'result class is not extended from MDB2_Result_Common', __FUNCTION__);
2619                 return $err;
2620             }
2621             if (!empty($types)) {
2622                 $err = $result->setResultTypes($types);
2623                 if (PEAR::isError($err)) {
2624                     $result->free();
2625                     return $err;
2626                 }
2627             }
2628             if (!empty($types_assoc)) {
2629                 $err = $result->setResultTypesAssoc($types_assoc);
2630                 if (PEAR::isError($err)) {
2631                     $result->free();
2632                     return $err;
2633                 }
2634             }
2635         }
2636         if ($result_wrap_class === true) {
2637             $result_wrap_class = $this->options['result_wrap_class'];
2638         }
2639         if ($result_wrap_class) {
2640             if (!MDB2::classExists($result_wrap_class)) {
2641                 $err = $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
2642                     'result wrap class does not exist '.$result_wrap_class, __FUNCTION__);
2643                 return $err;
2644             }
2645             $result = new $result_wrap_class($result_resource, $this->fetchmode);
2646         }
2647         return $result;
2648     }
2649
2650     // }}}
2651     // {{{ function getServerVersion($native = false)
2652
2653     /**
2654      * return version information about the server
2655      *
2656      * @param   bool    determines if the raw version string should be returned
2657      *
2658      * @return  mixed   array with version information or row string
2659      *
2660      * @access  public
2661      */
2662     function getServerVersion($native = false)
2663     {
2664         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2665             'method not implemented', __FUNCTION__);
2666     }
2667
2668     // }}}
2669     // {{{ function setLimit($limit, $offset = null)
2670
2671     /**
2672      * set the range of the next query
2673      *
2674      * @param   string  number of rows to select
2675      * @param   string  first row to select
2676      *
2677      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
2678      *
2679      * @access  public
2680      */
2681     function setLimit($limit, $offset = null)
2682     {
2683         if (!$this->supports('limit_queries')) {
2684             return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2685                 'limit is not supported by this driver', __FUNCTION__);
2686         }
2687         $limit = (int)$limit;
2688         if ($limit < 0) {
2689             return $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
2690                 'it was not specified a valid selected range row limit', __FUNCTION__);
2691         }
2692         $this->limit = $limit;
2693         if (null !== $offset) {
2694             $offset = (int)$offset;
2695             if ($offset < 0) {
2696                 return $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
2697                     'it was not specified a valid first selected range row', __FUNCTION__);
2698             }
2699             $this->offset = $offset;
2700         }
2701         return MDB2_OK;
2702     }
2703
2704     // }}}
2705     // {{{ function subSelect($query, $type = false)
2706
2707     /**
2708      * simple subselect emulation: leaves the query untouched for all RDBMS
2709      * that support subselects
2710      *
2711      * @param   string  the SQL query for the subselect that may only
2712      *                      return a column
2713      * @param   string  determines type of the field
2714      *
2715      * @return  string  the query
2716      *
2717      * @access  public
2718      */
2719     function subSelect($query, $type = false)
2720     {
2721         if ($this->supports('sub_selects') === true) {
2722             return $query;
2723         }
2724
2725         if (!$this->supports('sub_selects')) {
2726             return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2727                 'method not implemented', __FUNCTION__);
2728         }
2729
2730         $col = $this->queryCol($query, $type);
2731         if (PEAR::isError($col)) {
2732             return $col;
2733         }
2734         if (!is_array($col) || count($col) == 0) {
2735             return 'NULL';
2736         }
2737         if ($type) {
2738             $this->loadModule('Datatype', null, true);
2739             return $this->datatype->implodeArray($col, $type);
2740         }
2741         return implode(', ', $col);
2742     }
2743
2744     // }}}
2745     // {{{ function replace($table, $fields)
2746
2747     /**
2748      * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
2749      * query, except that if there is already a row in the table with the same
2750      * key field values, the old row is deleted before the new row is inserted.
2751      *
2752      * The REPLACE type of query does not make part of the SQL standards. Since
2753      * practically only MySQL and SQLite implement it natively, this type of
2754      * query isemulated through this method for other DBMS using standard types
2755      * of queries inside a transaction to assure the atomicity of the operation.
2756      *
2757      * @param   string  name of the table on which the REPLACE query will
2758      *       be executed.
2759      * @param   array   associative array   that describes the fields and the
2760      *       values that will be inserted or updated in the specified table. The
2761      *       indexes of the array are the names of all the fields of the table.
2762      *       The values of the array are also associative arrays that describe
2763      *       the values and other properties of the table fields.
2764      *
2765      *       Here follows a list of field properties that need to be specified:
2766      *
2767      *       value
2768      *           Value to be assigned to the specified field. This value may be
2769      *           of specified in database independent type format as this
2770      *           function can perform the necessary datatype conversions.
2771      *
2772      *           Default: this property is required unless the Null property is
2773      *           set to 1.
2774      *
2775      *       type
2776      *           Name of the type of the field. Currently, all types MDB2
2777      *           are supported except for clob and blob.
2778      *
2779      *           Default: no type conversion
2780      *
2781      *       null
2782      *           bool    property that indicates that the value for this field
2783      *           should be set to null.
2784      *
2785      *           The default value for fields missing in INSERT queries may be
2786      *           specified the definition of a table. Often, the default value
2787      *           is already null, but since the REPLACE may be emulated using
2788      *           an UPDATE query, make sure that all fields of the table are
2789      *           listed in this function argument array.
2790      *
2791      *           Default: 0
2792      *
2793      *       key
2794      *           bool    property that indicates that this field should be
2795      *           handled as a primary key or at least as part of the compound
2796      *           unique index of the table that will determine the row that will
2797      *           updated if it exists or inserted a new row otherwise.
2798      *
2799      *           This function will fail if no key field is specified or if the
2800      *           value of a key field is set to null because fields that are
2801      *           part of unique index they may not be null.
2802      *
2803      *           Default: 0
2804      *
2805      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
2806      *
2807      * @access  public
2808      */
2809     function replace($table, $fields)
2810     {
2811         if (!$this->supports('replace')) {
2812             return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2813                 'replace query is not supported', __FUNCTION__);
2814         }
2815         $count = count($fields);
2816         $condition = $values = array();
2817         for ($colnum = 0, reset($fields); $colnum < $count; next($fields), $colnum++) {
2818             $name = key($fields);
2819             if (isset($fields[$name]['null']) && $fields[$name]['null']) {
2820                 $value = 'NULL';
2821             } else {
2822                 $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
2823                 $value = $this->quote($fields[$name]['value'], $type);
2824             }
2825             $values[$name] = $value;
2826             if (isset($fields[$name]['key']) && $fields[$name]['key']) {
2827                 if ($value === 'NULL') {
2828                     return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
2829                         'key value '.$name.' may not be NULL', __FUNCTION__);
2830                 }
2831                 $condition[] = $this->quoteIdentifier($name, true) . '=' . $value;
2832             }
2833         }
2834         if (empty($condition)) {
2835             return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
2836                 'not specified which fields are keys', __FUNCTION__);
2837         }
2838
2839         $result = null;
2840         $in_transaction = $this->in_transaction;
2841         if (!$in_transaction && PEAR::isError($result = $this->beginTransaction())) {
2842             return $result;
2843         }
2844
2845         $connection = $this->getConnection();
2846         if (PEAR::isError($connection)) {
2847             return $connection;
2848         }
2849
2850         $condition = ' WHERE '.implode(' AND ', $condition);
2851         $query = 'DELETE FROM ' . $this->quoteIdentifier($table, true) . $condition;
2852         $result = $this->_doQuery($query, true, $connection);
2853         if (!PEAR::isError($result)) {
2854             $affected_rows = $this->_affectedRows($connection, $result);
2855             $insert = '';
2856             foreach ($values as $key => $value) {
2857                 $insert .= ($insert?', ':'') . $this->quoteIdentifier($key, true);
2858             }
2859             $values = implode(', ', $values);
2860             $query = 'INSERT INTO '. $this->quoteIdentifier($table, true) . "($insert) VALUES ($values)";
2861             $result = $this->_doQuery($query, true, $connection);
2862             if (!PEAR::isError($result)) {
2863                 $affected_rows += $this->_affectedRows($connection, $result);;
2864             }
2865         }
2866
2867         if (!$in_transaction) {
2868             if (PEAR::isError($result)) {
2869                 $this->rollback();
2870             } else {
2871                 $result = $this->commit();
2872             }
2873         }
2874
2875         if (PEAR::isError($result)) {
2876             return $result;
2877         }
2878
2879         return $affected_rows;
2880     }
2881
2882     // }}}
2883     // {{{ function &prepare($query, $types = null, $result_types = null, $lobs = array())
2884
2885     /**
2886      * Prepares a query for multiple execution with execute().
2887      * With some database backends, this is emulated.
2888      * prepare() requires a generic query as string like
2889      * 'INSERT INTO numbers VALUES(?,?)' or
2890      * 'INSERT INTO numbers VALUES(:foo,:bar)'.
2891      * The ? and :name and are placeholders which can be set using
2892      * bindParam() and the query can be sent off using the execute() method.
2893      * The allowed format for :name can be set with the 'bindname_format' option.
2894      *
2895      * @param   string  the query to prepare
2896      * @param   mixed   array that contains the types of the placeholders
2897      * @param   mixed   array that contains the types of the columns in
2898      *                        the result set or MDB2_PREPARE_RESULT, if set to
2899      *                        MDB2_PREPARE_MANIP the query is handled as a manipulation query
2900      * @param   mixed   key (field) value (parameter) pair for all lob placeholders
2901      *
2902      * @return  mixed   resource handle for the prepared query on success, 
2903      *                  a MDB2 error on failure
2904      *
2905      * @access  public
2906      * @see     bindParam, execute
2907      */
2908     function prepare($query, $types = null, $result_types = null, $lobs = array())
2909     {
2910         $is_manip = ($result_types === MDB2_PREPARE_MANIP);
2911         $offset = $this->offset;
2912         $limit = $this->limit;
2913         $this->offset = $this->limit = 0;
2914         $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
2915         if ($result) {
2916             if (PEAR::isError($result)) {
2917                 return $result;
2918             }
2919             $query = $result;
2920         }
2921         $placeholder_type_guess = $placeholder_type = null;
2922         $question  = '?';
2923         $colon     = ':';
2924         $positions = array();
2925         $position  = 0;
2926         while ($position < strlen($query)) {
2927             $q_position = strpos($query, $question, $position);
2928             $c_position = strpos($query, $colon, $position);
2929             if ($q_position && $c_position) {
2930                 $p_position = min($q_position, $c_position);
2931             } elseif ($q_position) {
2932                 $p_position = $q_position;
2933             } elseif ($c_position) {
2934                 $p_position = $c_position;
2935             } else {
2936                 break;
2937             }
2938             if (null === $placeholder_type) {
2939                 $placeholder_type_guess = $query[$p_position];
2940             }
2941
2942             $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
2943             if (PEAR::isError($new_pos)) {
2944                 return $new_pos;
2945             }
2946             if ($new_pos != $position) {
2947                 $position = $new_pos;
2948                 continue; //evaluate again starting from the new position
2949             }
2950
2951             if ($query[$position] == $placeholder_type_guess) {
2952                 if (null === $placeholder_type) {
2953                     $placeholder_type = $query[$p_position];
2954                     $question = $colon = $placeholder_type;
2955                     if (!empty($types) && is_array($types)) {
2956                         if ($placeholder_type == ':') {
2957                             if (is_int(key($types))) {
2958                                 $types_tmp = $types;
2959                                 $types = array();
2960                                 $count = -1;
2961                             }
2962                         } else {
2963                             $types = array_values($types);
2964                         }
2965                     }
2966                 }
2967                 if ($placeholder_type == ':') {
2968                     $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
2969                     $parameter = preg_replace($regexp, '\\1', $query);
2970                     if ($parameter === '') {
2971                         $err = $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
2972                             'named parameter name must match "bindname_format" option', __FUNCTION__);
2973                         return $err;
2974                     }
2975                     $positions[$p_position] = $parameter;
2976                     $query = substr_replace($query, '?', $position, strlen($parameter)+1);
2977                     // use parameter name in type array
2978                     if (isset($count) && isset($types_tmp[++$count])) {
2979                         $types[$parameter] = $types_tmp[$count];
2980                     }
2981                 } else {
2982                     $positions[$p_position] = count($positions);
2983                 }
2984                 $position = $p_position + 1;
2985             } else {
2986                 $position = $p_position;
2987             }
2988         }
2989         $class_name = 'MDB2_Statement_'.$this->phptype;
2990         $statement = null;
2991         $obj = new $class_name($this, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
2992         $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
2993         return $obj;
2994     }
2995
2996     // }}}
2997     // {{{ function _skipDelimitedStrings($query, $position, $p_position)
2998     
2999     /**
3000      * Utility method, used by prepare() to avoid replacing placeholders within delimited strings.
3001      * Check if the placeholder is contained within a delimited string.
3002      * If so, skip it and advance the position, otherwise return the current position,
3003      * which is valid
3004      *
3005      * @param string $query
3006      * @param integer $position current string cursor position
3007      * @param integer $p_position placeholder position
3008      *
3009      * @return mixed integer $new_position on success
3010      *               MDB2_Error on failure
3011      *
3012      * @access  protected
3013      */
3014     function _skipDelimitedStrings($query, $position, $p_position)
3015     {
3016         $ignores = array();
3017         $ignores[] = $this->string_quoting;
3018         $ignores[] = $this->identifier_quoting;
3019         $ignores = array_merge($ignores, $this->sql_comments);
3020         
3021         foreach ($ignores as $ignore) {
3022             if (!empty($ignore['start'])) {
3023                 if (is_int($start_quote = strpos($query, $ignore['start'], $position)) && $start_quote < $p_position) {
3024                     $end_quote = $start_quote;
3025                     do {
3026                         if (!is_int($end_quote = strpos($query, $ignore['end'], $end_quote + 1))) {
3027                             if ($ignore['end'] === "\n") {
3028                                 $end_quote = strlen($query) - 1;
3029                             } else {
3030                                 $err = $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
3031                                     'query with an unterminated text string specified', __FUNCTION__);
3032                                 return $err;
3033                             }
3034                         }
3035                     } while ($ignore['escape']
3036                         && $end_quote-1 != $start_quote
3037                         && $query[($end_quote - 1)] == $ignore['escape']
3038                         && (   $ignore['escape_pattern'] !== $ignore['escape']
3039                             || $query[($end_quote - 2)] != $ignore['escape'])
3040                     );
3041
3042                     $position = $end_quote + 1;
3043                     return $position;
3044                 }
3045             }
3046         }
3047         return $position;
3048     }
3049     
3050     // }}}
3051     // {{{ function quote($value, $type = null, $quote = true)
3052
3053     /**
3054      * Convert a text value into a DBMS specific format that is suitable to
3055      * compose query statements.
3056      *
3057      * @param   string  text string value that is intended to be converted.
3058      * @param   string  type to which the value should be converted to
3059      * @param   bool    quote
3060      * @param   bool    escape wildcards
3061      *
3062      * @return  string  text string that represents the given argument value in
3063      *       a DBMS specific format.
3064      *
3065      * @access  public
3066      */
3067     function quote($value, $type = null, $quote = true, $escape_wildcards = false)
3068     {
3069         $result = $this->loadModule('Datatype', null, true);
3070         if (PEAR::isError($result)) {
3071             return $result;
3072         }
3073
3074         return $this->datatype->quote($value, $type, $quote, $escape_wildcards);
3075     }
3076
3077     // }}}
3078     // {{{ function getDeclaration($type, $name, $field)
3079
3080     /**
3081      * Obtain DBMS specific SQL code portion needed to declare
3082      * of the given type
3083      *
3084      * @param   string  type to which the value should be converted to
3085      * @param   string  name the field to be declared.
3086      * @param   string  definition of the field
3087      *
3088      * @return  string  DBMS specific SQL code portion that should be used to
3089      *                 declare the specified field.
3090      *
3091      * @access  public
3092      */
3093     function getDeclaration($type, $name, $field)
3094     {
3095         $result = $this->loadModule('Datatype', null, true);
3096         if (PEAR::isError($result)) {
3097             return $result;
3098         }
3099         return $this->datatype->getDeclaration($type, $name, $field);
3100     }
3101
3102     // }}}
3103     // {{{ function compareDefinition($current, $previous)
3104
3105     /**
3106      * Obtain an array of changes that may need to applied
3107      *
3108      * @param   array   new definition
3109      * @param   array   old definition
3110      *
3111      * @return  array   containing all changes that will need to be applied
3112      *
3113      * @access  public
3114      */
3115     function compareDefinition($current, $previous)
3116     {
3117         $result = $this->loadModule('Datatype', null, true);
3118         if (PEAR::isError($result)) {
3119             return $result;
3120         }
3121         return $this->datatype->compareDefinition($current, $previous);
3122     }
3123
3124     // }}}
3125     // {{{ function supports($feature)
3126
3127     /**
3128      * Tell whether a DB implementation or its backend extension
3129      * supports a given feature.
3130      *
3131      * @param   string  name of the feature (see the MDB2 class doc)
3132      *
3133      * @return  bool|string if this DB implementation supports a given feature
3134      *                      false means no, true means native,
3135      *                      'emulated' means emulated
3136      *
3137      * @access  public
3138      */
3139     function supports($feature)
3140     {
3141         if (array_key_exists($feature, $this->supported)) {
3142             return $this->supported[$feature];
3143         }
3144         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
3145             "unknown support feature $feature", __FUNCTION__);
3146     }
3147
3148     // }}}
3149     // {{{ function getSequenceName($sqn)
3150
3151     /**
3152      * adds sequence name formatting to a sequence name
3153      *
3154      * @param   string  name of the sequence
3155      *
3156      * @return  string  formatted sequence name
3157      *
3158      * @access  public
3159      */
3160     function getSequenceName($sqn)
3161     {
3162         return sprintf($this->options['seqname_format'],
3163             preg_replace('/[^a-z0-9_\-\$.]/i', '_', $sqn));
3164     }
3165
3166     // }}}
3167     // {{{ function getIndexName($idx)
3168
3169     /**
3170      * adds index name formatting to a index name
3171      *
3172      * @param   string  name of the index
3173      *
3174      * @return  string  formatted index name
3175      *
3176      * @access  public
3177      */
3178     function getIndexName($idx)
3179     {
3180         return sprintf($this->options['idxname_format'],
3181             preg_replace('/[^a-z0-9_\-\$.]/i', '_', $idx));
3182     }
3183
3184     // }}}
3185     // {{{ function nextID($seq_name, $ondemand = true)
3186
3187     /**
3188      * Returns the next free id of a sequence
3189      *
3190      * @param   string  name of the sequence
3191      * @param   bool    when true missing sequences are automatic created
3192      *
3193      * @return  mixed   MDB2 Error Object or id
3194      *
3195      * @access  public
3196      */
3197     function nextID($seq_name, $ondemand = true)
3198     {
3199         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
3200             'method not implemented', __FUNCTION__);
3201     }
3202
3203     // }}}
3204     // {{{ function lastInsertID($table = null, $field = null)
3205
3206     /**
3207      * Returns the autoincrement ID if supported or $id or fetches the current
3208      * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
3209      *
3210      * @param   string  name of the table into which a new row was inserted
3211      * @param   string  name of the field into which a new row was inserted
3212      *
3213      * @return  mixed   MDB2 Error Object or id
3214      *
3215      * @access  public
3216      */
3217     function lastInsertID($table = null, $field = null)
3218     {
3219         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
3220             'method not implemented', __FUNCTION__);
3221     }
3222
3223     // }}}
3224     // {{{ function currID($seq_name)
3225
3226     /**
3227      * Returns the current id of a sequence
3228      *
3229      * @param   string  name of the sequence
3230      *
3231      * @return  mixed   MDB2 Error Object or id
3232      *
3233      * @access  public
3234      */
3235     function currID($seq_name)
3236     {
3237         $this->warnings[] = 'database does not support getting current
3238             sequence value, the sequence value was incremented';
3239         return $this->nextID($seq_name);
3240     }
3241
3242     // }}}
3243     // {{{ function queryOne($query, $type = null, $colnum = 0)
3244
3245     /**
3246      * Execute the specified query, fetch the value from the first column of
3247      * the first row of the result set and then frees
3248      * the result set.
3249      *
3250      * @param string $query  the SELECT query statement to be executed.
3251      * @param string $type   optional argument that specifies the expected
3252      *                       datatype of the result set field, so that an eventual
3253      *                       conversion may be performed. The default datatype is
3254      *                       text, meaning that no conversion is performed
3255      * @param mixed  $colnum the column number (or name) to fetch
3256      *
3257      * @return  mixed   MDB2_OK or field value on success, a MDB2 error on failure
3258      *
3259      * @access  public
3260      */
3261     function queryOne($query, $type = null, $colnum = 0)
3262     {
3263         $result = $this->query($query, $type);
3264         if (!MDB2::isResultCommon($result)) {
3265             return $result;
3266         }
3267
3268         $one = $result->fetchOne($colnum);
3269         $result->free();
3270         return $one;
3271     }
3272
3273     // }}}
3274     // {{{ function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
3275
3276     /**
3277      * Execute the specified query, fetch the values from the first
3278      * row of the result set into an array and then frees
3279      * the result set.
3280      *
3281      * @param   string  the SELECT query statement to be executed.
3282      * @param   array   optional array argument that specifies a list of
3283      *       expected datatypes of the result set columns, so that the eventual
3284      *       conversions may be performed. The default list of datatypes is
3285      *       empty, meaning that no conversion is performed.
3286      * @param   int     how the array data should be indexed
3287      *
3288      * @return  mixed   MDB2_OK or data array on success, a MDB2 error on failure
3289      *
3290      * @access  public
3291      */
3292     function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
3293     {
3294         $result = $this->query($query, $types);
3295         if (!MDB2::isResultCommon($result)) {
3296             return $result;
3297         }
3298
3299         $row = $result->fetchRow($fetchmode);
3300         $result->free();
3301         return $row;
3302     }
3303
3304     // }}}
3305     // {{{ function queryCol($query, $type = null, $colnum = 0)
3306
3307     /**
3308      * Execute the specified query, fetch the value from the first column of
3309      * each row of the result set into an array and then frees the result set.
3310      *
3311      * @param string $query  the SELECT query statement to be executed.
3312      * @param string $type   optional argument that specifies the expected
3313      *                       datatype of the result set field, so that an eventual
3314      *                       conversion may be performed. The default datatype is text,
3315      *                       meaning that no conversion is performed
3316      * @param mixed  $colnum the column number (or name) to fetch
3317      *
3318      * @return  mixed   MDB2_OK or data array on success, a MDB2 error on failure
3319      * @access  public
3320      */
3321     function queryCol($query, $type = null, $colnum = 0)
3322     {
3323         $result = $this->query($query, $type);
3324         if (!MDB2::isResultCommon($result)) {
3325             return $result;
3326         }
3327
3328         $col = $result->fetchCol($colnum);
3329         $result->free();
3330         return $col;
3331     }
3332
3333     // }}}
3334     // {{{ function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
3335
3336     /**
3337      * Execute the specified query, fetch all the rows of the result set into
3338      * a two dimensional array and then frees the result set.
3339      *
3340      * @param   string  the SELECT query statement to be executed.
3341      * @param   array   optional array argument that specifies a list of
3342      *       expected datatypes of the result set columns, so that the eventual
3343      *       conversions may be performed. The default list of datatypes is
3344      *       empty, meaning that no conversion is performed.
3345      * @param   int     how the array data should be indexed
3346      * @param   bool    if set to true, the $all will have the first
3347      *       column as its first dimension
3348      * @param   bool    used only when the query returns exactly
3349      *       two columns. If true, the values of the returned array will be
3350      *       one-element arrays instead of scalars.
3351      * @param   bool    if true, the values of the returned array is
3352      *       wrapped in another array.  If the same key value (in the first
3353      *       column) repeats itself, the values will be appended to this array
3354      *       instead of overwriting the existing values.
3355      *
3356      * @return  mixed   MDB2_OK or data array on success, a MDB2 error on failure
3357      *
3358      * @access  public
3359      */
3360     function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT,
3361         $rekey = false, $force_array = false, $group = false)
3362     {
3363         $result = $this->query($query, $types);
3364         if (!MDB2::isResultCommon($result)) {
3365             return $result;
3366         }
3367
3368         $all = $result->fetchAll($fetchmode, $rekey, $force_array, $group);
3369         $result->free();
3370         return $all;
3371     }
3372
3373     // }}}
3374 }
3375
3376 // }}}
3377 // {{{ class MDB2_Result
3378
3379 /**
3380  * The dummy class that all user space result classes should extend from
3381  *
3382  * @package     MDB2
3383  * @category    Database
3384  * @author      Lukas Smith <smith@pooteeweet.org>
3385  */
3386 class MDB2_Result
3387 {
3388 }
3389
3390 // }}}
3391 // {{{ class MDB2_Result_Common extends MDB2_Result
3392
3393 /**
3394  * The common result class for MDB2 result objects
3395  *
3396  * @package     MDB2
3397  * @category    Database
3398  * @author      Lukas Smith <smith@pooteeweet.org>
3399  */
3400 class MDB2_Result_Common extends MDB2_Result
3401 {
3402     // {{{ Variables (Properties)
3403
3404     protected $db;
3405     protected $result;
3406     protected $rownum = -1;
3407     protected $types = array();
3408     protected $types_assoc = array();
3409     protected $values = array();
3410     protected $offset;
3411     protected $offset_count = 0;
3412     protected $limit;
3413     protected $column_names;
3414
3415     // }}}
3416     // {{{ constructor: function __construct($db, &$result, $limit = 0, $offset = 0)
3417
3418     /**
3419      * Constructor
3420      */
3421     function __construct($db, &$result, $limit = 0, $offset = 0)
3422     {
3423         $this->db = $db;
3424         $this->result = $result;
3425         $this->offset = $offset;
3426         $this->limit = max(0, $limit - 1);
3427     }
3428
3429     // }}}
3430     // {{{ function setResultTypes($types)
3431
3432     /**
3433      * Define the list of types to be associated with the columns of a given
3434      * result set.
3435      *
3436      * This function may be called before invoking fetchRow(), fetchOne(),
3437      * fetchCol() and fetchAll() so that the necessary data type
3438      * conversions are performed on the data to be retrieved by them. If this
3439      * function is not called, the type of all result set columns is assumed
3440      * to be text, thus leading to not perform any conversions.
3441      *
3442      * @param   array   variable that lists the
3443      *       data types to be expected in the result set columns. If this array
3444      *       contains less types than the number of columns that are returned
3445      *       in the result set, the remaining columns are assumed to be of the
3446      *       type text. Currently, the types clob and blob are not fully
3447      *       supported.
3448      *
3449      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
3450      *
3451      * @access  public
3452      */
3453     function setResultTypes($types)
3454     {
3455         $load = $this->db->loadModule('Datatype', null, true);
3456         if (PEAR::isError($load)) {
3457             return $load;
3458         }
3459         $types = $this->db->datatype->checkResultTypes($types);
3460         if (PEAR::isError($types)) {
3461             return $types;
3462         }
3463         $this->types = $types;
3464         return MDB2_OK;
3465     }
3466
3467     // }}}
3468     // {{{ function seek($rownum = 0)
3469
3470     /**
3471      * Seek to a specific row in a result set
3472      *
3473      * @param   int     number of the row where the data can be found
3474      *
3475      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
3476      *
3477      * @access  public
3478      */
3479     function seek($rownum = 0)
3480     {
3481         $target_rownum = $rownum - 1;
3482         if ($this->rownum > $target_rownum) {
3483             return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
3484                 'seeking to previous rows not implemented', __FUNCTION__);
3485         }
3486         while ($this->rownum < $target_rownum) {
3487             $this->fetchRow();
3488         }
3489         return MDB2_OK;
3490     }
3491
3492     // }}}
3493     // {{{ function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
3494
3495     /**
3496      * Fetch and return a row of data
3497      *
3498      * @param   int     how the array data should be indexed
3499      * @param   int     number of the row where the data can be found
3500      *
3501      * @return  int     data array on success, a MDB2 error on failure
3502      *
3503      * @access  public
3504      */
3505     function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
3506     {
3507         $err = $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
3508             'method not implemented', __FUNCTION__);
3509         return $err;
3510     }
3511
3512     // }}}
3513     // {{{ function fetchOne($colnum = 0)
3514
3515     /**
3516      * fetch single column from the next row from a result set
3517      *
3518      * @param int|string the column number (or name) to fetch
3519      * @param int        number of the row where the data can be found
3520      *
3521      * @return string data on success, a MDB2 error on failure
3522      * @access  public
3523      */
3524     function fetchOne($colnum = 0, $rownum = null)
3525     {
3526         $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
3527         $row = $this->fetchRow($fetchmode, $rownum);
3528         if (!is_array($row) || PEAR::isError($row)) {
3529             return $row;
3530         }
3531         if (!array_key_exists($colnum, $row)) {
3532             return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
3533                 'column is not defined in the result set: '.$colnum, __FUNCTION__);
3534         }
3535         return $row[$colnum];
3536     }
3537
3538     // }}}
3539     // {{{ function fetchCol($colnum = 0)
3540
3541     /**
3542      * Fetch and return a column from the current row pointer position
3543      *
3544      * @param int|string the column number (or name) to fetch
3545      *
3546      * @return  mixed data array on success, a MDB2 error on failure
3547      * @access  public
3548      */
3549     function fetchCol($colnum = 0)
3550     {
3551         $column = array();
3552         $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
3553         $row = $this->fetchRow($fetchmode);
3554         if (is_array($row)) {
3555             if (!array_key_exists($colnum, $row)) {
3556                 return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
3557                     'column is not defined in the result set: '.$colnum, __FUNCTION__);
3558             }
3559             do {
3560                 $column[] = $row[$colnum];
3561             } while (is_array($row = $this->fetchRow($fetchmode)));
3562         }
3563         if (PEAR::isError($row)) {
3564             return $row;
3565         }
3566         return $column;
3567     }
3568
3569     // }}}
3570     // {{{ function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
3571
3572     /**
3573      * Fetch and return all rows from the current row pointer position
3574      *
3575      * @param   int     $fetchmode  the fetch mode to use:
3576      *                            + MDB2_FETCHMODE_ORDERED
3577      *                            + MDB2_FETCHMODE_ASSOC
3578      *                            + MDB2_FETCHMODE_ORDERED | MDB2_FETCHMODE_FLIPPED
3579      *                            + MDB2_FETCHMODE_ASSOC | MDB2_FETCHMODE_FLIPPED
3580      * @param   bool    if set to true, the $all will have the first
3581      *       column as its first dimension
3582      * @param   bool    used only when the query returns exactly
3583      *       two columns. If true, the values of the returned array will be
3584      *       one-element arrays instead of scalars.
3585      * @param   bool    if true, the values of the returned array is
3586      *       wrapped in another array.  If the same key value (in the first
3587      *       column) repeats itself, the values will be appended to this array
3588      *       instead of overwriting the existing values.
3589      *
3590      * @return  mixed   data array on success, a MDB2 error on failure
3591      *
3592      * @access  public
3593      * @see     getAssoc()
3594      */
3595     function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false,
3596         $force_array = false, $group = false)
3597     {
3598         $all = array();
3599         $row = $this->fetchRow($fetchmode);
3600         if (PEAR::isError($row)) {
3601             return $row;
3602         } elseif (!$row) {
3603             return $all;
3604         }
3605
3606         $shift_array = $rekey ? false : null;
3607         if (null !== $shift_array) {
3608             if (is_object($row)) {
3609                 $colnum = count(get_object_vars($row));
3610             } else {
3611                 $colnum = count($row);
3612             }
3613             if ($colnum < 2) {
3614                 return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
3615                     'rekey feature requires atleast 2 column', __FUNCTION__);
3616             }
3617             $shift_array = (!$force_array && $colnum == 2);
3618         }
3619
3620         if ($rekey) {
3621             do {
3622                 if (is_object($row)) {
3623                     $arr = get_object_vars($row);
3624                     $key = reset($arr);
3625                     unset($row->{$key});
3626                 } else {
3627                     if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
3628                         $key = reset($row);
3629                         unset($row[key($row)]);
3630                     } else {
3631                         $key = array_shift($row);
3632                     }
3633                     if ($shift_array) {
3634                         $row = array_shift($row);
3635                     }
3636                 }
3637                 if ($group) {
3638                     $all[$key][] = $row;
3639                 } else {
3640                     $all[$key] = $row;
3641                 }
3642             } while (($row = $this->fetchRow($fetchmode)));
3643         } elseif ($fetchmode & MDB2_FETCHMODE_FLIPPED) {
3644             do {
3645                 foreach ($row as $key => $val) {
3646                     $all[$key][] = $val;
3647                 }
3648             } while (($row = $this->fetchRow($fetchmode)));
3649         } else {
3650             do {
3651                 $all[] = $row;
3652             } while (($row = $this->fetchRow($fetchmode)));
3653         }
3654
3655         return $all;
3656     }
3657
3658     // }}}
3659     // {{{ function rowCount()
3660     /**
3661      * Returns the actual row number that was last fetched (count from 0)
3662      * @return  int
3663      *
3664      * @access  public
3665      */
3666     function rowCount()
3667     {
3668         return $this->rownum + 1;
3669     }
3670
3671     // }}}
3672     // {{{ function numRows()
3673
3674     /**
3675      * Returns the number of rows in a result object
3676      *
3677      * @return  mixed   MDB2 Error Object or the number of rows
3678      *
3679      * @access  public
3680      */
3681     function numRows()
3682     {
3683         return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
3684             'method not implemented', __FUNCTION__);
3685     }
3686
3687     // }}}
3688     // {{{ function nextResult()
3689
3690     /**
3691      * Move the internal result pointer to the next available result
3692      *
3693      * @return  true on success, false if there is no more result set or an error object on failure
3694      *
3695      * @access  public
3696      */
3697     function nextResult()
3698     {
3699         return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
3700             'method not implemented', __FUNCTION__);
3701     }
3702
3703     // }}}
3704     // {{{ function getColumnNames()
3705
3706     /**
3707      * Retrieve the names of columns returned by the DBMS in a query result or
3708      * from the cache.
3709      *
3710      * @param   bool    If set to true the values are the column names,
3711      *                  otherwise the names of the columns are the keys.
3712      * @return  mixed   Array variable that holds the names of columns or an
3713      *                  MDB2 error on failure.
3714      *                  Some DBMS may not return any columns when the result set
3715      *                  does not contain any rows.
3716      *
3717      * @access  public
3718      */
3719     function getColumnNames($flip = false)
3720     {
3721         if (!isset($this->column_names)) {
3722             $result = $this->_getColumnNames();
3723             if (PEAR::isError($result)) {
3724                 return $result;
3725             }
3726             $this->column_names = $result;
3727         }
3728         if ($flip) {
3729             return array_flip($this->column_names);
3730         }
3731         return $this->column_names;
3732     }
3733
3734     // }}}
3735     // {{{ function _getColumnNames()
3736
3737     /**
3738      * Retrieve the names of columns returned by the DBMS in a query result.
3739      *
3740      * @return  mixed   Array variable that holds the names of columns as keys
3741      *                  or an MDB2 error on failure.
3742      *                  Some DBMS may not return any columns when the result set
3743      *                  does not contain any rows.
3744      *
3745      * @access  private
3746      */
3747     function _getColumnNames()
3748     {
3749         return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
3750             'method not implemented', __FUNCTION__);
3751     }
3752
3753     // }}}
3754     // {{{ function numCols()
3755
3756     /**
3757      * Count the number of columns returned by the DBMS in a query result.
3758      *
3759      * @return  mixed   integer value with the number of columns, a MDB2 error
3760      *       on failure
3761      *
3762      * @access  public
3763      */
3764     function numCols()
3765     {
3766         return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
3767             'method not implemented', __FUNCTION__);
3768     }
3769
3770     // }}}
3771     // {{{ function getResource()
3772
3773     /**
3774      * return the resource associated with the result object
3775      *
3776      * @return  resource
3777      *
3778      * @access  public
3779      */
3780     function getResource()
3781     {
3782         return $this->result;
3783     }
3784
3785     // }}}
3786     // {{{ function bindColumn($column, &$value, $type = null)
3787
3788     /**
3789      * Set bind variable to a column.
3790      *
3791      * @param   int     column number or name
3792      * @param   mixed   variable reference
3793      * @param   string  specifies the type of the field
3794      *
3795      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
3796      *
3797      * @access  public
3798      */
3799     function bindColumn($column, &$value, $type = null)
3800     {
3801         if (!is_numeric($column)) {
3802             $column_names = $this->getColumnNames();
3803             if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
3804                 if ($this->db->options['field_case'] == CASE_LOWER) {
3805                     $column = strtolower($column);
3806                 } else {
3807                     $column = strtoupper($column);
3808                 }
3809             }
3810             $column = $column_names[$column];
3811         }
3812         $this->values[$column] =& $value;
3813         if (null !== $type) {
3814             $this->types[$column] = $type;
3815         }
3816         return MDB2_OK;
3817     }
3818
3819     // }}}
3820     // {{{ function _assignBindColumns($row)
3821
3822     /**
3823      * Bind a variable to a value in the result row.
3824      *
3825      * @param   array   row data
3826      *
3827      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
3828      *
3829      * @access  private
3830      */
3831     function _assignBindColumns($row)
3832     {
3833         $row = array_values($row);
3834         foreach ($row as $column => $value) {
3835             if (array_key_exists($column, $this->values)) {
3836                 $this->values[$column] = $value;
3837             }
3838         }
3839         return MDB2_OK;
3840     }
3841
3842     // }}}
3843     // {{{ function free()
3844
3845     /**
3846      * Free the internal resources associated with result.
3847      *
3848      * @return  bool    true on success, false if result is invalid
3849      *
3850      * @access  public
3851      */
3852     function free()
3853     {
3854         $this->result = false;
3855         return MDB2_OK;
3856     }
3857
3858     // }}}
3859 }
3860
3861 // }}}
3862 // {{{ class MDB2_Row
3863
3864 /**
3865  * The simple class that accepts row data as an array
3866  *
3867  * @package     MDB2
3868  * @category    Database
3869  * @author      Lukas Smith <smith@pooteeweet.org>
3870  */
3871 class MDB2_Row
3872 {
3873     // {{{ constructor: function __construct(&$row)
3874
3875     /**
3876      * constructor
3877      *
3878      * @param   resource    row data as array
3879      */
3880     function __construct(&$row)
3881     {
3882         foreach ($row as $key => $value) {
3883             $this->$key = &$row[$key];
3884         }
3885     }
3886
3887     // }}}
3888 }
3889
3890 // }}}
3891 // {{{ class MDB2_Statement_Common
3892
3893 /**
3894  * The common statement class for MDB2 statement objects
3895  *
3896  * @package     MDB2
3897  * @category    Database
3898  * @author      Lukas Smith <smith@pooteeweet.org>
3899  */
3900 class MDB2_Statement_Common
3901 {
3902     // {{{ Variables (Properties)
3903
3904     var $db;
3905     var $statement;
3906     var $query;
3907     var $result_types;
3908     var $types;
3909     var $values = array();
3910     var $limit;
3911     var $offset;
3912     var $is_manip;
3913
3914     // }}}
3915     // {{{ constructor: function __construct($db, $statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
3916
3917     /**
3918      * Constructor
3919      */
3920     function __construct($db, $statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
3921     {
3922         $this->db = $db;
3923         $this->statement = $statement;
3924         $this->positions = $positions;
3925         $this->query = $query;
3926         $this->types = (array)$types;
3927         $this->result_types = (array)$result_types;
3928         $this->limit = $limit;
3929         $this->is_manip = $is_manip;
3930         $this->offset = $offset;
3931     }
3932
3933     // }}}
3934     // {{{ function bindValue($parameter, &$value, $type = null)
3935
3936     /**
3937      * Set the value of a parameter of a prepared query.
3938      *
3939      * @param   int     the order number of the parameter in the query
3940      *       statement. The order number of the first parameter is 1.
3941      * @param   mixed   value that is meant to be assigned to specified
3942      *       parameter. The type of the value depends on the $type argument.
3943      * @param   string  specifies the type of the field
3944      *
3945      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
3946      *
3947      * @access  public
3948      */
3949     function bindValue($parameter, $value, $type = null)
3950     {
3951         if (!is_numeric($parameter)) {
3952             if (strpos($parameter, ':') === 0) {
3953                 $parameter = substr($parameter, 1);
3954             }
3955         }
3956         if (!in_array($parameter, $this->positions)) {
3957             return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
3958                 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
3959         }
3960         $this->values[$parameter] = $value;
3961         if (null !== $type) {
3962             $this->types[$parameter] = $type;
3963         }
3964         return MDB2_OK;
3965     }
3966
3967     // }}}
3968     // {{{ function bindValueArray($values, $types = null)
3969
3970     /**
3971      * Set the values of multiple a parameter of a prepared query in bulk.
3972      *
3973      * @param   array   specifies all necessary information
3974      *       for bindValue() the array elements must use keys corresponding to
3975      *       the number of the position of the parameter.
3976      * @param   array   specifies the types of the fields
3977      *
3978      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
3979      *
3980      * @access  public
3981      * @see     bindParam()
3982      */
3983     function bindValueArray($values, $types = null)
3984     {
3985         $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
3986         $parameters = array_keys($values);
3987         $this->db->pushErrorHandling(PEAR_ERROR_RETURN);
3988         $this->db->expectError(MDB2_ERROR_NOT_FOUND);
3989         foreach ($parameters as $key => $parameter) {
3990             $err = $this->bindValue($parameter, $values[$parameter], $types[$key]);
3991             if (PEAR::isError($err)) {
3992                 if ($err->getCode() == MDB2_ERROR_NOT_FOUND) {
3993                     //ignore (extra value for missing placeholder)
3994                     continue;
3995                 }
3996                 $this->db->popExpect();
3997                 $this->db->popErrorHandling();
3998                 return $err;
3999             }
4000         }
4001         $this->db->popExpect();
4002         $this->db->popErrorHandling();
4003         return MDB2_OK;
4004     }
4005
4006     // }}}
4007     // {{{ function bindParam($parameter, &$value, $type = null)
4008
4009     /**
4010      * Bind a variable to a parameter of a prepared query.
4011      *
4012      * @param   int     the order number of the parameter in the query
4013      *       statement. The order number of the first parameter is 1.
4014      * @param   mixed   variable that is meant to be bound to specified
4015      *       parameter. The type of the value depends on the $type argument.
4016      * @param   string  specifies the type of the field
4017      *
4018      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
4019      *
4020      * @access  public
4021      */
4022     function bindParam($parameter, &$value, $type = null)
4023     {
4024         if (!is_numeric($parameter)) {
4025             if (strpos($parameter, ':') === 0) {
4026                 $parameter = substr($parameter, 1);
4027             }
4028         }
4029         if (!in_array($parameter, $this->positions)) {
4030             return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
4031                 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
4032         }
4033         $this->values[$parameter] =& $value;
4034         if (null !== $type) {
4035             $this->types[$parameter] = $type;
4036         }
4037         return MDB2_OK;
4038     }
4039
4040     // }}}
4041     // {{{ function bindParamArray(&$values, $types = null)
4042
4043     /**
4044      * Bind the variables of multiple a parameter of a prepared query in bulk.
4045      *
4046      * @param   array   specifies all necessary information
4047      *       for bindParam() the array elements must use keys corresponding to
4048      *       the number of the position of the parameter.
4049      * @param   array   specifies the types of the fields
4050      *
4051      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
4052      *
4053      * @access  public
4054      * @see     bindParam()
4055      */
4056     function bindParamArray(&$values, $types = null)
4057     {
4058         $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
4059         $parameters = array_keys($values);
4060         foreach ($parameters as $key => $parameter) {
4061             $err = $this->bindParam($parameter, $values[$parameter], $types[$key]);
4062             if (PEAR::isError($err)) {
4063                 return $err;
4064             }
4065         }
4066         return MDB2_OK;
4067     }
4068
4069     // }}}
4070     // {{{ function &execute($values = null, $result_class = true, $result_wrap_class = false)
4071
4072     /**
4073      * Execute a prepared query statement.
4074      *
4075      * @param array specifies all necessary information
4076      *              for bindParam() the array elements must use keys corresponding
4077      *              to the number of the position of the parameter.
4078      * @param mixed specifies which result class to use
4079      * @param mixed specifies which class to wrap results in
4080      *
4081      * @return mixed MDB2_Result or integer (affected rows) on success,
4082      *               a MDB2 error on failure
4083      * @access public
4084      */
4085     function execute($values = null, $result_class = true, $result_wrap_class = false)
4086     {
4087         if (null === $this->positions) {
4088             return $this->db->raiseError(MDB2_ERROR, null, null,
4089                 'Prepared statement has already been freed', __FUNCTION__);
4090         }
4091
4092         $values = (array)$values;
4093         if (!empty($values)) {
4094             $err = $this->bindValueArray($values);
4095             if (PEAR::isError($err)) {
4096                 return $this->db->raiseError(MDB2_ERROR, null, null,
4097                                             'Binding Values failed with message: ' . $err->getMessage(), __FUNCTION__);
4098             }
4099         }
4100         $result = $this->_execute($result_class, $result_wrap_class);
4101         return $result;
4102     }
4103
4104     // }}}
4105     // {{{ function _execute($result_class = true, $result_wrap_class = false)
4106
4107     /**
4108      * Execute a prepared query statement helper method.
4109      *
4110      * @param   mixed   specifies which result class to use
4111      * @param   mixed   specifies which class to wrap results in
4112      *
4113      * @return mixed MDB2_Result or integer (affected rows) on success,
4114      *               a MDB2 error on failure
4115      * @access  private
4116      */
4117     function _execute($result_class = true, $result_wrap_class = false)
4118     {
4119         $this->last_query = $this->query;
4120         $query = '';
4121         $last_position = 0;
4122         foreach ($this->positions as $current_position => $parameter) {
4123             if (!array_key_exists($parameter, $this->values)) {
4124                 return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
4125                     'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
4126             }
4127             $value = $this->values[$parameter];
4128             $query.= substr($this->query, $last_position, $current_position - $last_position);
4129             if (!isset($value)) {
4130                 $value_quoted = 'NULL';
4131             } else {
4132                 $type = !empty($this->types[$parameter]) ? $this->types[$parameter] : null;
4133                 $value_quoted = $this->db->quote($value, $type);
4134                 if (PEAR::isError($value_quoted)) {
4135                     return $value_quoted;
4136                 }
4137             }
4138             $query.= $value_quoted;
4139             $last_position = $current_position + 1;
4140         }
4141         $query.= substr($this->query, $last_position);
4142
4143         $this->db->offset = $this->offset;
4144         $this->db->limit = $this->limit;
4145         if ($this->is_manip) {
4146             $result = $this->db->exec($query);
4147         } else {
4148             $result = $this->db->query($query, $this->result_types, $result_class, $result_wrap_class);
4149         }
4150         return $result;
4151     }
4152
4153     // }}}
4154     // {{{ function free()
4155
4156     /**
4157      * Release resources allocated for the specified prepared query.
4158      *
4159      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
4160      *
4161      * @access  public
4162      */
4163     function free()
4164     {
4165         if (null === $this->positions) {
4166             return $this->db->raiseError(MDB2_ERROR, null, null,
4167                 'Prepared statement has already been freed', __FUNCTION__);
4168         }
4169
4170         $this->statement = null;
4171         $this->positions = null;
4172         $this->query = null;
4173         $this->types = null;
4174         $this->result_types = null;
4175         $this->limit = null;
4176         $this->is_manip = null;
4177         $this->offset = null;
4178         $this->values = null;
4179
4180         return MDB2_OK;
4181     }
4182
4183     // }}}
4184 }
4185
4186 // }}}
4187 // {{{ class MDB2_Module_Common
4188
4189 /**
4190  * The common modules class for MDB2 module objects
4191  *
4192  * @package     MDB2
4193  * @category    Database
4194  * @author      Lukas Smith <smith@pooteeweet.org>
4195  */
4196 class MDB2_Module_Common
4197 {
4198     // {{{ Variables (Properties)
4199
4200     /**
4201      * contains the key to the global MDB2 instance array of the associated
4202      * MDB2 instance
4203      *
4204      * @var     int
4205      * @access  protected
4206      */
4207     protected $db_index;
4208
4209     // }}}
4210     // {{{ constructor: function __construct($db_index)
4211
4212     /**
4213      * Constructor
4214      */
4215     function __construct($db_index)
4216     {
4217         $this->db_index = $db_index;
4218     }
4219
4220     // }}}
4221     // {{{ function getDBInstance()
4222
4223     /**
4224      * Get the instance of MDB2 associated with the module instance
4225      *
4226      * @return  object  MDB2 instance or a MDB2 error on failure
4227      *
4228      * @access  public
4229      */
4230     function getDBInstance()
4231     {
4232         if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
4233             $result = $GLOBALS['_MDB2_databases'][$this->db_index];
4234         } else {
4235             $result = MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
4236                 'could not find MDB2 instance');
4237         }
4238         return $result;
4239     }
4240
4241     // }}}
4242 }
4243
4244 // }}}
4245 // {{{ function MDB2_closeOpenTransactions()
4246
4247 /**
4248  * Close any open transactions form persistent connections
4249  *
4250  * @return  void
4251  *
4252  * @access  public
4253  */
4254
4255 function MDB2_closeOpenTransactions()
4256 {
4257     reset($GLOBALS['_MDB2_databases']);
4258     while (next($GLOBALS['_MDB2_databases'])) {
4259         $key = key($GLOBALS['_MDB2_databases']);
4260         if ($GLOBALS['_MDB2_databases'][$key]->opened_persistent
4261             && $GLOBALS['_MDB2_databases'][$key]->in_transaction
4262         ) {
4263             $GLOBALS['_MDB2_databases'][$key]->rollback();
4264         }
4265     }
4266 }
4267
4268 // }}}
4269 // {{{ function MDB2_defaultDebugOutput(&$db, $scope, $message, $is_manip = null)
4270
4271 /**
4272  * default debug output handler
4273  *
4274  * @param   object  reference to an MDB2 database object
4275  * @param   string  usually the method name that triggered the debug call:
4276  *                  for example 'query', 'prepare', 'execute', 'parameters',
4277  *                  'beginTransaction', 'commit', 'rollback'
4278  * @param   string  message that should be appended to the debug variable
4279  * @param   array   contains context information about the debug() call
4280  *                  common keys are: is_manip, time, result etc.
4281  *
4282  * @return  void|string optionally return a modified message, this allows
4283  *                      rewriting a query before being issued or prepared
4284  *
4285  * @access  public
4286  */
4287 function MDB2_defaultDebugOutput(&$db, $scope, $message, $context = array())
4288 {
4289     $db->debug_output.= $scope.'('.$db->db_index.'): ';
4290     $db->debug_output.= $message.$db->getOption('log_line_break');
4291     return $message;
4292 }
4293
4294 // }}}