source: closed/dev/data/module/MDB2.php @ 15985

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