source: branches/version-2_12-dev/data/module/MDB2.php @ 20764

Revision 20764, 140.9 KB checked in by nanasess, 13 years ago (diff)

#601 (コピーライトの更新)

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