thomascube
2012-04-17 6ab9e8a6c8474063ea70c727bb3fe107f1a864dc
commit | author | age
200b16 1 <?php
A 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 //
7244b4 46 // $Id: MDB2.php 295587 2010-02-28 17:16:38Z quipo $
200b16 47 //
A 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);
2273d4 104 define('MDB2_ERROR_DISCONNECT_FAILED',  -37);
200b16 105
A 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 {
7244b4 270     // {{{ function setOptions($db, $options)
200b16 271
A 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      */
7244b4 282     static function setOptions($db, $options)
200b16 283     {
A 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      */
7244b4 307     static function classExists($classname)
200b16 308     {
7244b4 309         return class_exists($classname, false);
200b16 310     }
A 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      */
7244b4 325     static function loadClass($class_name, $debug)
200b16 326     {
A 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                 }
7244b4 340                 $err = MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null, $msg);
200b16 341                 return $err;
A 342             }
2273d4 343             if (!MDB2::classExists($class_name)) {
A 344                 $msg = "unable to load class '$class_name' from file '$file_name'";
7244b4 345                 $err = MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null, $msg);
2273d4 346                 return $err;
A 347             }
200b16 348         }
A 349         return MDB2_OK;
350     }
351
352     // }}}
7244b4 353     // {{{ function factory($dsn, $options = false)
200b16 354
A 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      */
7244b4 369     static function factory($dsn, $options = false)
200b16 370     {
A 371         $dsninfo = MDB2::parseDSN($dsn);
372         if (empty($dsninfo['phptype'])) {
7244b4 373             $err = MDB2::raiseError(MDB2_ERROR_NOT_FOUND,
200b16 374                 null, null, 'no RDBMS driver specified');
A 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
0f6e0e 385         $db = new $class_name();
200b16 386         $db->setDSN($dsninfo);
A 387         $err = MDB2::setOptions($db, $options);
388         if (PEAR::isError($err)) {
389             return $err;
390         }
391
392         return $db;
393     }
394
395     // }}}
7244b4 396     // {{{ function connect($dsn, $options = false)
200b16 397
A 398     /**
2273d4 399      * Create a new MDB2_Driver_* connection object and connect to the specified
200b16 400      * database
A 401      *
2273d4 402      * @param mixed $dsn     'data source name', see the MDB2::parseDSN
A 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.
200b16 408      *
2273d4 409      * @return mixed a newly created MDB2 connection object, or a MDB2
A 410      *               error object on error
200b16 411      *
A 412      * @access  public
413      * @see     MDB2::parseDSN
414      */
7244b4 415     static function connect($dsn, $options = false)
200b16 416     {
7244b4 417         $db = MDB2::factory($dsn, $options);
200b16 418         if (PEAR::isError($db)) {
A 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     // }}}
7244b4 434     // {{{ function singleton($dsn = null, $options = false)
200b16 435
A 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      */
7244b4 454     static function singleton($dsn = null, $options = false)
200b16 455     {
A 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'])) {
7244b4 470             return $GLOBALS['_MDB2_databases'][key($GLOBALS['_MDB2_databases'])];
200b16 471         }
7244b4 472         $db = MDB2::factory($dsn, $options);
200b16 473         return $db;
A 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      */
7244b4 488     static function areEquals($arr1, $arr2)
200b16 489     {
A 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      *
7244b4 507      * @param string $file name of the file in the MDB2 directory (without '.php')
200b16 508      *
7244b4 509      * @return string name of the file that was included
200b16 510      *
A 511      * @access  public
512      */
7244b4 513     static function loadFile($file)
200b16 514     {
A 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     {
2273d4 539         return '@package_version@';
200b16 540     }
A 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      */
7244b4 597     static function isError($data, $code = null)
200b16 598     {
7244b4 599         if ($data instanceof MDB2_Error) {
2273d4 600             if (null === $code) {
200b16 601                 return true;
A 602             }
7244b4 603             if (is_string($code)) {
A 604                 return $data->getMessage() === $code;
605             }
606             return in_array($data->getCode(), (array)$code);
200b16 607         }
A 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     {
7244b4 624         return ($value instanceof MDB2_Driver_Common);
200b16 625     }
A 626
627     // }}}
628     // {{{ function isResult($value)
629
630     /**
631      * Tell whether a value is a MDB2 result
632      *
7244b4 633      * @param mixed $value value to test
200b16 634      *
7244b4 635      * @return bool whether $value is a MDB2 result
200b16 636      *
7244b4 637      * @access public
200b16 638      */
A 639     function isResult($value)
640     {
7244b4 641         return ($value instanceof MDB2_Result);
200b16 642     }
A 643
644     // }}}
645     // {{{ function isResultCommon($value)
646
647     /**
648      * Tell whether a value is a MDB2 result implementing the common interface
649      *
7244b4 650      * @param mixed $value value to test
200b16 651      *
7244b4 652      * @return bool whether $value is a MDB2 result implementing the common interface
200b16 653      *
A 654      * @access  public
655      */
7244b4 656     static function isResultCommon($value)
200b16 657     {
7244b4 658         return ($value instanceof MDB2_Result_Common);
200b16 659     }
A 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     {
7244b4 675         return ($value instanceof MDB2_Statement_Common);
200b16 676     }
A 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     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',
2273d4 738                 MDB2_ERROR_DISCONNECT_FAILED  => 'disconnect failed',
200b16 739             );
A 740         }
741
2273d4 742         if (null === $value) {
200b16 743             return $errorMessages;
A 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      */
7244b4 794     static function parseDSN($dsn)
200b16 795     {
2273d4 796         $parsed = $GLOBALS['_MDB2_dsninfo_default'];
200b16 797
A 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)) {
2273d4 826             return $parsed;
200b16 827         }
A 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;
2273d4 863                 $pos = strrpos($proto_opts, '/');
A 864                 $dsn = substr($proto_opts, $pos + 1);
865                 $proto_opts = substr($proto_opts, 0, $pos);
200b16 866             } elseif (strpos($dsn, '/') !== false) {
A 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) {
4da69b 891                 $parsed['database'] = rawurldecode($dsn);
200b16 892             // /database?param1=value1&param2=value2
A 893             } else {
4da69b 894                 $parsed['database'] = rawurldecode(substr($dsn, 0, $pos));
200b16 895                 $dsn = substr($dsn, $pos + 1);
A 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);
2273d4 903                     if (!array_key_exists($key, $parsed) || false === $parsed[$key]) {
200b16 904                         // don't allow params overwrite
A 905                         $parsed[$key] = rawurldecode($value);
906                     }
907                 }
908             }
909         }
910
2273d4 911         return $parsed;
200b16 912     }
A 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      */
7244b4 926     static function fileExists($file)
200b16 927     {
A 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      */
7244b4 971     function __construct($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN,
200b16 972               $level = E_USER_NOTICE, $debuginfo = null, $dummy = null)
A 973     {
2273d4 974         if (null === $code) {
200b16 975             $code = MDB2_ERROR;
A 976         }
977         $this->PEAR_Error('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     var $db_index = 0;
1004
1005     /**
1006      * DSN used for the next query
1007      * @var     array
1008      * @access  protected
1009      */
1010     var $dsn = array();
1011
1012     /**
1013      * DSN that was used to create the current connection
1014      * @var     array
1015      * @access  protected
1016      */
1017     var $connected_dsn = array();
1018
1019     /**
1020      * connection resource
1021      * @var     mixed
1022      * @access  protected
1023      */
1024     var $connection = 0;
1025
1026     /**
1027      * if the current opened connection is a persistent connection
1028      * @var     bool
1029      * @access  protected
1030      */
1031     var $opened_persistent;
1032
1033     /**
1034      * the name of the database for the next query
1035      * @var     string
1036      * @access  protected
1037      */
1038     var $database_name = '';
1039
1040     /**
1041      * the name of the database currently selected
1042      * @var     string
1043      * @access  protected
1044      */
1045     var $connected_database_name = '';
1046
1047     /**
1048      * server version information
1049      * @var     string
1050      * @access  protected
1051      */
1052     var $connected_server_info = '';
1053
1054     /**
1055      * list of all supported features of the given driver
1056      * @var     array
1057      * @access  public
1058      */
1059     var $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>
2273d4 1119      *  <li>$options['bindname_format'] -> string: regular expression pattern for named parameters</li>
A 1120      *  <li>$options['multi_query'] -> boolean: determines if queries returning multiple result sets should be executed</li>
200b16 1121      *  <li>$options['max_identifiers_length'] -> integer: max identifier length</li>
2273d4 1122      *  <li>$options['default_fk_action_onupdate'] -> string: default FOREIGN KEY ON UPDATE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']</li>
A 1123      *  <li>$options['default_fk_action_ondelete'] -> string: default FOREIGN KEY ON DELETE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']</li>
200b16 1124      * </ul>
A 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     var $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,
2273d4 1173         'default_fk_action_onupdate' => 'RESTRICT',
A 1174         'default_fk_action_ondelete' => 'RESTRICT',
200b16 1175     );
A 1176
1177     /**
1178      * string array
1179      * @var     string
1180      * @access  protected
1181      */
1182     var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => false, 'escape_pattern' => false);
1183
1184     /**
1185      * identifier quoting
1186      * @var     array
1187      * @access  protected
1188      */
1189     var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
1190
1191     /**
1192      * sql comments
1193      * @var     array
1194      * @access  protected
1195      */
1196     var $sql_comments = array(
1197         array('start' => '--', 'end' => "\n", 'escape' => false),
1198         array('start' => '/*', 'end' => '*/', 'escape' => false),
1199     );
1200
1201     /**
1202      * comparision wildcards
1203      * @var     array
1204      * @access  protected
1205      */
1206     var $wildcards = array('%', '_');
1207
1208     /**
1209      * column alias keyword
1210      * @var     string
1211      * @access  protected
1212      */
1213     var $as_keyword = ' AS ';
1214
1215     /**
1216      * warnings
1217      * @var     array
1218      * @access  protected
1219      */
1220     var $warnings = array();
1221
1222     /**
1223      * string with the debugging information
1224      * @var     string
1225      * @access  public
1226      */
1227     var $debug_output = '';
1228
1229     /**
1230      * determine if there is an open transaction
1231      * @var     bool
1232      * @access  protected
1233      */
1234     var $in_transaction = false;
1235
1236     /**
1237      * the smart transaction nesting depth
1238      * @var     int
1239      * @access  protected
1240      */
1241     var $nested_transaction_counter = null;
1242
1243     /**
1244      * the first error that occured inside a nested transaction
1245      * @var     MDB2_Error|bool
1246      * @access  protected
1247      */
1248     var $has_transaction_error = false;
1249
1250     /**
1251      * result offset used in the next query
1252      * @var     int
1253      * @access  protected
1254      */
1255     var $offset = 0;
1256
1257     /**
1258      * result limit used in the next query
1259      * @var     int
1260      * @access  protected
1261      */
1262     var $limit = 0;
1263
1264     /**
1265      * Database backend used in PHP (mysql, odbc etc.)
1266      * @var     string
1267      * @access  public
1268      */
1269     var $phptype;
1270
1271     /**
1272      * Database used with regards to SQL syntax etc.
1273      * @var     string
1274      * @access  public
1275      */
1276     var $dbsyntax;
1277
1278     /**
1279      * the last query sent to the driver
1280      * @var     string
1281      * @access  public
1282      */
1283     var $last_query;
1284
1285     /**
1286      * the default fetchmode used
1287      * @var     int
1288      * @access  protected
1289      */
1290     var $fetchmode = MDB2_FETCHMODE_ORDERED;
1291
1292     /**
1293      * array of module instances
1294      * @var     array
1295      * @access  protected
1296      */
1297     var $modules = array();
1298
1299     /**
1300      * determines of the PHP4 destructor emulation has been enabled yet
1301      * @var     array
1302      * @access  protected
1303      */
1304     var $destructor_registered = true;
1305
1306     // }}}
1307     // {{{ constructor: function __construct()
1308
1309     /**
1310      * Constructor
1311      */
1312     function __construct()
1313     {
1314         end($GLOBALS['_MDB2_databases']);
1315         $db_index = key($GLOBALS['_MDB2_databases']) + 1;
1316         $GLOBALS['_MDB2_databases'][$db_index] = &$this;
1317         $this->db_index = $db_index;
1318     }
1319
1320     // }}}
1321     // {{{ destructor: function __destruct()
1322
1323     /**
1324      *  Destructor
1325      */
1326     function __destruct()
1327     {
1328         $this->disconnect(false);
1329     }
1330
1331     // }}}
1332     // {{{ function free()
1333
1334     /**
1335      * Free the internal references so that the instance can be destroyed
1336      *
1337      * @return  bool    true on success, false if result is invalid
1338      *
1339      * @access  public
1340      */
1341     function free()
1342     {
1343         unset($GLOBALS['_MDB2_databases'][$this->db_index]);
1344         unset($this->db_index);
1345         return MDB2_OK;
1346     }
1347
1348     // }}}
1349     // {{{ function __toString()
1350
1351     /**
1352      * String conversation
1353      *
1354      * @return  string representation of the object
1355      *
1356      * @access  public
1357      */
1358     function __toString()
1359     {
1360         $info = get_class($this);
1361         $info.= ': (phptype = '.$this->phptype.', dbsyntax = '.$this->dbsyntax.')';
1362         if ($this->connection) {
1363             $info.= ' [connected]';
1364         }
1365         return $info;
1366     }
1367
1368     // }}}
1369     // {{{ function errorInfo($error = null)
1370
1371     /**
1372      * This method is used to collect information about an error
1373      *
1374      * @param   mixed   error code or resource
1375      *
1376      * @return  array   with MDB2 errorcode, native error code, native message
1377      *
1378      * @access  public
1379      */
1380     function errorInfo($error = null)
1381     {
1382         return array($error, null, null);
1383     }
1384
1385     // }}}
1386     // {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
1387
1388     /**
1389      * This method is used to communicate an error and invoke error
1390      * callbacks etc.  Basically a wrapper for PEAR::raiseError
1391      * without the message string.
1392      *
2273d4 1393      * @param mixed  $code     integer error code, or a PEAR error object (all 
A 1394      *                         other parameters are ignored if this parameter is
1395      *                         an object
1396      * @param int    $mode     error mode, see PEAR_Error docs
1397      * @param mixed  $options  If error mode is PEAR_ERROR_TRIGGER, this is the
1398      *                         error level (E_USER_NOTICE etc). If error mode is
1399      *                         PEAR_ERROR_CALLBACK, this is the callback function,
1400      *                         either as a function name, or as an array of an
1401      *                         object and method name. For other error modes this
1402      *                         parameter is ignored.
1403      * @param string $userinfo Extra debug information. Defaults to the last
1404      *                         query and native error code.
1405      * @param string $method   name of the method that triggered the error
1406      * @param string $dummy1   not used
1407      * @param bool   $dummy2   not used
200b16 1408      *
2273d4 1409      * @return PEAR_Error instance of a PEAR Error object
A 1410      * @access public
1411      * @see    PEAR_Error
200b16 1412      */
2273d4 1413     function &raiseError($code = null,
A 1414                          $mode = null,
1415                          $options = null,
1416                          $userinfo = null,
1417                          $method = null,
1418                          $dummy1 = null,
1419                          $dummy2 = false
1420     ) {
200b16 1421         $userinfo = "[Error message: $userinfo]\n";
A 1422         // The error is yet a MDB2 error object
1423         if (PEAR::isError($code)) {
1424             // because we use the static PEAR::raiseError, our global
1425             // handler should be used if it is set
2273d4 1426             if ((null === $mode) && !empty($this->_default_error_mode)) {
200b16 1427                 $mode    = $this->_default_error_mode;
A 1428                 $options = $this->_default_error_options;
1429             }
2273d4 1430             if (null === $userinfo) {
200b16 1431                 $userinfo = $code->getUserinfo();
A 1432             }
1433             $code = $code->getCode();
1434         } elseif ($code == MDB2_ERROR_NOT_FOUND) {
1435             // extension not loaded: don't call $this->errorInfo() or the script
1436             // will die
1437         } elseif (isset($this->connection)) {
1438             if (!empty($this->last_query)) {
1439                 $userinfo.= "[Last executed query: {$this->last_query}]\n";
1440             }
1441             $native_errno = $native_msg = null;
1442             list($code, $native_errno, $native_msg) = $this->errorInfo($code);
2273d4 1443             if ((null !== $native_errno) && $native_errno !== '') {
200b16 1444                 $userinfo.= "[Native code: $native_errno]\n";
A 1445             }
2273d4 1446             if ((null !== $native_msg) && $native_msg !== '') {
200b16 1447                 $userinfo.= "[Native message: ". strip_tags($native_msg) ."]\n";
A 1448             }
2273d4 1449             if (null !== $method) {
200b16 1450                 $userinfo = $method.': '.$userinfo;
A 1451             }
1452         }
1453
7244b4 1454         $err = PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
200b16 1455         if ($err->getMode() !== PEAR_ERROR_RETURN
A 1456             && isset($this->nested_transaction_counter) && !$this->has_transaction_error) {
7244b4 1457             $this->has_transaction_error = $err;
200b16 1458         }
A 1459         return $err;
1460     }
1461
1462     // }}}
1463     // {{{ function resetWarnings()
1464
1465     /**
1466      * reset the warning array
1467      *
1468      * @return void
1469      *
1470      * @access  public
1471      */
1472     function resetWarnings()
1473     {
1474         $this->warnings = array();
1475     }
1476
1477     // }}}
1478     // {{{ function getWarnings()
1479
1480     /**
1481      * Get all warnings in reverse order.
1482      * This means that the last warning is the first element in the array
1483      *
1484      * @return  array   with warnings
1485      *
1486      * @access  public
1487      * @see     resetWarnings()
1488      */
1489     function getWarnings()
1490     {
1491         return array_reverse($this->warnings);
1492     }
1493
1494     // }}}
1495     // {{{ function setFetchMode($fetchmode, $object_class = 'stdClass')
1496
1497     /**
1498      * Sets which fetch mode should be used by default on queries
1499      * on this connection
1500      *
1501      * @param   int     MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC
1502      *                               or MDB2_FETCHMODE_OBJECT
1503      * @param   string  the class name of the object to be returned
1504      *                               by the fetch methods when the
1505      *                               MDB2_FETCHMODE_OBJECT mode is selected.
1506      *                               If no class is specified by default a cast
1507      *                               to object from the assoc array row will be
1508      *                               done.  There is also the possibility to use
1509      *                               and extend the 'MDB2_row' class.
1510      *
1511      * @return  mixed   MDB2_OK or MDB2 Error Object
1512      *
1513      * @access  public
1514      * @see     MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC, MDB2_FETCHMODE_OBJECT
1515      */
1516     function setFetchMode($fetchmode, $object_class = 'stdClass')
1517     {
1518         switch ($fetchmode) {
1519         case MDB2_FETCHMODE_OBJECT:
1520             $this->options['fetch_class'] = $object_class;
1521         case MDB2_FETCHMODE_ORDERED:
1522         case MDB2_FETCHMODE_ASSOC:
1523             $this->fetchmode = $fetchmode;
1524             break;
1525         default:
1526             return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
1527                 'invalid fetchmode mode', __FUNCTION__);
1528         }
1529
1530         return MDB2_OK;
1531     }
1532
1533     // }}}
1534     // {{{ function setOption($option, $value)
1535
1536     /**
1537      * set the option for the db class
1538      *
1539      * @param   string  option name
1540      * @param   mixed   value for the option
1541      *
1542      * @return  mixed   MDB2_OK or MDB2 Error Object
1543      *
1544      * @access  public
1545      */
1546     function setOption($option, $value)
1547     {
1548         if (array_key_exists($option, $this->options)) {
1549             $this->options[$option] = $value;
1550             return MDB2_OK;
1551         }
1552         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
1553             "unknown option $option", __FUNCTION__);
1554     }
1555
1556     // }}}
1557     // {{{ function getOption($option)
1558
1559     /**
1560      * Returns the value of an option
1561      *
1562      * @param   string  option name
1563      *
1564      * @return  mixed   the option value or error object
1565      *
1566      * @access  public
1567      */
1568     function getOption($option)
1569     {
1570         if (array_key_exists($option, $this->options)) {
1571             return $this->options[$option];
1572         }
1573         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
1574             "unknown option $option", __FUNCTION__);
1575     }
1576
1577     // }}}
1578     // {{{ function debug($message, $scope = '', $is_manip = null)
1579
1580     /**
1581      * set a debug message
1582      *
1583      * @param   string  message that should be appended to the debug variable
1584      * @param   string  usually the method name that triggered the debug call:
1585      *                  for example 'query', 'prepare', 'execute', 'parameters',
1586      *                  'beginTransaction', 'commit', 'rollback'
1587      * @param   array   contains context information about the debug() call
1588      *                  common keys are: is_manip, time, result etc.
1589      *
1590      * @return void
1591      *
1592      * @access  public
1593      */
1594     function debug($message, $scope = '', $context = array())
1595     {
1596         if ($this->options['debug'] && $this->options['debug_handler']) {
1597             if (!$this->options['debug_expanded_output']) {
1598                 if (!empty($context['when']) && $context['when'] !== 'pre') {
1599                     return null;
1600                 }
1601                 $context = empty($context['is_manip']) ? false : $context['is_manip'];
1602             }
1603             return call_user_func_array($this->options['debug_handler'], array(&$this, $scope, $message, $context));
1604         }
1605         return null;
1606     }
1607
1608     // }}}
1609     // {{{ function getDebugOutput()
1610
1611     /**
1612      * output debug info
1613      *
1614      * @return  string  content of the debug_output class variable
1615      *
1616      * @access  public
1617      */
1618     function getDebugOutput()
1619     {
1620         return $this->debug_output;
1621     }
1622
1623     // }}}
1624     // {{{ function escape($text)
1625
1626     /**
1627      * Quotes a string so it can be safely used in a query. It will quote
1628      * the text so it can safely be used within a query.
1629      *
1630      * @param   string  the input string to quote
1631      * @param   bool    escape wildcards
1632      *
1633      * @return  string  quoted string
1634      *
1635      * @access  public
1636      */
1637     function escape($text, $escape_wildcards = false)
1638     {
1639         if ($escape_wildcards) {
1640             $text = $this->escapePattern($text);
1641         }
1642
1643         $text = str_replace($this->string_quoting['end'], $this->string_quoting['escape'] . $this->string_quoting['end'], $text);
1644         return $text;
1645     }
1646
1647     // }}}
1648     // {{{ function escapePattern($text)
1649
1650     /**
1651      * Quotes pattern (% and _) characters in a string)
1652      *
1653      * @param   string  the input string to quote
1654      *
1655      * @return  string  quoted string
1656      *
1657      * @access  public
1658      */
1659     function escapePattern($text)
1660     {
1661         if ($this->string_quoting['escape_pattern']) {
1662             $text = str_replace($this->string_quoting['escape_pattern'], $this->string_quoting['escape_pattern'] . $this->string_quoting['escape_pattern'], $text);
1663             foreach ($this->wildcards as $wildcard) {
1664                 $text = str_replace($wildcard, $this->string_quoting['escape_pattern'] . $wildcard, $text);
1665             }
1666         }
1667         return $text;
1668     }
1669
1670     // }}}
1671     // {{{ function quoteIdentifier($str, $check_option = false)
1672
1673     /**
1674      * Quote a string so it can be safely used as a table or column name
1675      *
1676      * Delimiting style depends on which database driver is being used.
1677      *
1678      * NOTE: just because you CAN use delimited identifiers doesn't mean
1679      * you SHOULD use them.  In general, they end up causing way more
1680      * problems than they solve.
1681      *
1682      * NOTE: if you have table names containing periods, don't use this method
1683      * (@see bug #11906)
1684      *
1685      * Portability is broken by using the following characters inside
1686      * delimited identifiers:
1687      *   + backtick (<kbd>`</kbd>) -- due to MySQL
1688      *   + double quote (<kbd>"</kbd>) -- due to Oracle
1689      *   + brackets (<kbd>[</kbd> or <kbd>]</kbd>) -- due to Access
1690      *
1691      * Delimited identifiers are known to generally work correctly under
1692      * the following drivers:
1693      *   + mssql
1694      *   + mysql
1695      *   + mysqli
1696      *   + oci8
1697      *   + pgsql
1698      *   + sqlite
1699      *
1700      * InterBase doesn't seem to be able to use delimited identifiers
1701      * via PHP 4.  They work fine under PHP 5.
1702      *
1703      * @param   string  identifier name to be quoted
1704      * @param   bool    check the 'quote_identifier' option
1705      *
1706      * @return  string  quoted identifier string
1707      *
1708      * @access  public
1709      */
1710     function quoteIdentifier($str, $check_option = false)
1711     {
1712         if ($check_option && !$this->options['quote_identifier']) {
1713             return $str;
1714         }
1715         $str = str_replace($this->identifier_quoting['end'], $this->identifier_quoting['escape'] . $this->identifier_quoting['end'], $str);
1716         $parts = explode('.', $str);
1717         foreach (array_keys($parts) as $k) {
1718             $parts[$k] = $this->identifier_quoting['start'] . $parts[$k] . $this->identifier_quoting['end'];
1719         }
1720         return implode('.', $parts);
1721     }
1722
1723     // }}}
1724     // {{{ function getAsKeyword()
1725
1726     /**
1727      * Gets the string to alias column
1728      *
1729      * @return string to use when aliasing a column
1730      */
1731     function getAsKeyword()
1732     {
1733         return $this->as_keyword;
1734     }
1735
1736     // }}}
1737     // {{{ function getConnection()
1738
1739     /**
1740      * Returns a native connection
1741      *
1742      * @return  mixed   a valid MDB2 connection object,
1743      *                  or a MDB2 error object on error
1744      *
1745      * @access  public
1746      */
1747     function getConnection()
1748     {
1749         $result = $this->connect();
1750         if (PEAR::isError($result)) {
1751             return $result;
1752         }
1753         return $this->connection;
1754     }
1755
1756      // }}}
1757     // {{{ function _fixResultArrayValues(&$row, $mode)
1758
1759     /**
1760      * Do all necessary conversions on result arrays to fix DBMS quirks
1761      *
1762      * @param   array   the array to be fixed (passed by reference)
1763      * @param   array   bit-wise addition of the required portability modes
1764      *
1765      * @return  void
1766      *
1767      * @access  protected
1768      */
1769     function _fixResultArrayValues(&$row, $mode)
1770     {
1771         switch ($mode) {
1772         case MDB2_PORTABILITY_EMPTY_TO_NULL:
1773             foreach ($row as $key => $value) {
1774                 if ($value === '') {
1775                     $row[$key] = null;
1776                 }
1777             }
1778             break;
1779         case MDB2_PORTABILITY_RTRIM:
1780             foreach ($row as $key => $value) {
1781                 if (is_string($value)) {
1782                     $row[$key] = rtrim($value);
1783                 }
1784             }
1785             break;
1786         case MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES:
1787             $tmp_row = array();
1788             foreach ($row as $key => $value) {
1789                 $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
1790             }
1791             $row = $tmp_row;
1792             break;
1793         case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL):
1794             foreach ($row as $key => $value) {
1795                 if ($value === '') {
1796                     $row[$key] = null;
1797                 } elseif (is_string($value)) {
1798                     $row[$key] = rtrim($value);
1799                 }
1800             }
1801             break;
1802         case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
1803             $tmp_row = array();
1804             foreach ($row as $key => $value) {
1805                 if (is_string($value)) {
1806                     $value = rtrim($value);
1807                 }
1808                 $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
1809             }
1810             $row = $tmp_row;
1811             break;
1812         case (MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
1813             $tmp_row = array();
1814             foreach ($row as $key => $value) {
1815                 if ($value === '') {
1816                     $value = null;
1817                 }
1818                 $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
1819             }
1820             $row = $tmp_row;
1821             break;
1822         case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
1823             $tmp_row = array();
1824             foreach ($row as $key => $value) {
1825                 if ($value === '') {
1826                     $value = null;
1827                 } elseif (is_string($value)) {
1828                     $value = rtrim($value);
1829                 }
1830                 $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
1831             }
1832             $row = $tmp_row;
1833             break;
1834         }
1835     }
1836
1837     // }}}
7244b4 1838     // {{{ function loadModule($module, $property = null, $phptype_specific = null)
200b16 1839
A 1840     /**
1841      * loads a module
1842      *
1843      * @param   string  name of the module that should be loaded
1844      *                  (only used for error messages)
1845      * @param   string  name of the property into which the class will be loaded
1846      * @param   bool    if the class to load for the module is specific to the
1847      *                  phptype
1848      *
1849      * @return  object  on success a reference to the given module is returned
1850      *                  and on failure a PEAR error
1851      *
1852      * @access  public
1853      */
7244b4 1854     function loadModule($module, $property = null, $phptype_specific = null)
200b16 1855     {
A 1856         if (!$property) {
1857             $property = strtolower($module);
1858         }
1859
1860         if (!isset($this->{$property})) {
1861             $version = $phptype_specific;
1862             if ($phptype_specific !== false) {
1863                 $version = true;
1864                 $class_name = 'MDB2_Driver_'.$module.'_'.$this->phptype;
1865                 $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
1866             }
1867             if ($phptype_specific === false
1868                 || (!MDB2::classExists($class_name) && !MDB2::fileExists($file_name))
1869             ) {
1870                 $version = false;
1871                 $class_name = 'MDB2_'.$module;
1872                 $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
1873             }
1874
1875             $err = MDB2::loadClass($class_name, $this->getOption('debug'));
1876             if (PEAR::isError($err)) {
1877                 return $err;
1878             }
1879
1880             // load module in a specific version
1881             if ($version) {
1882                 if (method_exists($class_name, 'getClassName')) {
1883                     $class_name_new = call_user_func(array($class_name, 'getClassName'), $this->db_index);
1884                     if ($class_name != $class_name_new) {
1885                         $class_name = $class_name_new;
1886                         $err = MDB2::loadClass($class_name, $this->getOption('debug'));
1887                         if (PEAR::isError($err)) {
1888                             return $err;
1889                         }
1890                     }
1891                 }
1892             }
1893
1894             if (!MDB2::classExists($class_name)) {
7244b4 1895                 $err = $this->raiseError(MDB2_ERROR_LOADMODULE, null, null,
200b16 1896                     "unable to load module '$module' into property '$property'", __FUNCTION__);
A 1897                 return $err;
1898             }
1899             $this->{$property} = new $class_name($this->db_index);
7244b4 1900             $this->modules[$module] = $this->{$property};
200b16 1901             if ($version) {
A 1902                 // this will be used in the connect method to determine if the module
1903                 // needs to be loaded with a different version if the server
1904                 // version changed in between connects
1905                 $this->loaded_version_modules[] = $property;
1906             }
1907         }
1908
1909         return $this->{$property};
1910     }
1911
1912     // }}}
1913     // {{{ function __call($method, $params)
1914
1915     /**
1916      * Calls a module method using the __call magic method
1917      *
1918      * @param   string  Method name.
1919      * @param   array   Arguments.
1920      *
1921      * @return  mixed   Returned value.
1922      */
1923     function __call($method, $params)
1924     {
1925         $module = null;
1926         if (preg_match('/^([a-z]+)([A-Z])(.*)$/', $method, $match)
1927             && isset($this->options['modules'][$match[1]])
1928         ) {
1929             $module = $this->options['modules'][$match[1]];
1930             $method = strtolower($match[2]).$match[3];
1931             if (!isset($this->modules[$module]) || !is_object($this->modules[$module])) {
7244b4 1932                 $result = $this->loadModule($module);
200b16 1933                 if (PEAR::isError($result)) {
A 1934                     return $result;
1935                 }
1936             }
1937         } else {
1938             foreach ($this->modules as $key => $foo) {
1939                 if (is_object($this->modules[$key])
1940                     && method_exists($this->modules[$key], $method)
1941                 ) {
1942                     $module = $key;
1943                     break;
1944                 }
1945             }
1946         }
2273d4 1947         if (null !== $module) {
200b16 1948             return call_user_func_array(array(&$this->modules[$module], $method), $params);
A 1949         }
1950         trigger_error(sprintf('Call to undefined function: %s::%s().', get_class($this), $method), E_USER_ERROR);
1951     }
1952
1953     // }}}
1954     // {{{ function beginTransaction($savepoint = null)
1955
1956     /**
1957      * Start a transaction or set a savepoint.
1958      *
1959      * @param   string  name of a savepoint to set
1960      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
1961      *
1962      * @access  public
1963      */
1964     function beginTransaction($savepoint = null)
1965     {
1966         $this->debug('Starting transaction', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
1967         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
1968             'transactions are not supported', __FUNCTION__);
1969     }
1970
1971     // }}}
1972     // {{{ function commit($savepoint = null)
1973
1974     /**
1975      * Commit the database changes done during a transaction that is in
1976      * progress or release a savepoint. This function may only be called when
1977      * auto-committing is disabled, otherwise it will fail. Therefore, a new
1978      * transaction is implicitly started after committing the pending changes.
1979      *
1980      * @param   string  name of a savepoint to release
1981      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
1982      *
1983      * @access  public
1984      */
1985     function commit($savepoint = null)
1986     {
1987         $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
1988         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
1989             'commiting transactions is not supported', __FUNCTION__);
1990     }
1991
1992     // }}}
1993     // {{{ function rollback($savepoint = null)
1994
1995     /**
1996      * Cancel any database changes done during a transaction or since a specific
1997      * savepoint that is in progress. This function may only be called when
1998      * auto-committing is disabled, otherwise it will fail. Therefore, a new
1999      * transaction is implicitly started after canceling the pending changes.
2000      *
2001      * @param   string  name of a savepoint to rollback to
2002      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
2003      *
2004      * @access  public
2005      */
2006     function rollback($savepoint = null)
2007     {
2008         $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
2009         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2010             'rolling back transactions is not supported', __FUNCTION__);
2011     }
2012
2013     // }}}
2014     // {{{ function inTransaction($ignore_nested = false)
2015
2016     /**
2017      * If a transaction is currently open.
2018      *
2019      * @param   bool    if the nested transaction count should be ignored
2020      * @return  int|bool    - an integer with the nesting depth is returned if a
2021      *                      nested transaction is open
2022      *                      - true is returned for a normal open transaction
2023      *                      - false is returned if no transaction is open
2024      *
2025      * @access  public
2026      */
2027     function inTransaction($ignore_nested = false)
2028     {
2029         if (!$ignore_nested && isset($this->nested_transaction_counter)) {
2030             return $this->nested_transaction_counter;
2031         }
2032         return $this->in_transaction;
2033     }
2034
2035     // }}}
2036     // {{{ function setTransactionIsolation($isolation)
2037
2038     /**
2039      * Set the transacton isolation level.
2040      *
2041      * @param   string  standard isolation level
2042      *                  READ UNCOMMITTED (allows dirty reads)
2043      *                  READ COMMITTED (prevents dirty reads)
2044      *                  REPEATABLE READ (prevents nonrepeatable reads)
2045      *                  SERIALIZABLE (prevents phantom reads)
2046      * @param   array some transaction options:
2047      *                  'wait' => 'WAIT' | 'NO WAIT'
2048      *                  'rw'   => 'READ WRITE' | 'READ ONLY'
2049      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
2050      *
2051      * @access  public
2052      * @since   2.1.1
2053      */
2054     function setTransactionIsolation($isolation, $options = array())
2055     {
2056         $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
2057         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2058             'isolation level setting is not supported', __FUNCTION__);
2059     }
2060
2061     // }}}
2062     // {{{ function beginNestedTransaction($savepoint = false)
2063
2064     /**
2065      * Start a nested transaction.
2066      *
2067      * @return  mixed   MDB2_OK on success/savepoint name, a MDB2 error on failure
2068      *
2069      * @access  public
2070      * @since   2.1.1
2071      */
2072     function beginNestedTransaction()
2073     {
2074         if ($this->in_transaction) {
2075             ++$this->nested_transaction_counter;
2076             $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
2077             if ($this->supports('savepoints') && $savepoint) {
2078                 return $this->beginTransaction($savepoint);
2079             }
2080             return MDB2_OK;
2081         }
2082         $this->has_transaction_error = false;
2083         $result = $this->beginTransaction();
2084         $this->nested_transaction_counter = 1;
2085         return $result;
2086     }
2087
2088     // }}}
2089     // {{{ function completeNestedTransaction($force_rollback = false, $release = false)
2090
2091     /**
2092      * Finish a nested transaction by rolling back if an error occured or
2093      * committing otherwise.
2094      *
2095      * @param   bool    if the transaction should be rolled back regardless
2096      *                  even if no error was set within the nested transaction
2097      * @return  mixed   MDB_OK on commit/counter decrementing, false on rollback
2098      *                  and a MDB2 error on failure
2099      *
2100      * @access  public
2101      * @since   2.1.1
2102      */
2103     function completeNestedTransaction($force_rollback = false)
2104     {
2105         if ($this->nested_transaction_counter > 1) {
2106             $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
2107             if ($this->supports('savepoints') && $savepoint) {
2108                 if ($force_rollback || $this->has_transaction_error) {
2109                     $result = $this->rollback($savepoint);
2110                     if (!PEAR::isError($result)) {
2111                         $result = false;
2112                         $this->has_transaction_error = false;
2113                     }
2114                 } else {
2115                     $result = $this->commit($savepoint);
2116                 }
2117             } else {
2118                 $result = MDB2_OK;
2119             }
2120             --$this->nested_transaction_counter;
2121             return $result;
2122         }
2123
2124         $this->nested_transaction_counter = null;
2125         $result = MDB2_OK;
2126
2127         // transaction has not yet been rolled back
2128         if ($this->in_transaction) {
2129             if ($force_rollback || $this->has_transaction_error) {
2130                 $result = $this->rollback();
2131                 if (!PEAR::isError($result)) {
2132                     $result = false;
2133                 }
2134             } else {
2135                 $result = $this->commit();
2136             }
2137         }
2138         $this->has_transaction_error = false;
2139         return $result;
2140     }
2141
2142     // }}}
2143     // {{{ function failNestedTransaction($error = null, $immediately = false)
2144
2145     /**
2146      * Force setting nested transaction to failed.
2147      *
2148      * @param   mixed   value to return in getNestededTransactionError()
2149      * @param   bool    if the transaction should be rolled back immediately
2150      * @return  bool    MDB2_OK
2151      *
2152      * @access  public
2153      * @since   2.1.1
2154      */
2155     function failNestedTransaction($error = null, $immediately = false)
2156     {
2273d4 2157         if (null !== $error) {
200b16 2158             $error = $this->has_transaction_error ? $this->has_transaction_error : true;
A 2159         } elseif (!$error) {
2160             $error = true;
2161         }
2162         $this->has_transaction_error = $error;
2163         if (!$immediately) {
2164             return MDB2_OK;
2165         }
2166         return $this->rollback();
2167     }
2168
2169     // }}}
2170     // {{{ function getNestedTransactionError()
2171
2172     /**
2173      * The first error that occured since the transaction start.
2174      *
2175      * @return  MDB2_Error|bool     MDB2 error object if an error occured or false.
2176      *
2177      * @access  public
2178      * @since   2.1.1
2179      */
2180     function getNestedTransactionError()
2181     {
2182         return $this->has_transaction_error;
2183     }
2184
2185     // }}}
2186     // {{{ connect()
2187
2188     /**
2189      * Connect to the database
2190      *
2191      * @return true on success, MDB2 Error Object on failure
2192      */
2193     function connect()
2194     {
2195         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2196             'method not implemented', __FUNCTION__);
2197     }
2198
2199     // }}}
2200     // {{{ databaseExists()
2201
2202     /**
2203      * check if given database name is exists?
2204      *
2205      * @param string $name    name of the database that should be checked
2206      *
2207      * @return mixed true/false on success, a MDB2 error on failure
2208      * @access public
2209      */
2210     function databaseExists($name)
2211     {
2212         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2213             'method not implemented', __FUNCTION__);
2214     }
2215
2216     // }}}
2217     // {{{ setCharset($charset, $connection = null)
2218
2219     /**
2220      * Set the charset on the current connection
2221      *
2222      * @param string    charset
2223      * @param resource  connection handle
2224      *
2225      * @return true on success, MDB2 Error Object on failure
2226      */
2227     function setCharset($charset, $connection = null)
2228     {
2229         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2230             'method not implemented', __FUNCTION__);
2231     }
2232
2233     // }}}
2234     // {{{ function disconnect($force = true)
2235
2236     /**
2237      * Log out and disconnect from the database.
2238      *
2273d4 2239      * @param boolean $force whether the disconnect should be forced even if the
A 2240      *                       connection is opened persistently
200b16 2241      *
2273d4 2242      * @return mixed true on success, false if not connected and error object on error
200b16 2243      *
A 2244      * @access  public
2245      */
2246     function disconnect($force = true)
2247     {
2248         $this->connection = 0;
2249         $this->connected_dsn = array();
2250         $this->connected_database_name = '';
2251         $this->opened_persistent = null;
2252         $this->connected_server_info = '';
2253         $this->in_transaction = null;
2254         $this->nested_transaction_counter = null;
2255         return MDB2_OK;
2256     }
2257
2258     // }}}
2259     // {{{ function setDatabase($name)
2260
2261     /**
2262      * Select a different database
2263      *
2264      * @param   string  name of the database that should be selected
2265      *
2266      * @return  string  name of the database previously connected to
2267      *
2268      * @access  public
2269      */
2270     function setDatabase($name)
2271     {
2272         $previous_database_name = (isset($this->database_name)) ? $this->database_name : '';
2273         $this->database_name = $name;
2274         if (!empty($this->connected_database_name) && ($this->connected_database_name != $this->database_name)) {
2275             $this->disconnect(false);
2276         }
2277         return $previous_database_name;
2278     }
2279
2280     // }}}
2281     // {{{ function getDatabase()
2282
2283     /**
2284      * Get the current database
2285      *
2286      * @return  string  name of the database
2287      *
2288      * @access  public
2289      */
2290     function getDatabase()
2291     {
2292         return $this->database_name;
2293     }
2294
2295     // }}}
2296     // {{{ function setDSN($dsn)
2297
2298     /**
2299      * set the DSN
2300      *
2301      * @param   mixed   DSN string or array
2302      *
2303      * @return  MDB2_OK
2304      *
2305      * @access  public
2306      */
2307     function setDSN($dsn)
2308     {
2309         $dsn_default = $GLOBALS['_MDB2_dsninfo_default'];
2310         $dsn = MDB2::parseDSN($dsn);
2311         if (array_key_exists('database', $dsn)) {
2312             $this->database_name = $dsn['database'];
2313             unset($dsn['database']);
2314         }
2315         $this->dsn = array_merge($dsn_default, $dsn);
2316         return $this->disconnect(false);
2317     }
2318
2319     // }}}
2320     // {{{ function getDSN($type = 'string', $hidepw = false)
2321
2322     /**
2323      * return the DSN as a string
2324      *
2325      * @param   string  format to return ("array", "string")
2326      * @param   string  string to hide the password with
2327      *
2328      * @return  mixed   DSN in the chosen type
2329      *
2330      * @access  public
2331      */
2332     function getDSN($type = 'string', $hidepw = false)
2333     {
2334         $dsn = array_merge($GLOBALS['_MDB2_dsninfo_default'], $this->dsn);
2335         $dsn['phptype'] = $this->phptype;
2336         $dsn['database'] = $this->database_name;
2337         if ($hidepw) {
2338             $dsn['password'] = $hidepw;
2339         }
2340         switch ($type) {
2341         // expand to include all possible options
2342         case 'string':
2343            $dsn = $dsn['phptype'].
2344                ($dsn['dbsyntax'] ? ('('.$dsn['dbsyntax'].')') : '').
2345                '://'.$dsn['username'].':'.
2346                 $dsn['password'].'@'.$dsn['hostspec'].
2347                 ($dsn['port'] ? (':'.$dsn['port']) : '').
2348                 '/'.$dsn['database'];
2349             break;
2350         case 'array':
2351         default:
2352             break;
2353         }
2354         return $dsn;
2273d4 2355     }
A 2356
2357     // }}}
2358     // {{{ _isNewLinkSet()
2359
2360     /**
2361      * Check if the 'new_link' option is set
2362      *
2363      * @return boolean
2364      *
2365      * @access protected
2366      */
2367     function _isNewLinkSet()
2368     {
2369         return (isset($this->dsn['new_link'])
2370             && ($this->dsn['new_link'] === true
2371              || (is_string($this->dsn['new_link']) && preg_match('/^true$/i', $this->dsn['new_link']))
2372              || (is_numeric($this->dsn['new_link']) && 0 != (int)$this->dsn['new_link'])
2373             )
2374         );
200b16 2375     }
A 2376
2377     // }}}
2378     // {{{ function &standaloneQuery($query, $types = null, $is_manip = false)
2379
2380    /**
2381      * execute a query as database administrator
2382      *
2383      * @param   string  the SQL query
2384      * @param   mixed   array that contains the types of the columns in
2385      *                        the result set
2386      * @param   bool    if the query is a manipulation query
2387      *
2388      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
2389      *
2390      * @access  public
2391      */
7244b4 2392     function standaloneQuery($query, $types = null, $is_manip = false)
200b16 2393     {
A 2394         $offset = $this->offset;
2395         $limit = $this->limit;
2396         $this->offset = $this->limit = 0;
2397         $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
2398
2399         $connection = $this->getConnection();
2400         if (PEAR::isError($connection)) {
2401             return $connection;
2402         }
2403
7244b4 2404         $result = $this->_doQuery($query, $is_manip, $connection, false);
200b16 2405         if (PEAR::isError($result)) {
A 2406             return $result;
2407         }
2408
2409         if ($is_manip) {
2410             $affected_rows =  $this->_affectedRows($connection, $result);
2411             return $affected_rows;
2412         }
7244b4 2413         $result = $this->_wrapResult($result, $types, true, false, $limit, $offset);
200b16 2414         return $result;
A 2415     }
2416
2417     // }}}
2418     // {{{ function _modifyQuery($query, $is_manip, $limit, $offset)
2419
2420     /**
2421      * Changes a query string for various DBMS specific reasons
2422      *
2423      * @param   string  query to modify
2424      * @param   bool    if it is a DML query
2425      * @param   int  limit the number of rows
2426      * @param   int  start reading from given offset
2427      *
2428      * @return  string  modified query
2429      *
2430      * @access  protected
2431      */
2432     function _modifyQuery($query, $is_manip, $limit, $offset)
2433     {
2434         return $query;
2435     }
2436
2437     // }}}
2438     // {{{ function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
2439
2440     /**
2441      * Execute a query
2442      * @param   string  query
2443      * @param   bool    if the query is a manipulation query
2444      * @param   resource connection handle
2445      * @param   string  database name
2446      *
2447      * @return  result or error object
2448      *
2449      * @access  protected
2450      */
7244b4 2451     function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)
200b16 2452     {
A 2453         $this->last_query = $query;
2454         $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
2455         if ($result) {
2456             if (PEAR::isError($result)) {
2457                 return $result;
2458             }
2459             $query = $result;
2460         }
7244b4 2461         $err = $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
200b16 2462             'method not implemented', __FUNCTION__);
A 2463         return $err;
2464     }
2465
2466     // }}}
2467     // {{{ function _affectedRows($connection, $result = null)
2468
2469     /**
2470      * Returns the number of rows affected
2471      *
2472      * @param   resource result handle
2473      * @param   resource connection handle
2474      *
2475      * @return  mixed   MDB2 Error Object or the number of rows affected
2476      *
2477      * @access  private
2478      */
2479     function _affectedRows($connection, $result = null)
2480     {
2481         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2482             'method not implemented', __FUNCTION__);
2483     }
2484
2485     // }}}
2486     // {{{ function &exec($query)
2487
2488     /**
2489      * Execute a manipulation query to the database and return the number of affected rows
2490      *
2491      * @param   string  the SQL query
2492      *
2493      * @return  mixed   number of affected rows on success, a MDB2 error on failure
2494      *
2495      * @access  public
2496      */
7244b4 2497     function exec($query)
200b16 2498     {
A 2499         $offset = $this->offset;
2500         $limit = $this->limit;
2501         $this->offset = $this->limit = 0;
2502         $query = $this->_modifyQuery($query, true, $limit, $offset);
2503
2504         $connection = $this->getConnection();
2505         if (PEAR::isError($connection)) {
2506             return $connection;
2507         }
2508
7244b4 2509         $result = $this->_doQuery($query, true, $connection, $this->database_name);
200b16 2510         if (PEAR::isError($result)) {
A 2511             return $result;
2512         }
2513
2514         $affectedRows = $this->_affectedRows($connection, $result);
2515         return $affectedRows;
2516     }
2517
2518     // }}}
2519     // {{{ function &query($query, $types = null, $result_class = true, $result_wrap_class = false)
2520
2521     /**
2522      * Send a query to the database and return any results
2523      *
2524      * @param   string  the SQL query
2525      * @param   mixed   array that contains the types of the columns in
2526      *                        the result set
2527      * @param   mixed   string which specifies which result class to use
2528      * @param   mixed   string which specifies which class to wrap results in
2529      *
2530      * @return mixed   an MDB2_Result handle on success, a MDB2 error on failure
2531      *
2532      * @access  public
2533      */
7244b4 2534     function query($query, $types = null, $result_class = true, $result_wrap_class = false)
200b16 2535     {
A 2536         $offset = $this->offset;
2537         $limit = $this->limit;
2538         $this->offset = $this->limit = 0;
2539         $query = $this->_modifyQuery($query, false, $limit, $offset);
2540
2541         $connection = $this->getConnection();
2542         if (PEAR::isError($connection)) {
2543             return $connection;
2544         }
2545
7244b4 2546         $result = $this->_doQuery($query, false, $connection, $this->database_name);
200b16 2547         if (PEAR::isError($result)) {
A 2548             return $result;
2549         }
2550
7244b4 2551         $result = $this->_wrapResult($result, $types, $result_class, $result_wrap_class, $limit, $offset);
200b16 2552         return $result;
A 2553     }
2554
2555     // }}}
7244b4 2556     // {{{ function _wrapResult($result_resource, $types = array(), $result_class = true, $result_wrap_class = false, $limit = null, $offset = null)
200b16 2557
A 2558     /**
2559      * wrap a result set into the correct class
2560      *
2561      * @param   resource result handle
2562      * @param   mixed   array that contains the types of the columns in
2563      *                        the result set
2564      * @param   mixed   string which specifies which result class to use
2565      * @param   mixed   string which specifies which class to wrap results in
2566      * @param   string  number of rows to select
2567      * @param   string  first row to select
2568      *
2569      * @return mixed   an MDB2_Result, a MDB2 error on failure
2570      *
2571      * @access  protected
2572      */
7244b4 2573     function _wrapResult($result_resource, $types = array(), $result_class = true,
200b16 2574         $result_wrap_class = false, $limit = null, $offset = null)
A 2575     {
2576         if ($types === true) {
2577             if ($this->supports('result_introspection')) {
2578                 $this->loadModule('Reverse', null, true);
0f6e0e 2579                 $tableInfo = $this->reverse->tableInfo($result_resource);
200b16 2580                 if (PEAR::isError($tableInfo)) {
A 2581                     return $tableInfo;
2582                 }
2583                 $types = array();
2584                 foreach ($tableInfo as $field) {
2585                     $types[] = $field['mdb2type'];
2586                 }
2587             } else {
2588                 $types = null;
2589             }
2590         }
2591
2592         if ($result_class === true) {
2593             $result_class = $this->options['result_buffering']
2594                 ? $this->options['buffered_result_class'] : $this->options['result_class'];
2595         }
2596
2597         if ($result_class) {
2598             $class_name = sprintf($result_class, $this->phptype);
2599             if (!MDB2::classExists($class_name)) {
7244b4 2600                 $err = $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
200b16 2601                     'result class does not exist '.$class_name, __FUNCTION__);
A 2602                 return $err;
2603             }
0f6e0e 2604             $result = new $class_name($this, $result_resource, $limit, $offset);
200b16 2605             if (!MDB2::isResultCommon($result)) {
7244b4 2606                 $err = $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
200b16 2607                     'result class is not extended from MDB2_Result_Common', __FUNCTION__);
A 2608                 return $err;
2609             }
2610             if (!empty($types)) {
2611                 $err = $result->setResultTypes($types);
2612                 if (PEAR::isError($err)) {
2613                     $result->free();
2614                     return $err;
2615                 }
2616             }
2617         }
2618         if ($result_wrap_class === true) {
2619             $result_wrap_class = $this->options['result_wrap_class'];
2620         }
2621         if ($result_wrap_class) {
2622             if (!MDB2::classExists($result_wrap_class)) {
7244b4 2623                 $err = $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
200b16 2624                     'result wrap class does not exist '.$result_wrap_class, __FUNCTION__);
A 2625                 return $err;
2626             }
2273d4 2627             $result = new $result_wrap_class($result_resource, $this->fetchmode);
200b16 2628         }
A 2629         return $result;
2630     }
2631
2632     // }}}
2633     // {{{ function getServerVersion($native = false)
2634
2635     /**
2636      * return version information about the server
2637      *
2638      * @param   bool    determines if the raw version string should be returned
2639      *
2640      * @return  mixed   array with version information or row string
2641      *
2642      * @access  public
2643      */
2644     function getServerVersion($native = false)
2645     {
2646         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2647             'method not implemented', __FUNCTION__);
2648     }
2649
2650     // }}}
2651     // {{{ function setLimit($limit, $offset = null)
2652
2653     /**
2654      * set the range of the next query
2655      *
2656      * @param   string  number of rows to select
2657      * @param   string  first row to select
2658      *
2659      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
2660      *
2661      * @access  public
2662      */
2663     function setLimit($limit, $offset = null)
2664     {
2665         if (!$this->supports('limit_queries')) {
2666             return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2667                 'limit is not supported by this driver', __FUNCTION__);
2668         }
2669         $limit = (int)$limit;
2670         if ($limit < 0) {
2671             return $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
2672                 'it was not specified a valid selected range row limit', __FUNCTION__);
2673         }
2674         $this->limit = $limit;
2273d4 2675         if (null !== $offset) {
200b16 2676             $offset = (int)$offset;
A 2677             if ($offset < 0) {
2678                 return $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
2679                     'it was not specified a valid first selected range row', __FUNCTION__);
2680             }
2681             $this->offset = $offset;
2682         }
2683         return MDB2_OK;
2684     }
2685
2686     // }}}
2687     // {{{ function subSelect($query, $type = false)
2688
2689     /**
2690      * simple subselect emulation: leaves the query untouched for all RDBMS
2691      * that support subselects
2692      *
2693      * @param   string  the SQL query for the subselect that may only
2694      *                      return a column
2695      * @param   string  determines type of the field
2696      *
2697      * @return  string  the query
2698      *
2699      * @access  public
2700      */
2701     function subSelect($query, $type = false)
2702     {
2703         if ($this->supports('sub_selects') === true) {
2704             return $query;
2705         }
2706
2707         if (!$this->supports('sub_selects')) {
2708             return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2709                 'method not implemented', __FUNCTION__);
2710         }
2711
2712         $col = $this->queryCol($query, $type);
2713         if (PEAR::isError($col)) {
2714             return $col;
2715         }
2716         if (!is_array($col) || count($col) == 0) {
2717             return 'NULL';
2718         }
2719         if ($type) {
2720             $this->loadModule('Datatype', null, true);
2721             return $this->datatype->implodeArray($col, $type);
2722         }
2723         return implode(', ', $col);
2724     }
2725
2726     // }}}
2727     // {{{ function replace($table, $fields)
2728
2729     /**
2730      * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
2731      * query, except that if there is already a row in the table with the same
2273d4 2732      * key field values, the old row is deleted before the new row is inserted.
200b16 2733      *
A 2734      * The REPLACE type of query does not make part of the SQL standards. Since
2735      * practically only MySQL and SQLite implement it natively, this type of
2736      * query isemulated through this method for other DBMS using standard types
2737      * of queries inside a transaction to assure the atomicity of the operation.
2738      *
2739      * @param   string  name of the table on which the REPLACE query will
2740      *       be executed.
2741      * @param   array   associative array   that describes the fields and the
2742      *       values that will be inserted or updated in the specified table. The
2743      *       indexes of the array are the names of all the fields of the table.
2744      *       The values of the array are also associative arrays that describe
2745      *       the values and other properties of the table fields.
2746      *
2747      *       Here follows a list of field properties that need to be specified:
2748      *
2749      *       value
2750      *           Value to be assigned to the specified field. This value may be
2751      *           of specified in database independent type format as this
2752      *           function can perform the necessary datatype conversions.
2753      *
2754      *           Default: this property is required unless the Null property is
2755      *           set to 1.
2756      *
2757      *       type
2758      *           Name of the type of the field. Currently, all types MDB2
2759      *           are supported except for clob and blob.
2760      *
2761      *           Default: no type conversion
2762      *
2763      *       null
2764      *           bool    property that indicates that the value for this field
2765      *           should be set to null.
2766      *
2767      *           The default value for fields missing in INSERT queries may be
2768      *           specified the definition of a table. Often, the default value
2769      *           is already null, but since the REPLACE may be emulated using
2770      *           an UPDATE query, make sure that all fields of the table are
2771      *           listed in this function argument array.
2772      *
2773      *           Default: 0
2774      *
2775      *       key
2776      *           bool    property that indicates that this field should be
2777      *           handled as a primary key or at least as part of the compound
2778      *           unique index of the table that will determine the row that will
2779      *           updated if it exists or inserted a new row otherwise.
2780      *
2781      *           This function will fail if no key field is specified or if the
2782      *           value of a key field is set to null because fields that are
2783      *           part of unique index they may not be null.
2784      *
2785      *           Default: 0
2786      *
2787      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
2788      *
2789      * @access  public
2790      */
2791     function replace($table, $fields)
2792     {
2793         if (!$this->supports('replace')) {
2794             return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
2795                 'replace query is not supported', __FUNCTION__);
2796         }
2797         $count = count($fields);
2798         $condition = $values = array();
2799         for ($colnum = 0, reset($fields); $colnum < $count; next($fields), $colnum++) {
2800             $name = key($fields);
2801             if (isset($fields[$name]['null']) && $fields[$name]['null']) {
2802                 $value = 'NULL';
2803             } else {
2804                 $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
2805                 $value = $this->quote($fields[$name]['value'], $type);
2806             }
2807             $values[$name] = $value;
2808             if (isset($fields[$name]['key']) && $fields[$name]['key']) {
2809                 if ($value === 'NULL') {
2810                     return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
2811                         'key value '.$name.' may not be NULL', __FUNCTION__);
2812                 }
2813                 $condition[] = $this->quoteIdentifier($name, true) . '=' . $value;
2814             }
2815         }
2816         if (empty($condition)) {
2817             return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
2818                 'not specified which fields are keys', __FUNCTION__);
2819         }
2820
2821         $result = null;
2822         $in_transaction = $this->in_transaction;
2823         if (!$in_transaction && PEAR::isError($result = $this->beginTransaction())) {
2824             return $result;
2825         }
2826
2827         $connection = $this->getConnection();
2828         if (PEAR::isError($connection)) {
2829             return $connection;
2830         }
2831
2832         $condition = ' WHERE '.implode(' AND ', $condition);
2833         $query = 'DELETE FROM ' . $this->quoteIdentifier($table, true) . $condition;
7244b4 2834         $result = $this->_doQuery($query, true, $connection);
200b16 2835         if (!PEAR::isError($result)) {
A 2836             $affected_rows = $this->_affectedRows($connection, $result);
2837             $insert = '';
2838             foreach ($values as $key => $value) {
2839                 $insert .= ($insert?', ':'') . $this->quoteIdentifier($key, true);
2840             }
2841             $values = implode(', ', $values);
2842             $query = 'INSERT INTO '. $this->quoteIdentifier($table, true) . "($insert) VALUES ($values)";
7244b4 2843             $result = $this->_doQuery($query, true, $connection);
200b16 2844             if (!PEAR::isError($result)) {
A 2845                 $affected_rows += $this->_affectedRows($connection, $result);;
2846             }
2847         }
2848
2849         if (!$in_transaction) {
2850             if (PEAR::isError($result)) {
2851                 $this->rollback();
2852             } else {
2853                 $result = $this->commit();
2854             }
2855         }
2856
2857         if (PEAR::isError($result)) {
2858             return $result;
2859         }
2860
2861         return $affected_rows;
2862     }
2863
2864     // }}}
2865     // {{{ function &prepare($query, $types = null, $result_types = null, $lobs = array())
2866
2867     /**
2868      * Prepares a query for multiple execution with execute().
2869      * With some database backends, this is emulated.
2870      * prepare() requires a generic query as string like
2871      * 'INSERT INTO numbers VALUES(?,?)' or
2872      * 'INSERT INTO numbers VALUES(:foo,:bar)'.
2873      * The ? and :name and are placeholders which can be set using
2874      * bindParam() and the query can be sent off using the execute() method.
2875      * The allowed format for :name can be set with the 'bindname_format' option.
2876      *
2877      * @param   string  the query to prepare
2878      * @param   mixed   array that contains the types of the placeholders
2879      * @param   mixed   array that contains the types of the columns in
2880      *                        the result set or MDB2_PREPARE_RESULT, if set to
2881      *                        MDB2_PREPARE_MANIP the query is handled as a manipulation query
2882      * @param   mixed   key (field) value (parameter) pair for all lob placeholders
2883      *
2884      * @return  mixed   resource handle for the prepared query on success, 
2885      *                  a MDB2 error on failure
2886      *
2887      * @access  public
2888      * @see     bindParam, execute
2889      */
7244b4 2890     function prepare($query, $types = null, $result_types = null, $lobs = array())
200b16 2891     {
A 2892         $is_manip = ($result_types === MDB2_PREPARE_MANIP);
2893         $offset = $this->offset;
2894         $limit = $this->limit;
2895         $this->offset = $this->limit = 0;
2896         $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
2897         if ($result) {
2898             if (PEAR::isError($result)) {
2899                 return $result;
2900             }
2901             $query = $result;
2902         }
2903         $placeholder_type_guess = $placeholder_type = null;
2273d4 2904         $question  = '?';
A 2905         $colon     = ':';
200b16 2906         $positions = array();
2273d4 2907         $position  = 0;
200b16 2908         while ($position < strlen($query)) {
A 2909             $q_position = strpos($query, $question, $position);
2910             $c_position = strpos($query, $colon, $position);
2911             if ($q_position && $c_position) {
2912                 $p_position = min($q_position, $c_position);
2913             } elseif ($q_position) {
2914                 $p_position = $q_position;
2915             } elseif ($c_position) {
2916                 $p_position = $c_position;
2917             } else {
2918                 break;
2919             }
2273d4 2920             if (null === $placeholder_type) {
200b16 2921                 $placeholder_type_guess = $query[$p_position];
A 2922             }
2923
2924             $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
2925             if (PEAR::isError($new_pos)) {
2926                 return $new_pos;
2927             }
2928             if ($new_pos != $position) {
2929                 $position = $new_pos;
2930                 continue; //evaluate again starting from the new position
2931             }
2932
2933             if ($query[$position] == $placeholder_type_guess) {
2273d4 2934                 if (null === $placeholder_type) {
200b16 2935                     $placeholder_type = $query[$p_position];
A 2936                     $question = $colon = $placeholder_type;
2937                     if (!empty($types) && is_array($types)) {
2938                         if ($placeholder_type == ':') {
2939                             if (is_int(key($types))) {
2940                                 $types_tmp = $types;
2941                                 $types = array();
2942                                 $count = -1;
2943                             }
2944                         } else {
2945                             $types = array_values($types);
2946                         }
2947                     }
2948                 }
2949                 if ($placeholder_type == ':') {
2950                     $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
2951                     $parameter = preg_replace($regexp, '\\1', $query);
2952                     if ($parameter === '') {
7244b4 2953                         $err = $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
200b16 2954                             'named parameter name must match "bindname_format" option', __FUNCTION__);
A 2955                         return $err;
2956                     }
2957                     $positions[$p_position] = $parameter;
2958                     $query = substr_replace($query, '?', $position, strlen($parameter)+1);
2959                     // use parameter name in type array
2960                     if (isset($count) && isset($types_tmp[++$count])) {
2961                         $types[$parameter] = $types_tmp[$count];
2962                     }
2963                 } else {
2964                     $positions[$p_position] = count($positions);
2965                 }
2966                 $position = $p_position + 1;
2967             } else {
2968                 $position = $p_position;
2969             }
2970         }
2971         $class_name = 'MDB2_Statement_'.$this->phptype;
2972         $statement = null;
2973         $obj = new $class_name($this, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
2974         $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
2975         return $obj;
2976     }
2977
2978     // }}}
2979     // {{{ function _skipDelimitedStrings($query, $position, $p_position)
2980     
2981     /**
2982      * Utility method, used by prepare() to avoid replacing placeholders within delimited strings.
2983      * Check if the placeholder is contained within a delimited string.
2984      * If so, skip it and advance the position, otherwise return the current position,
2985      * which is valid
2986      *
2987      * @param string $query
2988      * @param integer $position current string cursor position
2989      * @param integer $p_position placeholder position
2990      *
2991      * @return mixed integer $new_position on success
2992      *               MDB2_Error on failure
2993      *
2994      * @access  protected
2995      */
2996     function _skipDelimitedStrings($query, $position, $p_position)
2997     {
7244b4 2998         $ignores = array();
A 2999         $ignores[] = $this->string_quoting;
2273d4 3000         $ignores[] = $this->identifier_quoting;
200b16 3001         $ignores = array_merge($ignores, $this->sql_comments);
A 3002         
3003         foreach ($ignores as $ignore) {
3004             if (!empty($ignore['start'])) {
3005                 if (is_int($start_quote = strpos($query, $ignore['start'], $position)) && $start_quote < $p_position) {
3006                     $end_quote = $start_quote;
3007                     do {
3008                         if (!is_int($end_quote = strpos($query, $ignore['end'], $end_quote + 1))) {
3009                             if ($ignore['end'] === "\n") {
3010                                 $end_quote = strlen($query) - 1;
3011                             } else {
7244b4 3012                                 $err = $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
200b16 3013                                     'query with an unterminated text string specified', __FUNCTION__);
A 3014                                 return $err;
3015                             }
3016                         }
3017                     } while ($ignore['escape']
2273d4 3018                         && $end_quote-1 != $start_quote
A 3019                         && $query[($end_quote - 1)] == $ignore['escape']
3020                         && (   $ignore['escape_pattern'] !== $ignore['escape']
3021                             || $query[($end_quote - 2)] != $ignore['escape'])
3022                     );
3023
200b16 3024                     $position = $end_quote + 1;
A 3025                     return $position;
3026                 }
3027             }
3028         }
3029         return $position;
3030     }
3031     
3032     // }}}
3033     // {{{ function quote($value, $type = null, $quote = true)
3034
3035     /**
3036      * Convert a text value into a DBMS specific format that is suitable to
3037      * compose query statements.
3038      *
3039      * @param   string  text string value that is intended to be converted.
3040      * @param   string  type to which the value should be converted to
3041      * @param   bool    quote
3042      * @param   bool    escape wildcards
3043      *
3044      * @return  string  text string that represents the given argument value in
3045      *       a DBMS specific format.
3046      *
3047      * @access  public
3048      */
3049     function quote($value, $type = null, $quote = true, $escape_wildcards = false)
3050     {
3051         $result = $this->loadModule('Datatype', null, true);
3052         if (PEAR::isError($result)) {
3053             return $result;
3054         }
3055
3056         return $this->datatype->quote($value, $type, $quote, $escape_wildcards);
3057     }
3058
3059     // }}}
3060     // {{{ function getDeclaration($type, $name, $field)
3061
3062     /**
3063      * Obtain DBMS specific SQL code portion needed to declare
3064      * of the given type
3065      *
3066      * @param   string  type to which the value should be converted to
3067      * @param   string  name the field to be declared.
3068      * @param   string  definition of the field
3069      *
3070      * @return  string  DBMS specific SQL code portion that should be used to
3071      *                 declare the specified field.
3072      *
3073      * @access  public
3074      */
3075     function getDeclaration($type, $name, $field)
3076     {
3077         $result = $this->loadModule('Datatype', null, true);
3078         if (PEAR::isError($result)) {
3079             return $result;
3080         }
3081         return $this->datatype->getDeclaration($type, $name, $field);
3082     }
3083
3084     // }}}
3085     // {{{ function compareDefinition($current, $previous)
3086
3087     /**
3088      * Obtain an array of changes that may need to applied
3089      *
3090      * @param   array   new definition
3091      * @param   array   old definition
3092      *
3093      * @return  array   containing all changes that will need to be applied
3094      *
3095      * @access  public
3096      */
3097     function compareDefinition($current, $previous)
3098     {
3099         $result = $this->loadModule('Datatype', null, true);
3100         if (PEAR::isError($result)) {
3101             return $result;
3102         }
3103         return $this->datatype->compareDefinition($current, $previous);
3104     }
3105
3106     // }}}
3107     // {{{ function supports($feature)
3108
3109     /**
3110      * Tell whether a DB implementation or its backend extension
3111      * supports a given feature.
3112      *
3113      * @param   string  name of the feature (see the MDB2 class doc)
3114      *
3115      * @return  bool|string if this DB implementation supports a given feature
3116      *                      false means no, true means native,
3117      *                      'emulated' means emulated
3118      *
3119      * @access  public
3120      */
3121     function supports($feature)
3122     {
3123         if (array_key_exists($feature, $this->supported)) {
3124             return $this->supported[$feature];
3125         }
3126         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
3127             "unknown support feature $feature", __FUNCTION__);
3128     }
3129
3130     // }}}
3131     // {{{ function getSequenceName($sqn)
3132
3133     /**
3134      * adds sequence name formatting to a sequence name
3135      *
3136      * @param   string  name of the sequence
3137      *
3138      * @return  string  formatted sequence name
3139      *
3140      * @access  public
3141      */
3142     function getSequenceName($sqn)
3143     {
3144         return sprintf($this->options['seqname_format'],
3145             preg_replace('/[^a-z0-9_\-\$.]/i', '_', $sqn));
3146     }
3147
3148     // }}}
3149     // {{{ function getIndexName($idx)
3150
3151     /**
3152      * adds index name formatting to a index name
3153      *
3154      * @param   string  name of the index
3155      *
3156      * @return  string  formatted index name
3157      *
3158      * @access  public
3159      */
3160     function getIndexName($idx)
3161     {
3162         return sprintf($this->options['idxname_format'],
2273d4 3163             preg_replace('/[^a-z0-9_\-\$.]/i', '_', $idx));
200b16 3164     }
A 3165
3166     // }}}
3167     // {{{ function nextID($seq_name, $ondemand = true)
3168
3169     /**
3170      * Returns the next free id of a sequence
3171      *
3172      * @param   string  name of the sequence
3173      * @param   bool    when true missing sequences are automatic created
3174      *
3175      * @return  mixed   MDB2 Error Object or id
3176      *
3177      * @access  public
3178      */
3179     function nextID($seq_name, $ondemand = true)
3180     {
3181         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
3182             'method not implemented', __FUNCTION__);
3183     }
3184
3185     // }}}
3186     // {{{ function lastInsertID($table = null, $field = null)
3187
3188     /**
3189      * Returns the autoincrement ID if supported or $id or fetches the current
3190      * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
3191      *
3192      * @param   string  name of the table into which a new row was inserted
3193      * @param   string  name of the field into which a new row was inserted
3194      *
3195      * @return  mixed   MDB2 Error Object or id
3196      *
3197      * @access  public
3198      */
3199     function lastInsertID($table = null, $field = null)
3200     {
3201         return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
3202             'method not implemented', __FUNCTION__);
3203     }
3204
3205     // }}}
3206     // {{{ function currID($seq_name)
3207
3208     /**
3209      * Returns the current id of a sequence
3210      *
3211      * @param   string  name of the sequence
3212      *
3213      * @return  mixed   MDB2 Error Object or id
3214      *
3215      * @access  public
3216      */
3217     function currID($seq_name)
3218     {
3219         $this->warnings[] = 'database does not support getting current
3220             sequence value, the sequence value was incremented';
3221         return $this->nextID($seq_name);
3222     }
3223
3224     // }}}
3225     // {{{ function queryOne($query, $type = null, $colnum = 0)
3226
3227     /**
3228      * Execute the specified query, fetch the value from the first column of
3229      * the first row of the result set and then frees
3230      * the result set.
3231      *
2273d4 3232      * @param string $query  the SELECT query statement to be executed.
A 3233      * @param string $type   optional argument that specifies the expected
3234      *                       datatype of the result set field, so that an eventual
3235      *                       conversion may be performed. The default datatype is
3236      *                       text, meaning that no conversion is performed
3237      * @param mixed  $colnum the column number (or name) to fetch
200b16 3238      *
A 3239      * @return  mixed   MDB2_OK or field value on success, a MDB2 error on failure
3240      *
3241      * @access  public
3242      */
3243     function queryOne($query, $type = null, $colnum = 0)
3244     {
3245         $result = $this->query($query, $type);
3246         if (!MDB2::isResultCommon($result)) {
3247             return $result;
3248         }
3249
3250         $one = $result->fetchOne($colnum);
3251         $result->free();
3252         return $one;
3253     }
3254
3255     // }}}
3256     // {{{ function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
3257
3258     /**
3259      * Execute the specified query, fetch the values from the first
3260      * row of the result set into an array and then frees
3261      * the result set.
3262      *
3263      * @param   string  the SELECT query statement to be executed.
3264      * @param   array   optional array argument that specifies a list of
3265      *       expected datatypes of the result set columns, so that the eventual
3266      *       conversions may be performed. The default list of datatypes is
3267      *       empty, meaning that no conversion is performed.
3268      * @param   int     how the array data should be indexed
3269      *
3270      * @return  mixed   MDB2_OK or data array on success, a MDB2 error on failure
3271      *
3272      * @access  public
3273      */
3274     function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
3275     {
3276         $result = $this->query($query, $types);
3277         if (!MDB2::isResultCommon($result)) {
3278             return $result;
3279         }
3280
3281         $row = $result->fetchRow($fetchmode);
3282         $result->free();
3283         return $row;
3284     }
3285
3286     // }}}
3287     // {{{ function queryCol($query, $type = null, $colnum = 0)
3288
3289     /**
3290      * Execute the specified query, fetch the value from the first column of
3291      * each row of the result set into an array and then frees the result set.
3292      *
2273d4 3293      * @param string $query  the SELECT query statement to be executed.
A 3294      * @param string $type   optional argument that specifies the expected
3295      *                       datatype of the result set field, so that an eventual
3296      *                       conversion may be performed. The default datatype is text,
3297      *                       meaning that no conversion is performed
3298      * @param mixed  $colnum the column number (or name) to fetch
200b16 3299      *
A 3300      * @return  mixed   MDB2_OK or data array on success, a MDB2 error on failure
3301      * @access  public
3302      */
3303     function queryCol($query, $type = null, $colnum = 0)
3304     {
3305         $result = $this->query($query, $type);
3306         if (!MDB2::isResultCommon($result)) {
3307             return $result;
3308         }
3309
3310         $col = $result->fetchCol($colnum);
3311         $result->free();
3312         return $col;
3313     }
3314
3315     // }}}
3316     // {{{ function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
3317
3318     /**
3319      * Execute the specified query, fetch all the rows of the result set into
3320      * a two dimensional array and then frees the result set.
3321      *
3322      * @param   string  the SELECT query statement to be executed.
3323      * @param   array   optional array argument that specifies a list of
3324      *       expected datatypes of the result set columns, so that the eventual
3325      *       conversions may be performed. The default list of datatypes is
3326      *       empty, meaning that no conversion is performed.
3327      * @param   int     how the array data should be indexed
3328      * @param   bool    if set to true, the $all will have the first
3329      *       column as its first dimension
3330      * @param   bool    used only when the query returns exactly
3331      *       two columns. If true, the values of the returned array will be
3332      *       one-element arrays instead of scalars.
3333      * @param   bool    if true, the values of the returned array is
3334      *       wrapped in another array.  If the same key value (in the first
3335      *       column) repeats itself, the values will be appended to this array
3336      *       instead of overwriting the existing values.
3337      *
3338      * @return  mixed   MDB2_OK or data array on success, a MDB2 error on failure
3339      *
3340      * @access  public
3341      */
3342     function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT,
3343         $rekey = false, $force_array = false, $group = false)
3344     {
3345         $result = $this->query($query, $types);
3346         if (!MDB2::isResultCommon($result)) {
3347             return $result;
3348         }
3349
3350         $all = $result->fetchAll($fetchmode, $rekey, $force_array, $group);
3351         $result->free();
3352         return $all;
3353     }
3354
3355     // }}}
3356 }
3357
3358 // }}}
3359 // {{{ class MDB2_Result
3360
3361 /**
3362  * The dummy class that all user space result classes should extend from
3363  *
3364  * @package     MDB2
3365  * @category    Database
3366  * @author      Lukas Smith <smith@pooteeweet.org>
3367  */
3368 class MDB2_Result
3369 {
3370 }
3371
3372 // }}}
3373 // {{{ class MDB2_Result_Common extends MDB2_Result
3374
3375 /**
3376  * The common result class for MDB2 result objects
3377  *
3378  * @package     MDB2
3379  * @category    Database
3380  * @author      Lukas Smith <smith@pooteeweet.org>
3381  */
3382 class MDB2_Result_Common extends MDB2_Result
3383 {
3384     // {{{ Variables (Properties)
3385
3386     var $db;
3387     var $result;
3388     var $rownum = -1;
3389     var $types = array();
3390     var $values = array();
3391     var $offset;
3392     var $offset_count = 0;
3393     var $limit;
3394     var $column_names;
3395
3396     // }}}
7244b4 3397     // {{{ constructor: function __construct($db, &$result, $limit = 0, $offset = 0)
200b16 3398
A 3399     /**
3400      * Constructor
3401      */
7244b4 3402     function __construct($db, &$result, $limit = 0, $offset = 0)
200b16 3403     {
7244b4 3404         $this->db = $db;
A 3405         $this->result = $result;
200b16 3406         $this->offset = $offset;
A 3407         $this->limit = max(0, $limit - 1);
3408     }
3409
3410     // }}}
3411     // {{{ function setResultTypes($types)
3412
3413     /**
3414      * Define the list of types to be associated with the columns of a given
3415      * result set.
3416      *
3417      * This function may be called before invoking fetchRow(), fetchOne(),
3418      * fetchCol() and fetchAll() so that the necessary data type
3419      * conversions are performed on the data to be retrieved by them. If this
3420      * function is not called, the type of all result set columns is assumed
3421      * to be text, thus leading to not perform any conversions.
3422      *
3423      * @param   array   variable that lists the
3424      *       data types to be expected in the result set columns. If this array
3425      *       contains less types than the number of columns that are returned
3426      *       in the result set, the remaining columns are assumed to be of the
3427      *       type text. Currently, the types clob and blob are not fully
3428      *       supported.
3429      *
3430      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
3431      *
3432      * @access  public
3433      */
3434     function setResultTypes($types)
3435     {
3436         $load = $this->db->loadModule('Datatype', null, true);
3437         if (PEAR::isError($load)) {
3438             return $load;
3439         }
3440         $types = $this->db->datatype->checkResultTypes($types);
3441         if (PEAR::isError($types)) {
3442             return $types;
3443         }
3444         $this->types = $types;
3445         return MDB2_OK;
3446     }
3447
3448     // }}}
3449     // {{{ function seek($rownum = 0)
3450
3451     /**
3452      * Seek to a specific row in a result set
3453      *
3454      * @param   int     number of the row where the data can be found
3455      *
3456      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
3457      *
3458      * @access  public
3459      */
3460     function seek($rownum = 0)
3461     {
3462         $target_rownum = $rownum - 1;
3463         if ($this->rownum > $target_rownum) {
3464             return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
3465                 'seeking to previous rows not implemented', __FUNCTION__);
3466         }
3467         while ($this->rownum < $target_rownum) {
3468             $this->fetchRow();
3469         }
3470         return MDB2_OK;
3471     }
3472
3473     // }}}
3474     // {{{ function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
3475
3476     /**
3477      * Fetch and return a row of data
3478      *
3479      * @param   int     how the array data should be indexed
3480      * @param   int     number of the row where the data can be found
3481      *
3482      * @return  int     data array on success, a MDB2 error on failure
3483      *
3484      * @access  public
3485      */
7244b4 3486     function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
200b16 3487     {
7244b4 3488         $err = $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
200b16 3489             'method not implemented', __FUNCTION__);
A 3490         return $err;
3491     }
3492
3493     // }}}
3494     // {{{ function fetchOne($colnum = 0)
3495
3496     /**
3497      * fetch single column from the next row from a result set
3498      *
2273d4 3499      * @param int|string the column number (or name) to fetch
A 3500      * @param int        number of the row where the data can be found
200b16 3501      *
2273d4 3502      * @return string data on success, a MDB2 error on failure
200b16 3503      * @access  public
A 3504      */
3505     function fetchOne($colnum = 0, $rownum = null)
3506     {
3507         $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
3508         $row = $this->fetchRow($fetchmode, $rownum);
3509         if (!is_array($row) || PEAR::isError($row)) {
3510             return $row;
3511         }
3512         if (!array_key_exists($colnum, $row)) {
3513             return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
3514                 'column is not defined in the result set: '.$colnum, __FUNCTION__);
3515         }
3516         return $row[$colnum];
3517     }
3518
3519     // }}}
3520     // {{{ function fetchCol($colnum = 0)
3521
3522     /**
3523      * Fetch and return a column from the current row pointer position
3524      *
2273d4 3525      * @param int|string the column number (or name) to fetch
200b16 3526      *
2273d4 3527      * @return  mixed data array on success, a MDB2 error on failure
200b16 3528      * @access  public
A 3529      */
3530     function fetchCol($colnum = 0)
3531     {
3532         $column = array();
3533         $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
3534         $row = $this->fetchRow($fetchmode);
3535         if (is_array($row)) {
3536             if (!array_key_exists($colnum, $row)) {
3537                 return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
3538                     'column is not defined in the result set: '.$colnum, __FUNCTION__);
3539             }
3540             do {
3541                 $column[] = $row[$colnum];
3542             } while (is_array($row = $this->fetchRow($fetchmode)));
3543         }
3544         if (PEAR::isError($row)) {
3545             return $row;
3546         }
3547         return $column;
3548     }
3549
3550     // }}}
3551     // {{{ function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
3552
3553     /**
3554      * Fetch and return all rows from the current row pointer position
3555      *
3556      * @param   int     $fetchmode  the fetch mode to use:
3557      *                            + MDB2_FETCHMODE_ORDERED
3558      *                            + MDB2_FETCHMODE_ASSOC
3559      *                            + MDB2_FETCHMODE_ORDERED | MDB2_FETCHMODE_FLIPPED
3560      *                            + MDB2_FETCHMODE_ASSOC | MDB2_FETCHMODE_FLIPPED
3561      * @param   bool    if set to true, the $all will have the first
3562      *       column as its first dimension
3563      * @param   bool    used only when the query returns exactly
3564      *       two columns. If true, the values of the returned array will be
3565      *       one-element arrays instead of scalars.
3566      * @param   bool    if true, the values of the returned array is
3567      *       wrapped in another array.  If the same key value (in the first
3568      *       column) repeats itself, the values will be appended to this array
3569      *       instead of overwriting the existing values.
3570      *
3571      * @return  mixed   data array on success, a MDB2 error on failure
3572      *
3573      * @access  public
3574      * @see     getAssoc()
3575      */
3576     function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false,
3577         $force_array = false, $group = false)
3578     {
3579         $all = array();
3580         $row = $this->fetchRow($fetchmode);
3581         if (PEAR::isError($row)) {
3582             return $row;
3583         } elseif (!$row) {
3584             return $all;
3585         }
3586
3587         $shift_array = $rekey ? false : null;
2273d4 3588         if (null !== $shift_array) {
200b16 3589             if (is_object($row)) {
A 3590                 $colnum = count(get_object_vars($row));
3591             } else {
3592                 $colnum = count($row);
3593             }
3594             if ($colnum < 2) {
3595                 return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
3596                     'rekey feature requires atleast 2 column', __FUNCTION__);
3597             }
3598             $shift_array = (!$force_array && $colnum == 2);
3599         }
3600
3601         if ($rekey) {
3602             do {
3603                 if (is_object($row)) {
3604                     $arr = get_object_vars($row);
3605                     $key = reset($arr);
3606                     unset($row->{$key});
3607                 } else {
3608                     if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
3609                         $key = reset($row);
3610                         unset($row[key($row)]);
3611                     } else {
3612                         $key = array_shift($row);
3613                     }
3614                     if ($shift_array) {
3615                         $row = array_shift($row);
3616                     }
3617                 }
3618                 if ($group) {
3619                     $all[$key][] = $row;
3620                 } else {
3621                     $all[$key] = $row;
3622                 }
3623             } while (($row = $this->fetchRow($fetchmode)));
3624         } elseif ($fetchmode & MDB2_FETCHMODE_FLIPPED) {
3625             do {
3626                 foreach ($row as $key => $val) {
3627                     $all[$key][] = $val;
3628                 }
3629             } while (($row = $this->fetchRow($fetchmode)));
3630         } else {
3631             do {
3632                 $all[] = $row;
3633             } while (($row = $this->fetchRow($fetchmode)));
3634         }
3635
3636         return $all;
3637     }
3638
3639     // }}}
3640     // {{{ function rowCount()
3641     /**
3642      * Returns the actual row number that was last fetched (count from 0)
3643      * @return  int
3644      *
3645      * @access  public
3646      */
3647     function rowCount()
3648     {
3649         return $this->rownum + 1;
3650     }
3651
3652     // }}}
3653     // {{{ function numRows()
3654
3655     /**
3656      * Returns the number of rows in a result object
3657      *
3658      * @return  mixed   MDB2 Error Object or the number of rows
3659      *
3660      * @access  public
3661      */
3662     function numRows()
3663     {
3664         return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
3665             'method not implemented', __FUNCTION__);
3666     }
3667
3668     // }}}
3669     // {{{ function nextResult()
3670
3671     /**
3672      * Move the internal result pointer to the next available result
3673      *
3674      * @return  true on success, false if there is no more result set or an error object on failure
3675      *
3676      * @access  public
3677      */
3678     function nextResult()
3679     {
3680         return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
3681             'method not implemented', __FUNCTION__);
3682     }
3683
3684     // }}}
3685     // {{{ function getColumnNames()
3686
3687     /**
3688      * Retrieve the names of columns returned by the DBMS in a query result or
3689      * from the cache.
3690      *
3691      * @param   bool    If set to true the values are the column names,
3692      *                  otherwise the names of the columns are the keys.
3693      * @return  mixed   Array variable that holds the names of columns or an
3694      *                  MDB2 error on failure.
3695      *                  Some DBMS may not return any columns when the result set
3696      *                  does not contain any rows.
3697      *
3698      * @access  public
3699      */
3700     function getColumnNames($flip = false)
3701     {
3702         if (!isset($this->column_names)) {
3703             $result = $this->_getColumnNames();
3704             if (PEAR::isError($result)) {
3705                 return $result;
3706             }
3707             $this->column_names = $result;
3708         }
3709         if ($flip) {
3710             return array_flip($this->column_names);
3711         }
3712         return $this->column_names;
3713     }
3714
3715     // }}}
3716     // {{{ function _getColumnNames()
3717
3718     /**
3719      * Retrieve the names of columns returned by the DBMS in a query result.
3720      *
3721      * @return  mixed   Array variable that holds the names of columns as keys
3722      *                  or an MDB2 error on failure.
3723      *                  Some DBMS may not return any columns when the result set
3724      *                  does not contain any rows.
3725      *
3726      * @access  private
3727      */
3728     function _getColumnNames()
3729     {
3730         return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
3731             'method not implemented', __FUNCTION__);
3732     }
3733
3734     // }}}
3735     // {{{ function numCols()
3736
3737     /**
3738      * Count the number of columns returned by the DBMS in a query result.
3739      *
3740      * @return  mixed   integer value with the number of columns, a MDB2 error
3741      *       on failure
3742      *
3743      * @access  public
3744      */
3745     function numCols()
3746     {
3747         return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
3748             'method not implemented', __FUNCTION__);
3749     }
3750
3751     // }}}
3752     // {{{ function getResource()
3753
3754     /**
3755      * return the resource associated with the result object
3756      *
3757      * @return  resource
3758      *
3759      * @access  public
3760      */
3761     function getResource()
3762     {
3763         return $this->result;
3764     }
3765
3766     // }}}
3767     // {{{ function bindColumn($column, &$value, $type = null)
3768
3769     /**
3770      * Set bind variable to a column.
3771      *
3772      * @param   int     column number or name
3773      * @param   mixed   variable reference
3774      * @param   string  specifies the type of the field
3775      *
3776      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
3777      *
3778      * @access  public
3779      */
3780     function bindColumn($column, &$value, $type = null)
3781     {
3782         if (!is_numeric($column)) {
3783             $column_names = $this->getColumnNames();
3784             if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
3785                 if ($this->db->options['field_case'] == CASE_LOWER) {
3786                     $column = strtolower($column);
3787                 } else {
3788                     $column = strtoupper($column);
3789                 }
3790             }
3791             $column = $column_names[$column];
3792         }
3793         $this->values[$column] =& $value;
2273d4 3794         if (null !== $type) {
200b16 3795             $this->types[$column] = $type;
A 3796         }
3797         return MDB2_OK;
3798     }
3799
3800     // }}}
3801     // {{{ function _assignBindColumns($row)
3802
3803     /**
3804      * Bind a variable to a value in the result row.
3805      *
3806      * @param   array   row data
3807      *
3808      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
3809      *
3810      * @access  private
3811      */
3812     function _assignBindColumns($row)
3813     {
3814         $row = array_values($row);
3815         foreach ($row as $column => $value) {
3816             if (array_key_exists($column, $this->values)) {
3817                 $this->values[$column] = $value;
3818             }
3819         }
3820         return MDB2_OK;
3821     }
3822
3823     // }}}
3824     // {{{ function free()
3825
3826     /**
3827      * Free the internal resources associated with result.
3828      *
3829      * @return  bool    true on success, false if result is invalid
3830      *
3831      * @access  public
3832      */
3833     function free()
3834     {
3835         $this->result = false;
3836         return MDB2_OK;
3837     }
3838
3839     // }}}
3840 }
3841
3842 // }}}
3843 // {{{ class MDB2_Row
3844
3845 /**
3846  * The simple class that accepts row data as an array
3847  *
3848  * @package     MDB2
3849  * @category    Database
3850  * @author      Lukas Smith <smith@pooteeweet.org>
3851  */
3852 class MDB2_Row
3853 {
3854     // {{{ constructor: function __construct(&$row)
3855
3856     /**
3857      * constructor
3858      *
3859      * @param   resource    row data as array
3860      */
3861     function __construct(&$row)
3862     {
3863         foreach ($row as $key => $value) {
3864             $this->$key = &$row[$key];
3865         }
3866     }
3867
3868     // }}}
3869 }
3870
3871 // }}}
3872 // {{{ class MDB2_Statement_Common
3873
3874 /**
3875  * The common statement class for MDB2 statement objects
3876  *
3877  * @package     MDB2
3878  * @category    Database
3879  * @author      Lukas Smith <smith@pooteeweet.org>
3880  */
3881 class MDB2_Statement_Common
3882 {
3883     // {{{ Variables (Properties)
3884
3885     var $db;
3886     var $statement;
3887     var $query;
3888     var $result_types;
3889     var $types;
3890     var $values = array();
3891     var $limit;
3892     var $offset;
3893     var $is_manip;
3894
3895     // }}}
7244b4 3896     // {{{ constructor: function __construct($db, $statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
200b16 3897
A 3898     /**
3899      * Constructor
3900      */
7244b4 3901     function __construct($db, $statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
200b16 3902     {
7244b4 3903         $this->db = $db;
A 3904         $this->statement = $statement;
200b16 3905         $this->positions = $positions;
A 3906         $this->query = $query;
3907         $this->types = (array)$types;
3908         $this->result_types = (array)$result_types;
3909         $this->limit = $limit;
3910         $this->is_manip = $is_manip;
3911         $this->offset = $offset;
3912     }
3913
3914     // }}}
3915     // {{{ function bindValue($parameter, &$value, $type = null)
3916
3917     /**
3918      * Set the value of a parameter of a prepared query.
3919      *
3920      * @param   int     the order number of the parameter in the query
3921      *       statement. The order number of the first parameter is 1.
3922      * @param   mixed   value that is meant to be assigned to specified
3923      *       parameter. The type of the value depends on the $type argument.
3924      * @param   string  specifies the type of the field
3925      *
3926      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
3927      *
3928      * @access  public
3929      */
3930     function bindValue($parameter, $value, $type = null)
3931     {
3932         if (!is_numeric($parameter)) {
3933             $parameter = preg_replace('/^:(.*)$/', '\\1', $parameter);
3934         }
3935         if (!in_array($parameter, $this->positions)) {
3936             return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
3937                 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
3938         }
3939         $this->values[$parameter] = $value;
2273d4 3940         if (null !== $type) {
200b16 3941             $this->types[$parameter] = $type;
A 3942         }
3943         return MDB2_OK;
3944     }
3945
3946     // }}}
3947     // {{{ function bindValueArray($values, $types = null)
3948
3949     /**
3950      * Set the values of multiple a parameter of a prepared query in bulk.
3951      *
3952      * @param   array   specifies all necessary information
3953      *       for bindValue() the array elements must use keys corresponding to
3954      *       the number of the position of the parameter.
3955      * @param   array   specifies the types of the fields
3956      *
3957      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
3958      *
3959      * @access  public
3960      * @see     bindParam()
3961      */
3962     function bindValueArray($values, $types = null)
3963     {
3964         $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
3965         $parameters = array_keys($values);
3966         foreach ($parameters as $key => $parameter) {
3967             $this->db->pushErrorHandling(PEAR_ERROR_RETURN);
3968             $this->db->expectError(MDB2_ERROR_NOT_FOUND);
3969             $err = $this->bindValue($parameter, $values[$parameter], $types[$key]);
3970             $this->db->popExpect();
3971             $this->db->popErrorHandling();
3972             if (PEAR::isError($err)) {
3973                 if ($err->getCode() == MDB2_ERROR_NOT_FOUND) {
3974                     //ignore (extra value for missing placeholder)
3975                     continue;
3976                 }
3977                 return $err;
3978             }
3979         }
3980         return MDB2_OK;
3981     }
3982
3983     // }}}
3984     // {{{ function bindParam($parameter, &$value, $type = null)
3985
3986     /**
3987      * Bind a variable to a parameter of a prepared query.
3988      *
3989      * @param   int     the order number of the parameter in the query
3990      *       statement. The order number of the first parameter is 1.
3991      * @param   mixed   variable that is meant to be bound to specified
3992      *       parameter. The type of the value depends on the $type argument.
3993      * @param   string  specifies the type of the field
3994      *
3995      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
3996      *
3997      * @access  public
3998      */
3999     function bindParam($parameter, &$value, $type = null)
4000     {
4001         if (!is_numeric($parameter)) {
4002             $parameter = preg_replace('/^:(.*)$/', '\\1', $parameter);
4003         }
4004         if (!in_array($parameter, $this->positions)) {
4005             return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
4006                 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
4007         }
4008         $this->values[$parameter] =& $value;
2273d4 4009         if (null !== $type) {
200b16 4010             $this->types[$parameter] = $type;
A 4011         }
4012         return MDB2_OK;
4013     }
4014
4015     // }}}
4016     // {{{ function bindParamArray(&$values, $types = null)
4017
4018     /**
4019      * Bind the variables of multiple a parameter of a prepared query in bulk.
4020      *
4021      * @param   array   specifies all necessary information
4022      *       for bindParam() the array elements must use keys corresponding to
4023      *       the number of the position of the parameter.
4024      * @param   array   specifies the types of the fields
4025      *
4026      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
4027      *
4028      * @access  public
4029      * @see     bindParam()
4030      */
4031     function bindParamArray(&$values, $types = null)
4032     {
4033         $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
4034         $parameters = array_keys($values);
4035         foreach ($parameters as $key => $parameter) {
4036             $err = $this->bindParam($parameter, $values[$parameter], $types[$key]);
4037             if (PEAR::isError($err)) {
4038                 return $err;
4039             }
4040         }
4041         return MDB2_OK;
4042     }
4043
4044     // }}}
4045     // {{{ function &execute($values = null, $result_class = true, $result_wrap_class = false)
4046
4047     /**
4048      * Execute a prepared query statement.
4049      *
2273d4 4050      * @param array specifies all necessary information
A 4051      *              for bindParam() the array elements must use keys corresponding
4052      *              to the number of the position of the parameter.
4053      * @param mixed specifies which result class to use
4054      * @param mixed specifies which class to wrap results in
200b16 4055      *
2273d4 4056      * @return mixed MDB2_Result or integer (affected rows) on success,
A 4057      *               a MDB2 error on failure
4058      * @access public
200b16 4059      */
7244b4 4060     function execute($values = null, $result_class = true, $result_wrap_class = false)
200b16 4061     {
2273d4 4062         if (null === $this->positions) {
200b16 4063             return $this->db->raiseError(MDB2_ERROR, null, null,
A 4064                 'Prepared statement has already been freed', __FUNCTION__);
4065         }
4066
4067         $values = (array)$values;
4068         if (!empty($values)) {
4069             $err = $this->bindValueArray($values);
4070             if (PEAR::isError($err)) {
4071                 return $this->db->raiseError(MDB2_ERROR, null, null,
4072                                             'Binding Values failed with message: ' . $err->getMessage(), __FUNCTION__);
4073             }
4074         }
7244b4 4075         $result = $this->_execute($result_class, $result_wrap_class);
200b16 4076         return $result;
A 4077     }
4078
4079     // }}}
7244b4 4080     // {{{ function _execute($result_class = true, $result_wrap_class = false)
200b16 4081
A 4082     /**
4083      * Execute a prepared query statement helper method.
4084      *
4085      * @param   mixed   specifies which result class to use
4086      * @param   mixed   specifies which class to wrap results in
4087      *
2273d4 4088      * @return mixed MDB2_Result or integer (affected rows) on success,
A 4089      *               a MDB2 error on failure
200b16 4090      * @access  private
A 4091      */
7244b4 4092     function _execute($result_class = true, $result_wrap_class = false)
200b16 4093     {
A 4094         $this->last_query = $this->query;
4095         $query = '';
4096         $last_position = 0;
4097         foreach ($this->positions as $current_position => $parameter) {
4098             if (!array_key_exists($parameter, $this->values)) {
4099                 return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
4100                     'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
4101             }
4102             $value = $this->values[$parameter];
4103             $query.= substr($this->query, $last_position, $current_position - $last_position);
4104             if (!isset($value)) {
4105                 $value_quoted = 'NULL';
4106             } else {
4107                 $type = !empty($this->types[$parameter]) ? $this->types[$parameter] : null;
4108                 $value_quoted = $this->db->quote($value, $type);
4109                 if (PEAR::isError($value_quoted)) {
4110                     return $value_quoted;
4111                 }
4112             }
4113             $query.= $value_quoted;
4114             $last_position = $current_position + 1;
4115         }
4116         $query.= substr($this->query, $last_position);
4117
4118         $this->db->offset = $this->offset;
4119         $this->db->limit = $this->limit;
4120         if ($this->is_manip) {
4121             $result = $this->db->exec($query);
4122         } else {
7244b4 4123             $result = $this->db->query($query, $this->result_types, $result_class, $result_wrap_class);
200b16 4124         }
A 4125         return $result;
4126     }
4127
4128     // }}}
4129     // {{{ function free()
4130
4131     /**
4132      * Release resources allocated for the specified prepared query.
4133      *
4134      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
4135      *
4136      * @access  public
4137      */
4138     function free()
4139     {
2273d4 4140         if (null === $this->positions) {
200b16 4141             return $this->db->raiseError(MDB2_ERROR, null, null,
A 4142                 'Prepared statement has already been freed', __FUNCTION__);
4143         }
4144
4145         $this->statement = null;
4146         $this->positions = null;
4147         $this->query = null;
4148         $this->types = null;
4149         $this->result_types = null;
4150         $this->limit = null;
4151         $this->is_manip = null;
4152         $this->offset = null;
4153         $this->values = null;
4154
4155         return MDB2_OK;
4156     }
4157
4158     // }}}
4159 }
4160
4161 // }}}
4162 // {{{ class MDB2_Module_Common
4163
4164 /**
4165  * The common modules class for MDB2 module objects
4166  *
4167  * @package     MDB2
4168  * @category    Database
4169  * @author      Lukas Smith <smith@pooteeweet.org>
4170  */
4171 class MDB2_Module_Common
4172 {
4173     // {{{ Variables (Properties)
4174
4175     /**
4176      * contains the key to the global MDB2 instance array of the associated
4177      * MDB2 instance
4178      *
4179      * @var     int
4180      * @access  protected
4181      */
4182     var $db_index;
4183
4184     // }}}
4185     // {{{ constructor: function __construct($db_index)
4186
4187     /**
4188      * Constructor
4189      */
4190     function __construct($db_index)
4191     {
4192         $this->db_index = $db_index;
4193     }
4194
4195     // }}}
7244b4 4196     // {{{ function getDBInstance()
200b16 4197
A 4198     /**
4199      * Get the instance of MDB2 associated with the module instance
4200      *
4201      * @return  object  MDB2 instance or a MDB2 error on failure
4202      *
4203      * @access  public
4204      */
7244b4 4205     function getDBInstance()
200b16 4206     {
A 4207         if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
7244b4 4208             $result = $GLOBALS['_MDB2_databases'][$this->db_index];
200b16 4209         } else {
7244b4 4210             $result = MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
200b16 4211                 'could not find MDB2 instance');
A 4212         }
4213         return $result;
4214     }
4215
4216     // }}}
4217 }
4218
4219 // }}}
4220 // {{{ function MDB2_closeOpenTransactions()
4221
4222 /**
4223  * Close any open transactions form persistent connections
4224  *
4225  * @return  void
4226  *
4227  * @access  public
4228  */
4229
4230 function MDB2_closeOpenTransactions()
4231 {
4232     reset($GLOBALS['_MDB2_databases']);
4233     while (next($GLOBALS['_MDB2_databases'])) {
4234         $key = key($GLOBALS['_MDB2_databases']);
4235         if ($GLOBALS['_MDB2_databases'][$key]->opened_persistent
4236             && $GLOBALS['_MDB2_databases'][$key]->in_transaction
4237         ) {
4238             $GLOBALS['_MDB2_databases'][$key]->rollback();
4239         }
4240     }
4241 }
4242
4243 // }}}
4244 // {{{ function MDB2_defaultDebugOutput(&$db, $scope, $message, $is_manip = null)
4245
4246 /**
4247  * default debug output handler
4248  *
4249  * @param   object  reference to an MDB2 database object
4250  * @param   string  usually the method name that triggered the debug call:
4251  *                  for example 'query', 'prepare', 'execute', 'parameters',
4252  *                  'beginTransaction', 'commit', 'rollback'
4253  * @param   string  message that should be appended to the debug variable
4254  * @param   array   contains context information about the debug() call
4255  *                  common keys are: is_manip, time, result etc.
4256  *
4257  * @return  void|string optionally return a modified message, this allows
4258  *                      rewriting a query before being issued or prepared
4259  *
4260  * @access  public
4261  */
4262 function MDB2_defaultDebugOutput(&$db, $scope, $message, $context = array())
4263 {
4264     $db->debug_output.= $scope.'('.$db->db_index.'): ';
4265     $db->debug_output.= $message.$db->getOption('log_line_break');
4266     return $message;
4267 }
4268
4269 // }}}
2273d4 4270 ?>