source: branches/dev/data/module/MDB2.php @ 15951

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