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