]> source.dussan.org Git - nextcloud-server.git/commitdiff
update MDB2 and XML_Parser
authorRobin Appelman <icewind@owncloud.com>
Fri, 11 May 2012 18:25:00 +0000 (20:25 +0200)
committerRobin Appelman <icewind@owncloud.com>
Fri, 11 May 2012 18:33:56 +0000 (20:33 +0200)
35 files changed:
3rdparty/MDB2.php
3rdparty/MDB2/Date.php
3rdparty/MDB2/Driver/Datatype/Common.php
3rdparty/MDB2/Driver/Datatype/mysql.php
3rdparty/MDB2/Driver/Datatype/pgsql.php
3rdparty/MDB2/Driver/Datatype/sqlite.php
3rdparty/MDB2/Driver/Function/Common.php
3rdparty/MDB2/Driver/Function/mysql.php
3rdparty/MDB2/Driver/Function/pgsql.php
3rdparty/MDB2/Driver/Function/sqlite.php
3rdparty/MDB2/Driver/Manager/Common.php
3rdparty/MDB2/Driver/Manager/mysql.php
3rdparty/MDB2/Driver/Manager/pgsql.php
3rdparty/MDB2/Driver/Manager/sqlite.php
3rdparty/MDB2/Driver/Native/Common.php
3rdparty/MDB2/Driver/Native/mysql.php
3rdparty/MDB2/Driver/Native/pgsql.php
3rdparty/MDB2/Driver/Native/sqlite.php
3rdparty/MDB2/Driver/Reverse/Common.php
3rdparty/MDB2/Driver/Reverse/mysql.php
3rdparty/MDB2/Driver/Reverse/pgsql.php
3rdparty/MDB2/Driver/Reverse/sqlite.php
3rdparty/MDB2/Driver/mysql.php
3rdparty/MDB2/Driver/pgsql.php
3rdparty/MDB2/Driver/sqlite.php
3rdparty/MDB2/Extended.php
3rdparty/MDB2/Iterator.php
3rdparty/MDB2/LOB.php
3rdparty/MDB2/Schema.php
3rdparty/MDB2/Schema/Parser.php
3rdparty/MDB2/Schema/Validate.php
3rdparty/XML/Parser.php
3rdparty/XML/Parser/Simple.php [new file with mode: 0644]
3rdparty/XML/RPC.php [deleted file]
3rdparty/XML/RPC/Server.php [deleted file]

index aa7ec6ba093921a123898f97debe909a8eca00fa..2814f88ac0cd24e0cfcaab34710e86d6058e5810 100644 (file)
-<?php
-// vim: set et ts=4 sw=4 fdm=marker:
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: MDB2.php,v 1.335 2008/11/29 14:57:01 afz Exp $
-//
-
-/**
- * @package     MDB2
- * @category    Database
- * @author      Lukas Smith <smith@pooteeweet.org>
- */
-
-require_once('PEAR.php');
-
-// {{{ Error constants
-
-/**
- * The method mapErrorCode in each MDB2_dbtype implementation maps
- * native error codes to one of these.
- *
- * If you add an error code here, make sure you also add a textual
- * version of it in MDB2::errorMessage().
- */
-
-define('MDB2_OK',                      true);
-define('MDB2_ERROR',                     -1);
-define('MDB2_ERROR_SYNTAX',              -2);
-define('MDB2_ERROR_CONSTRAINT',          -3);
-define('MDB2_ERROR_NOT_FOUND',           -4);
-define('MDB2_ERROR_ALREADY_EXISTS',      -5);
-define('MDB2_ERROR_UNSUPPORTED',         -6);
-define('MDB2_ERROR_MISMATCH',            -7);
-define('MDB2_ERROR_INVALID',             -8);
-define('MDB2_ERROR_NOT_CAPABLE',         -9);
-define('MDB2_ERROR_TRUNCATED',          -10);
-define('MDB2_ERROR_INVALID_NUMBER',     -11);
-define('MDB2_ERROR_INVALID_DATE',       -12);
-define('MDB2_ERROR_DIVZERO',            -13);
-define('MDB2_ERROR_NODBSELECTED',       -14);
-define('MDB2_ERROR_CANNOT_CREATE',      -15);
-define('MDB2_ERROR_CANNOT_DELETE',      -16);
-define('MDB2_ERROR_CANNOT_DROP',        -17);
-define('MDB2_ERROR_NOSUCHTABLE',        -18);
-define('MDB2_ERROR_NOSUCHFIELD',        -19);
-define('MDB2_ERROR_NEED_MORE_DATA',     -20);
-define('MDB2_ERROR_NOT_LOCKED',         -21);
-define('MDB2_ERROR_VALUE_COUNT_ON_ROW', -22);
-define('MDB2_ERROR_INVALID_DSN',        -23);
-define('MDB2_ERROR_CONNECT_FAILED',     -24);
-define('MDB2_ERROR_EXTENSION_NOT_FOUND',-25);
-define('MDB2_ERROR_NOSUCHDB',           -26);
-define('MDB2_ERROR_ACCESS_VIOLATION',   -27);
-define('MDB2_ERROR_CANNOT_REPLACE',     -28);
-define('MDB2_ERROR_CONSTRAINT_NOT_NULL',-29);
-define('MDB2_ERROR_DEADLOCK',           -30);
-define('MDB2_ERROR_CANNOT_ALTER',       -31);
-define('MDB2_ERROR_MANAGER',            -32);
-define('MDB2_ERROR_MANAGER_PARSE',      -33);
-define('MDB2_ERROR_LOADMODULE',         -34);
-define('MDB2_ERROR_INSUFFICIENT_DATA',  -35);
-define('MDB2_ERROR_NO_PERMISSION',      -36);
-define('MDB2_ERROR_DISCONNECT_FAILED',  -37);
-
-// }}}
-// {{{ Verbose constants
-/**
- * These are just helper constants to more verbosely express parameters to prepare()
- */
-
-define('MDB2_PREPARE_MANIP', false);
-define('MDB2_PREPARE_RESULT', null);
-
-// }}}
-// {{{ Fetchmode constants
-
-/**
- * This is a special constant that tells MDB2 the user hasn't specified
- * any particular get mode, so the default should be used.
- */
-define('MDB2_FETCHMODE_DEFAULT', 0);
-
-/**
- * Column data indexed by numbers, ordered from 0 and up
- */
-define('MDB2_FETCHMODE_ORDERED', 1);
-
-/**
- * Column data indexed by column names
- */
-define('MDB2_FETCHMODE_ASSOC', 2);
-
-/**
- * Column data as object properties
- */
-define('MDB2_FETCHMODE_OBJECT', 3);
-
-/**
- * For multi-dimensional results: normally the first level of arrays
- * is the row number, and the second level indexed by column number or name.
- * MDB2_FETCHMODE_FLIPPED switches this order, so the first level of arrays
- * is the column name, and the second level the row number.
- */
-define('MDB2_FETCHMODE_FLIPPED', 4);
-
-// }}}
-// {{{ Portability mode constants
-
-/**
- * Portability: turn off all portability features.
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_NONE', 0);
-
-/**
- * Portability: convert names of tables and fields to case defined in the
- * "field_case" option when using the query*(), fetch*() and tableInfo() methods.
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_FIX_CASE', 1);
-
-/**
- * Portability: right trim the data output by query*() and fetch*().
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_RTRIM', 2);
-
-/**
- * Portability: force reporting the number of rows deleted.
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_DELETE_COUNT', 4);
-
-/**
- * Portability: not needed in MDB2 (just left here for compatibility to DB)
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_NUMROWS', 8);
-
-/**
- * Portability: makes certain error messages in certain drivers compatible
- * with those from other DBMS's.
- *
- * + mysql, mysqli:  change unique/primary key constraints
- *   MDB2_ERROR_ALREADY_EXISTS -> MDB2_ERROR_CONSTRAINT
- *
- * + odbc(access):  MS's ODBC driver reports 'no such field' as code
- *   07001, which means 'too few parameters.'  When this option is on
- *   that code gets mapped to MDB2_ERROR_NOSUCHFIELD.
- *
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_ERRORS', 16);
-
-/**
- * Portability: convert empty values to null strings in data output by
- * query*() and fetch*().
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_EMPTY_TO_NULL', 32);
-
-/**
- * Portability: removes database/table qualifiers from associative indexes
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES', 64);
-
-/**
- * Portability: turn on all portability features.
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_ALL', 127);
-
-// }}}
-// {{{ Globals for class instance tracking
-
-/**
- * These are global variables that are used to track the various class instances
- */
-
-$GLOBALS['_MDB2_databases'] = array();
-$GLOBALS['_MDB2_dsninfo_default'] = array(
-    'phptype'  => false,
-    'dbsyntax' => false,
-    'username' => false,
-    'password' => false,
-    'protocol' => false,
-    'hostspec' => false,
-    'port'     => false,
-    'socket'   => false,
-    'database' => false,
-    'mode'     => false,
-);
-
-// }}}
-// {{{ class MDB2
-
-/**
- * The main 'MDB2' class is simply a container class with some static
- * methods for creating DB objects as well as some utility functions
- * common to all parts of DB.
- *
- * The object model of MDB2 is as follows (indentation means inheritance):
- *
- * MDB2          The main MDB2 class.  This is simply a utility class
- *              with some 'static' methods for creating MDB2 objects as
- *              well as common utility functions for other MDB2 classes.
- *
- * MDB2_Driver_Common   The base for each MDB2 implementation.  Provides default
- * |            implementations (in OO lingo virtual methods) for
- * |            the actual DB implementations as well as a bunch of
- * |            query utility functions.
- * |
- * +-MDB2_Driver_mysql  The MDB2 implementation for MySQL. Inherits MDB2_Driver_Common.
- *              When calling MDB2::factory or MDB2::connect for MySQL
- *              connections, the object returned is an instance of this
- *              class.
- * +-MDB2_Driver_pgsql  The MDB2 implementation for PostGreSQL. Inherits MDB2_Driver_Common.
- *              When calling MDB2::factory or MDB2::connect for PostGreSQL
- *              connections, the object returned is an instance of this
- *              class.
- *
- * @package     MDB2
- * @category    Database
- * @author      Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2
-{
-    // {{{ function setOptions(&$db, $options)
-
-    /**
-     * set option array   in an exiting database object
-     *
-     * @param   MDB2_Driver_Common  MDB2 object
-     * @param   array   An associative array of option names and their values.
-     *
-     * @return mixed   MDB2_OK or a PEAR Error object
-     *
-     * @access  public
-     */
-    static function setOptions(&$db, $options)
-    {
-        if (is_array($options)) {
-            foreach ($options as $option => $value) {
-                $test = $db->setOption($option, $value);
-                if (PEAR::isError($test)) {
-                    return $test;
-                }
-            }
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ function classExists($classname)
-
-    /**
-     * Checks if a class exists without triggering __autoload
-     *
-     * @param   string  classname
-     *
-     * @return  bool    true success and false on error
-     * @static
-     * @access  public
-     */
-    static function classExists($classname)
-    {
-        if (version_compare(phpversion(), "5.0", ">=")) {
-            return class_exists($classname, false);
-        }
-        return class_exists($classname);
-    }
-
-    // }}}
-    // {{{ function loadClass($class_name, $debug)
-
-    /**
-     * Loads a PEAR class.
-     *
-     * @param   string  classname to load
-     * @param   bool    if errors should be suppressed
-     *
-     * @return  mixed   true success or PEAR_Error on failure
-     *
-     * @access  public
-     */
-    static function loadClass($class_name, $debug)
-    {
-        if (!MDB2::classExists($class_name)) {
-            $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
-            if ($debug) {
-                $include = include_once($file_name);
-            } else {
-                $include = include_once($file_name);
-            }
-            if (!$include) {
-                if (!MDB2::fileExists($file_name)) {
-                    $msg = "unable to find package '$class_name' file '$file_name'";
-                } else {
-                    $msg = "unable to load class '$class_name' from file '$file_name'";
-                }
-                $err =MDB2::raiseErrorStatic(MDB2_ERROR_NOT_FOUND, null, null, $msg);
-                return $err;
-            }
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ function &factory($dsn, $options = false)
-
-    /**
-     * Create a new MDB2 object for the specified database type
-     *
-     * IMPORTANT: In order for MDB2 to work properly it is necessary that
-     * you make sure that you work with a reference of the original
-     * object instead of a copy (this is a PHP4 quirk).
-     *
-     * For example:
-     *     $db =& MDB2::factory($dsn);
-     *          ^^
-     * And not:
-     *     $db = MDB2::factory($dsn);
-     *
-     * @param   mixed   'data source name', see the MDB2::parseDSN
-     *                      method for a description of the dsn format.
-     *                      Can also be specified as an array of the
-     *                      format returned by MDB2::parseDSN.
-     * @param   array   An associative array of option names and
-     *                            their values.
-     *
-     * @return  mixed   a newly created MDB2 object, or false on error
-     *
-     * @access  public
-     */
-    static function factory($dsn, $options = false)
-    {
-        $dsninfo = MDB2::parseDSN($dsn);
-        if (empty($dsninfo['phptype'])) {
-            $err =MDB2::raiseErrorStatic(MDB2_ERROR_NOT_FOUND,
-                null, null, 'no RDBMS driver specified');
-            return $err;
-        }
-        $class_name = 'MDB2_Driver_'.$dsninfo['phptype'];
-
-        $debug = (!empty($options['debug']));
-        $err = MDB2::loadClass($class_name, $debug);
-        if (PEAR::isError($err)) {
-            return $err;
-        }
-
-        $db =new $class_name();
-        $db->setDSN($dsninfo);
-        $err = MDB2::setOptions($db, $options);
-        if (PEAR::isError($err)) {
-            return $err;
-        }
-
-        return $db;
-    }
-
-    // }}}
-    // {{{ function &connect($dsn, $options = false)
-
-    /**
-     * Create a new MDB2_Driver_* connection object and connect to the specified
-     * database
-     *
-     * IMPORTANT: In order for MDB2 to work properly it is necessary that
-     * you make sure that you work with a reference of the original
-     * object instead of a copy (this is a PHP4 quirk).
-     *
-     * For example:
-     *     $db =& MDB2::connect($dsn);
-     *          ^^
-     * And not:
-     *     $db = MDB2::connect($dsn);
-     *          ^^
-     *
-     * @param mixed $dsn     'data source name', see the MDB2::parseDSN
-     *                       method for a description of the dsn format.
-     *                       Can also be specified as an array of the
-     *                       format returned by MDB2::parseDSN.
-     * @param array $options An associative array of option names and
-     *                       their values.
-     *
-     * @return mixed a newly created MDB2 connection object, or a MDB2
-     *               error object on error
-     *
-     * @access  public
-     * @see     MDB2::parseDSN
-     */
-    function &connect($dsn, $options = false)
-    {
-        $db =MDB2::factory($dsn, $options);
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $err = $db->connect();
-        if (PEAR::isError($err)) {
-            $dsn = $db->getDSN('string', 'xxx');
-            $db->disconnect();
-            $err->addUserInfo($dsn);
-            return $err;
-        }
-
-        return $db;
-    }
-
-    // }}}
-    // {{{ function &singleton($dsn = null, $options = false)
-
-    /**
-     * Returns a MDB2 connection with the requested DSN.
-     * A new MDB2 connection object is only created if no object with the
-     * requested DSN exists yet.
-     *
-     * IMPORTANT: In order for MDB2 to work properly it is necessary that
-     * you make sure that you work with a reference of the original
-     * object instead of a copy (this is a PHP4 quirk).
-     *
-     * For example:
-     *     $db =& MDB2::singleton($dsn);
-     *          ^^
-     * And not:
-     *     $db = MDB2::singleton($dsn);
-     *          ^^
-     *
-     * @param   mixed   'data source name', see the MDB2::parseDSN
-     *                            method for a description of the dsn format.
-     *                            Can also be specified as an array of the
-     *                            format returned by MDB2::parseDSN.
-     * @param   array   An associative array of option names and
-     *                            their values.
-     *
-     * @return  mixed   a newly created MDB2 connection object, or a MDB2
-     *                  error object on error
-     *
-     * @access  public
-     * @see     MDB2::parseDSN
-     */
-    function &singleton($dsn = null, $options = false)
-    {
-        if ($dsn) {
-            $dsninfo = MDB2::parseDSN($dsn);
-            $dsninfo = array_merge($GLOBALS['_MDB2_dsninfo_default'], $dsninfo);
-            $keys = array_keys($GLOBALS['_MDB2_databases']);
-            for ($i=0, $j=count($keys); $i<$j; ++$i) {
-                if (isset($GLOBALS['_MDB2_databases'][$keys[$i]])) {
-                    $tmp_dsn = $GLOBALS['_MDB2_databases'][$keys[$i]]->getDSN('array');
-                    if (count(array_diff_assoc($tmp_dsn, $dsninfo)) == 0) {
-                        MDB2::setOptions($GLOBALS['_MDB2_databases'][$keys[$i]], $options);
-                        return $GLOBALS['_MDB2_databases'][$keys[$i]];
-                    }
-                }
-            }
-        } elseif (is_array($GLOBALS['_MDB2_databases']) && reset($GLOBALS['_MDB2_databases'])) {
-            $db =$GLOBALS['_MDB2_databases'][key($GLOBALS['_MDB2_databases'])];
-            return $db;
-        }
-        $db =MDB2::factory($dsn, $options);
-        return $db;
-    }
-
-    // }}}
-    // {{{ function areEquals()
-
-    /**
-     * It looks like there's a memory leak in array_diff() in PHP 5.1.x,
-     * so use this method instead.
-     * @see http://pear.php.net/bugs/bug.php?id=11790
-     *
-     * @param array $arr1
-     * @param array $arr2
-     * @return boolean
-     */
-    static function areEquals($arr1, $arr2)
-    {
-        if (count($arr1) != count($arr2)) {
-            return false;
-        }
-        foreach (array_keys($arr1) as $k) {
-            if (!array_key_exists($k, $arr2) || $arr1[$k] != $arr2[$k]) {
-                return false;
-            }
-        }
-        return true;
-    }
-
-    // }}}
-    // {{{ function loadFile($file)
-
-    /**
-     * load a file (like 'Date')
-     *
-     * @param   string  name of the file in the MDB2 directory (without '.php')
-     *
-     * @return  string  name of the file that was included
-     *
-     * @access  public
-     */
-    function loadFile($file)
-    {
-        $file_name = 'MDB2'.DIRECTORY_SEPARATOR.$file.'.php';
-        if (!MDB2::fileExists($file_name)) {
-            return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                'unable to find: '.$file_name);
-        }
-        if (!include_once($file_name)) {
-            return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                'unable to load driver class: '.$file_name);
-        }
-        return $file_name;
-    }
-
-    // }}}
-    // {{{ function apiVersion()
-
-    /**
-     * Return the MDB2 API version
-     *
-     * @return  string  the MDB2 API version number
-     *
-     * @access  public
-     */
-    function apiVersion()
-    {
-        return '2.5.0b2';
-    }
-
-    // }}}
-    // {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
-
-    /**
-     * This method is used to communicate an error and invoke error
-     * callbacks etc.  Basically a wrapper for PEAR::raiseError
-     * without the message string.
-     *
-     * @param   mixed  int error code
-     *
-     * @param   int    error mode, see PEAR_Error docs
-     *
-     * @param   mixed  If error mode is PEAR_ERROR_TRIGGER, this is the
-     *                 error level (E_USER_NOTICE etc).  If error mode is
-     *                 PEAR_ERROR_CALLBACK, this is the callback function,
-     *                 either as a function name, or as an array of an
-     *                 object and method name.  For other error modes this
-     *                 parameter is ignored.
-     *
-     * @param   string Extra debug information.  Defaults to the last
-     *                 query and native error code.
-     *
-     * @return PEAR_Error instance of a PEAR Error object
-     *
-     * @access  private
-     * @see     PEAR_Error
-     */
-    function raiseError($code = null,
-                         $mode = null,
-                         $options = null,
-                         $userinfo = null,
-                         $dummy1 = null,
-                         $dummy2 = null,
-                         $dummy3 = false)
-    {
-        $err =PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
-        return $err;
-    }
-    static function raiseErrorStatic($code = null,
-                         $mode = null,
-                         $options = null,
-                         $userinfo = null,
-                         $dummy1 = null,
-                         $dummy2 = null,
-                         $dummy3 = false)
-    {
-           $pear=new PEAR();
-        $err =$pear->raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
-        return $err;
-    }
-
-    // }}}
-    // {{{ function isError($data, $code = null)
-
-    /**
-     * Tell whether a value is a MDB2 error.
-     *
-     * @param   mixed   the value to test
-     * @param   int     if is an error object, return true
-     *                        only if $code is a string and
-     *                        $db->getMessage() == $code or
-     *                        $code is an integer and $db->getCode() == $code
-     *
-     * @return  bool    true if parameter is an error
-     *
-     * @access  public
-     */
-    static function isError($data, $code = null)
-    {
-        if ($data instanceof MDB2_Error) {
-            if (is_null($code)) {
-                return true;
-            } elseif (is_string($code)) {
-                return $data->getMessage() === $code;
-            } else {
-                $code = (array)$code;
-                return in_array($data->getCode(), $code);
-            }
-        }
-        return false;
-    }
-
-    // }}}
-    // {{{ function isConnection($value)
-
-    /**
-     * Tell whether a value is a MDB2 connection
-     *
-     * @param   mixed   value to test
-     *
-     * @return  bool    whether $value is a MDB2 connection
-     *
-     * @access  public
-     */
-    static function isConnection($value)
-    {
-        return ($value instanceof MDB2_Driver_Common);
-    }
-
-    // }}}
-    // {{{ function isResult($value)
-
-    /**
-     * Tell whether a value is a MDB2 result
-     *
-     * @param   mixed   value to test
-     *
-     * @return  bool    whether $value is a MDB2 result
-     *
-     * @access  public
-     */
-    static function isResult($value)
-    {
-        return $value instanceof MDB2_Result;
-    }
-
-    // }}}
-    // {{{ function isResultCommon($value)
-
-    /**
-     * Tell whether a value is a MDB2 result implementing the common interface
-     *
-     * @param   mixed   value to test
-     *
-     * @return  bool    whether $value is a MDB2 result implementing the common interface
-     *
-     * @access  public
-     */
-    static function isResultCommon($value)
-    {
-        return ($value instanceof MDB2_Result_Common);
-    }
-
-    // }}}
-    // {{{ function isStatement($value)
-
-    /**
-     * Tell whether a value is a MDB2 statement interface
-     *
-     * @param   mixed   value to test
-     *
-     * @return  bool    whether $value is a MDB2 statement interface
-     *
-     * @access  public
-     */
-    static function isStatement($value)
-    {
-        return $value instanceof MDB2_Statement_Common;
-    }
-
-    // }}}
-    // {{{ function errorMessage($value = null)
-
-    /**
-     * Return a textual error message for a MDB2 error code
-     *
-     * @param   int|array   integer error code,
-                                null to get the current error code-message map,
-                                or an array with a new error code-message map
-     *
-     * @return  string  error message, or false if the error code was
-     *                  not recognized
-     *
-     * @access  public
-     */
-    static function errorMessage($value = null)
-    {
-        static $errorMessages;
-
-        if (is_array($value)) {
-            $errorMessages = $value;
-            return MDB2_OK;
-        }
-
-        if (!isset($errorMessages)) {
-            $errorMessages = array(
-                MDB2_OK                       => 'no error',
-                MDB2_ERROR                    => 'unknown error',
-                MDB2_ERROR_ALREADY_EXISTS     => 'already exists',
-                MDB2_ERROR_CANNOT_CREATE      => 'can not create',
-                MDB2_ERROR_CANNOT_ALTER       => 'can not alter',
-                MDB2_ERROR_CANNOT_REPLACE     => 'can not replace',
-                MDB2_ERROR_CANNOT_DELETE      => 'can not delete',
-                MDB2_ERROR_CANNOT_DROP        => 'can not drop',
-                MDB2_ERROR_CONSTRAINT         => 'constraint violation',
-                MDB2_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',
-                MDB2_ERROR_DIVZERO            => 'division by zero',
-                MDB2_ERROR_INVALID            => 'invalid',
-                MDB2_ERROR_INVALID_DATE       => 'invalid date or time',
-                MDB2_ERROR_INVALID_NUMBER     => 'invalid number',
-                MDB2_ERROR_MISMATCH           => 'mismatch',
-                MDB2_ERROR_NODBSELECTED       => 'no database selected',
-                MDB2_ERROR_NOSUCHFIELD        => 'no such field',
-                MDB2_ERROR_NOSUCHTABLE        => 'no such table',
-                MDB2_ERROR_NOT_CAPABLE        => 'MDB2 backend not capable',
-                MDB2_ERROR_NOT_FOUND          => 'not found',
-                MDB2_ERROR_NOT_LOCKED         => 'not locked',
-                MDB2_ERROR_SYNTAX             => 'syntax error',
-                MDB2_ERROR_UNSUPPORTED        => 'not supported',
-                MDB2_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
-                MDB2_ERROR_INVALID_DSN        => 'invalid DSN',
-                MDB2_ERROR_CONNECT_FAILED     => 'connect failed',
-                MDB2_ERROR_NEED_MORE_DATA     => 'insufficient data supplied',
-                MDB2_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
-                MDB2_ERROR_NOSUCHDB           => 'no such database',
-                MDB2_ERROR_ACCESS_VIOLATION   => 'insufficient permissions',
-                MDB2_ERROR_LOADMODULE         => 'error while including on demand module',
-                MDB2_ERROR_TRUNCATED          => 'truncated',
-                MDB2_ERROR_DEADLOCK           => 'deadlock detected',
-                MDB2_ERROR_NO_PERMISSION      => 'no permission',
-                MDB2_ERROR_DISCONNECT_FAILED  => 'disconnect failed',
-            );
-        }
-
-        if (is_null($value)) {
-            return $errorMessages;
-        }
-
-        if (PEAR::isError($value)) {
-            $value = $value->getCode();
-        }
-
-        return isset($errorMessages[$value]) ?
-           $errorMessages[$value] : $errorMessages[MDB2_ERROR];
-    }
-
-    // }}}
-    // {{{ function parseDSN($dsn)
-
-    /**
-     * Parse a data source name.
-     *
-     * Additional keys can be added by appending a URI query string to the
-     * end of the DSN.
-     *
-     * The format of the supplied DSN is in its fullest form:
-     * <code>
-     *  phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
-     * </code>
-     *
-     * Most variations are allowed:
-     * <code>
-     *  phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
-     *  phptype://username:password@hostspec/database_name
-     *  phptype://username:password@hostspec
-     *  phptype://username@hostspec
-     *  phptype://hostspec/database
-     *  phptype://hostspec
-     *  phptype(dbsyntax)
-     *  phptype
-     * </code>
-     *
-     * @param   string  Data Source Name to be parsed
-     *
-     * @return  array   an associative array with the following keys:
-     *  + phptype:  Database backend used in PHP (mysql, odbc etc.)
-     *  + dbsyntax: Database used with regards to SQL syntax etc.
-     *  + protocol: Communication protocol to use (tcp, unix etc.)
-     *  + hostspec: Host specification (hostname[:port])
-     *  + database: Database to use on the DBMS server
-     *  + username: User name for login
-     *  + password: Password for login
-     *
-     * @access  public
-     * @author  Tomas V.V.Cox <cox@idecnet.com>
-     */
-    static function parseDSN($dsn)
-    {
-        $parsed = $GLOBALS['_MDB2_dsninfo_default'];
-
-        if (is_array($dsn)) {
-            $dsn = array_merge($parsed, $dsn);
-            if (!$dsn['dbsyntax']) {
-                $dsn['dbsyntax'] = $dsn['phptype'];
-            }
-            return $dsn;
-        }
-
-        // Find phptype and dbsyntax
-        if (($pos = strpos($dsn, '://')) !== false) {
-            $str = substr($dsn, 0, $pos);
-            $dsn = substr($dsn, $pos + 3);
-        } else {
-            $str = $dsn;
-            $dsn = null;
-        }
-
-        // Get phptype and dbsyntax
-        // $str => phptype(dbsyntax)
-        if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
-            $parsed['phptype']  = $arr[1];
-            $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
-        } else {
-            $parsed['phptype']  = $str;
-            $parsed['dbsyntax'] = $str;
-        }
-
-        if (!count($dsn)) {
-            return $parsed;
-        }
-
-        // Get (if found): username and password
-        // $dsn => username:password@protocol+hostspec/database
-        if (($at = strrpos($dsn,'@')) !== false) {
-            $str = substr($dsn, 0, $at);
-            $dsn = substr($dsn, $at + 1);
-            if (($pos = strpos($str, ':')) !== false) {
-                $parsed['username'] = rawurldecode(substr($str, 0, $pos));
-                $parsed['password'] = rawurldecode(substr($str, $pos + 1));
-            } else {
-                $parsed['username'] = rawurldecode($str);
-            }
-        }
-
-        // Find protocol and hostspec
-
-        // $dsn => proto(proto_opts)/database
-        if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
-            $proto       = $match[1];
-            $proto_opts  = $match[2] ? $match[2] : false;
-            $dsn         = $match[3];
-
-        // $dsn => protocol+hostspec/database (old format)
-        } else {
-            if (strpos($dsn, '+') !== false) {
-                list($proto, $dsn) = explode('+', $dsn, 2);
-            }
-            if (   strpos($dsn, '//') === 0
-                && strpos($dsn, '/', 2) !== false
-                && $parsed['phptype'] == 'oci8'
-            ) {
-                //oracle's "Easy Connect" syntax:
-                //"username/password@[//]host[:port][/service_name]"
-                //e.g. "scott/tiger@//mymachine:1521/oracle"
-                $proto_opts = $dsn;
-                $dsn = substr($proto_opts, strrpos($proto_opts, '/') + 1);
-            } elseif (strpos($dsn, '/') !== false) {
-                list($proto_opts, $dsn) = explode('/', $dsn, 2);
-            } else {
-                $proto_opts = $dsn;
-                $dsn = null;
-            }
-        }
-
-        // process the different protocol options
-        $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
-        $proto_opts = rawurldecode($proto_opts);
-        if (strpos($proto_opts, ':') !== false) {
-            list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
-        }
-        if ($parsed['protocol'] == 'tcp') {
-            $parsed['hostspec'] = $proto_opts;
-        } elseif ($parsed['protocol'] == 'unix') {
-            $parsed['socket'] = $proto_opts;
-        }
-
-        // Get dabase if any
-        // $dsn => database
-        if ($dsn) {
-            // /database
-            if (($pos = strpos($dsn, '?')) === false) {
-                $parsed['database'] = $dsn;
-            // /database?param1=value1&param2=value2
-            } else {
-                $parsed['database'] = substr($dsn, 0, $pos);
-                $dsn = substr($dsn, $pos + 1);
-                if (strpos($dsn, '&') !== false) {
-                    $opts = explode('&', $dsn);
-                } else { // database?param1=value1
-                    $opts = array($dsn);
-                }
-                foreach ($opts as $opt) {
-                    list($key, $value) = explode('=', $opt);
-                    if (!isset($parsed[$key])) {
-                        // don't allow params overwrite
-                        $parsed[$key] = rawurldecode($value);
-                    }
-                }
-            }
-        }
-
-        return $parsed;
-    }
-
-    // }}}
-    // {{{ function fileExists($file)
-
-    /**
-     * Checks if a file exists in the include path
-     *
-     * @param   string  filename
-     *
-     * @return  bool    true success and false on error
-     *
-     * @access  public
-     */
-    static function fileExists($file)
-    {
-        // safe_mode does notwork with is_readable()
-        if (!@ini_get('safe_mode')) {
-             $dirs = explode(PATH_SEPARATOR, ini_get('include_path'));
-             array_unshift($dirs,OC::$SERVERROOT);
-             array_unshift($dirs,OC::$SERVERROOT. DIRECTORY_SEPARATOR .'inc');
-//              print_r($dirs);die();
-             foreach ($dirs as $dir) {
-                 if (is_readable($dir . DIRECTORY_SEPARATOR . $file)) {
-                     return true;
-                 }
-            }
-        } else {
-            $fp = @fopen($file, 'r', true);
-            if (is_resource($fp)) {
-                @fclose($fp);
-                return true;
-            }
-        }
-        return false;
-    }
-    // }}}
-}
-
-// }}}
-// {{{ class MDB2_Error extends PEAR_Error
-
-/**
- * MDB2_Error implements a class for reporting portable database error
- * messages.
- *
- * @package     MDB2
- * @category    Database
- * @author Stig Bakken <ssb@fast.no>
- */
-class MDB2_Error extends PEAR_Error
-{
-    // {{{ constructor: function MDB2_Error($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN, $level = E_USER_NOTICE, $debuginfo = null)
-
-    /**
-     * MDB2_Error constructor.
-     *
-     * @param   mixed   MDB2 error code, or string with error message.
-     * @param   int     what 'error mode' to operate in
-     * @param   int     what error level to use for $mode raPEAR_ERROR_TRIGGER
-     * @param   mixed   additional debug info, such as the last query
-     */
-    function MDB2_Error($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN,
-              $level = E_USER_NOTICE, $debuginfo = null, $dummy = null)
-    {
-        if (is_null($code)) {
-            $code = MDB2_ERROR;
-        }
-        $this->PEAR_Error('MDB2 Error: '.MDB2::errorMessage($code), $code,
-            $mode, $level, $debuginfo);
-    }
-
-    // }}}
-}
-
-// }}}
-// {{{ class MDB2_Driver_Common extends PEAR
-
-/**
- * MDB2_Driver_Common: Base class that is extended by each MDB2 driver
- *
- * @package     MDB2
- * @category    Database
- * @author      Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Common extends PEAR
-{
-    // {{{ Variables (Properties)
-
-    /**
-     * index of the MDB2 object within the $GLOBALS['_MDB2_databases'] array
-     * @var     int
-     * @access  public
-     */
-    var $db_index = 0;
-
-    /**
-     * DSN used for the next query
-     * @var     array
-     * @access  protected
-     */
-    var $dsn = array();
-
-    /**
-     * DSN that was used to create the current connection
-     * @var     array
-     * @access  protected
-     */
-    var $connected_dsn = array();
-
-    /**
-     * connection resource
-     * @var     mixed
-     * @access  protected
-     */
-    var $connection = 0;
-
-    /**
-     * if the current opened connection is a persistent connection
-     * @var     bool
-     * @access  protected
-     */
-    var $opened_persistent;
-
-    /**
-     * the name of the database for the next query
-     * @var     string
-     * @access  protected
-     */
-    var $database_name = '';
-
-    /**
-     * the name of the database currently selected
-     * @var     string
-     * @access  protected
-     */
-    var $connected_database_name = '';
-
-    /**
-     * server version information
-     * @var     string
-     * @access  protected
-     */
-    var $connected_server_info = '';
-
-    /**
-     * list of all supported features of the given driver
-     * @var     array
-     * @access  public
-     */
-    var $supported = array(
-        'sequences' => false,
-        'indexes' => false,
-        'affected_rows' => false,
-        'summary_functions' => false,
-        'order_by_text' => false,
-        'transactions' => false,
-        'savepoints' => false,
-        'current_id' => false,
-        'limit_queries' => false,
-        'LOBs' => false,
-        'replace' => false,
-        'sub_selects' => false,
-        'triggers' => false,
-        'auto_increment' => false,
-        'primary_key' => false,
-        'result_introspection' => false,
-        'prepared_statements' => false,
-        'identifier_quoting' => false,
-        'pattern_escaping' => false,
-        'new_link' => false,
-    );
-
-    /**
-     * Array of supported options that can be passed to the MDB2 instance.
-     * 
-     * The options can be set during object creation, using
-     * MDB2::connect(), MDB2::factory() or MDB2::singleton(). The options can 
-     * also be set after the object is created, using MDB2::setOptions() or 
-     * MDB2_Driver_Common::setOption().
-     * The list of available option includes:
-     * <ul>
-     *  <li>$options['ssl'] -> boolean: determines if ssl should be used for connections</li>
-     *  <li>$options['field_case'] -> CASE_LOWER|CASE_UPPER: determines what case to force on field/table names</li>
-     *  <li>$options['disable_query'] -> boolean: determines if queries should be executed</li>
-     *  <li>$options['result_class'] -> string: class used for result sets</li>
-     *  <li>$options['buffered_result_class'] -> string: class used for buffered result sets</li>
-     *  <li>$options['result_wrap_class'] -> string: class used to wrap result sets into</li>
-     *  <li>$options['result_buffering'] -> boolean should results be buffered or not?</li>
-     *  <li>$options['fetch_class'] -> string: class to use when fetch mode object is used</li>
-     *  <li>$options['persistent'] -> boolean: persistent connection?</li>
-     *  <li>$options['debug'] -> integer: numeric debug level</li>
-     *  <li>$options['debug_handler'] -> string: function/method that captures debug messages</li>
-     *  <li>$options['debug_expanded_output'] -> bool: BC option to determine if more context information should be send to the debug handler</li>
-     *  <li>$options['default_text_field_length'] -> integer: default text field length to use</li>
-     *  <li>$options['lob_buffer_length'] -> integer: LOB buffer length</li>
-     *  <li>$options['log_line_break'] -> string: line-break format</li>
-     *  <li>$options['idxname_format'] -> string: pattern for index name</li>
-     *  <li>$options['seqname_format'] -> string: pattern for sequence name</li>
-     *  <li>$options['savepoint_format'] -> string: pattern for auto generated savepoint names</li>
-     *  <li>$options['statement_format'] -> string: pattern for prepared statement names</li>
-     *  <li>$options['seqcol_name'] -> string: sequence column name</li>
-     *  <li>$options['quote_identifier'] -> boolean: if identifier quoting should be done when check_option is used</li>
-     *  <li>$options['use_transactions'] -> boolean: if transaction use should be enabled</li>
-     *  <li>$options['decimal_places'] -> integer: number of decimal places to handle</li>
-     *  <li>$options['portability'] -> integer: portability constant</li>
-     *  <li>$options['modules'] -> array: short to long module name mapping for __call()</li>
-     *  <li>$options['emulate_prepared'] -> boolean: force prepared statements to be emulated</li>
-     *  <li>$options['datatype_map'] -> array: map user defined datatypes to other primitive datatypes</li>
-     *  <li>$options['datatype_map_callback'] -> array: callback function/method that should be called</li>
-     *  <li>$options['bindname_format'] -> string: regular expression pattern for named parameters</li>
-     *  <li>$options['multi_query'] -> boolean: determines if queries returning multiple result sets should be executed</li>
-     *  <li>$options['max_identifiers_length'] -> integer: max identifier length</li>
-     *  <li>$options['default_fk_action_onupdate'] -> string: default FOREIGN KEY ON UPDATE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']</li>
-     *  <li>$options['default_fk_action_ondelete'] -> string: default FOREIGN KEY ON DELETE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']</li>
-     * </ul>
-     *
-     * @var     array
-     * @access  public
-     * @see     MDB2::connect()
-     * @see     MDB2::factory()
-     * @see     MDB2::singleton()
-     * @see     MDB2_Driver_Common::setOption()
-     */
-    var $options = array(
-        'ssl' => false,
-        'field_case' => CASE_LOWER,
-        'disable_query' => false,
-        'result_class' => 'MDB2_Result_%s',
-        'buffered_result_class' => 'MDB2_BufferedResult_%s',
-        'result_wrap_class' => false,
-        'result_buffering' => true,
-        'fetch_class' => 'stdClass',
-        'persistent' => false,
-        'debug' => 0,
-        'debug_handler' => 'MDB2_defaultDebugOutput',
-        'debug_expanded_output' => false,
-        'default_text_field_length' => 4096,
-        'lob_buffer_length' => 8192,
-        'log_line_break' => "\n",
-        'idxname_format' => '%s_idx',
-        'seqname_format' => '%s_seq',
-        'savepoint_format' => 'MDB2_SAVEPOINT_%s',
-        'statement_format' => 'MDB2_STATEMENT_%1$s_%2$s',
-        'seqcol_name' => 'sequence',
-        'quote_identifier' => false,
-        'use_transactions' => true,
-        'decimal_places' => 2,
-        'portability' => MDB2_PORTABILITY_ALL,
-        'modules' => array(
-            'ex' => 'Extended',
-            'dt' => 'Datatype',
-            'mg' => 'Manager',
-            'rv' => 'Reverse',
-            'na' => 'Native',
-            'fc' => 'Function',
-        ),
-        'emulate_prepared' => false,
-        'datatype_map' => array(),
-        'datatype_map_callback' => array(),
-        'nativetype_map_callback' => array(),
-        'lob_allow_url_include' => false,
-        'bindname_format' => '(?:\d+)|(?:[a-zA-Z][a-zA-Z0-9_]*)',
-        'max_identifiers_length' => 30,
-        'default_fk_action_onupdate' => 'RESTRICT',
-        'default_fk_action_ondelete' => 'RESTRICT',
-    );
-
-    /**
-     * string array
-     * @var     string
-     * @access  protected
-     */
-    var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => false, 'escape_pattern' => false);
-
-    /**
-     * identifier quoting
-     * @var     array
-     * @access  protected
-     */
-    var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
-
-    /**
-     * sql comments
-     * @var     array
-     * @access  protected
-     */
-    var $sql_comments = array(
-        array('start' => '--', 'end' => "\n", 'escape' => false),
-        array('start' => '/*', 'end' => '*/', 'escape' => false),
-    );
-
-    /**
-     * comparision wildcards
-     * @var     array
-     * @access  protected
-     */
-    var $wildcards = array('%', '_');
-
-    /**
-     * column alias keyword
-     * @var     string
-     * @access  protected
-     */
-    var $as_keyword = ' AS ';
-
-    /**
-     * warnings
-     * @var     array
-     * @access  protected
-     */
-    var $warnings = array();
-
-    /**
-     * string with the debugging information
-     * @var     string
-     * @access  public
-     */
-    var $debug_output = '';
-
-    /**
-     * determine if there is an open transaction
-     * @var     bool
-     * @access  protected
-     */
-    var $in_transaction = false;
-
-    /**
-     * the smart transaction nesting depth
-     * @var     int
-     * @access  protected
-     */
-    var $nested_transaction_counter = null;
-
-    /**
-     * the first error that occured inside a nested transaction
-     * @var     MDB2_Error|bool
-     * @access  protected
-     */
-    var $has_transaction_error = false;
-
-    /**
-     * result offset used in the next query
-     * @var     int
-     * @access  protected
-     */
-    var $offset = 0;
-
-    /**
-     * result limit used in the next query
-     * @var     int
-     * @access  protected
-     */
-    var $limit = 0;
-
-    /**
-     * Database backend used in PHP (mysql, odbc etc.)
-     * @var     string
-     * @access  public
-     */
-    var $phptype;
-
-    /**
-     * Database used with regards to SQL syntax etc.
-     * @var     string
-     * @access  public
-     */
-    var $dbsyntax;
-
-    /**
-     * the last query sent to the driver
-     * @var     string
-     * @access  public
-     */
-    var $last_query;
-
-    /**
-     * the default fetchmode used
-     * @var     int
-     * @access  protected
-     */
-    var $fetchmode = MDB2_FETCHMODE_ORDERED;
-
-    /**
-     * array of module instances
-     * @var     array
-     * @access  protected
-     */
-    var $modules = array();
-
-    /**
-     * determines of the PHP4 destructor emulation has been enabled yet
-     * @var     array
-     * @access  protected
-     */
-    var $destructor_registered = true;
-
-    // }}}
-    // {{{ constructor: function __construct()
-
-    /**
-     * Constructor
-     */
-    function __construct()
-    {
-        end($GLOBALS['_MDB2_databases']);
-        $db_index = key($GLOBALS['_MDB2_databases']) + 1;
-        $GLOBALS['_MDB2_databases'][$db_index] = &$this;
-        $this->db_index = $db_index;
-    }
-
-
-    // }}}
-    // {{{ destructor: function __destruct()
-
-    /**
-     *  Destructor
-     */
-    function __destruct()
-    {
-        $this->disconnect(false);
-    }
-
-    // }}}
-    // {{{ function free()
-
-    /**
-     * Free the internal references so that the instance can be destroyed
-     *
-     * @return  bool    true on success, false if result is invalid
-     *
-     * @access  public
-     */
-    function free()
-    {
-        unset($GLOBALS['_MDB2_databases'][$this->db_index]);
-        unset($this->db_index);
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ function __toString()
-
-    /**
-     * String conversation
-     *
-     * @return  string representation of the object
-     *
-     * @access  public
-     */
-    function __toString()
-    {
-        $info = get_class($this);
-        $info.= ': (phptype = '.$this->phptype.', dbsyntax = '.$this->dbsyntax.')';
-        if ($this->connection) {
-            $info.= ' [connected]';
-        }
-        return $info;
-    }
-
-    // }}}
-    // {{{ function errorInfo($error = null)
-
-    /**
-     * This method is used to collect information about an error
-     *
-     * @param   mixed   error code or resource
-     *
-     * @return  array   with MDB2 errorcode, native error code, native message
-     *
-     * @access  public
-     */
-    function errorInfo($error = null)
-    {
-        return array($error, null, null);
-    }
-
-    // }}}
-    // {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
-
-    /**
-     * This method is used to communicate an error and invoke error
-     * callbacks etc.  Basically a wrapper for PEAR::raiseError
-     * without the message string.
-     *
-     * @param mixed  $code     integer error code, or a PEAR error object (all 
-     *                         other parameters are ignored if this parameter is
-     *                         an object
-     * @param int    $mode     error mode, see PEAR_Error docs
-     * @param mixed  $options  If error mode is PEAR_ERROR_TRIGGER, this is the
-     *                         error level (E_USER_NOTICE etc). If error mode is
-     *                         PEAR_ERROR_CALLBACK, this is the callback function,
-     *                         either as a function name, or as an array of an
-     *                         object and method name. For other error modes this
-     *                         parameter is ignored.
-     * @param string $userinfo Extra debug information. Defaults to the last
-     *                         query and native error code.
-     * @param string $method   name of the method that triggered the error
-     * @param string $dummy1   not used
-     * @param bool   $dummy2   not used
-     *
-     * @return PEAR_Error instance of a PEAR Error object
-     * @access public
-     * @see    PEAR_Error
-     */
-    function raiseError($code = null,
-                         $mode = null,
-                         $options = null,
-                         $userinfo = null,
-                         $method = null,
-                         $dummy1 = null,
-                         $dummy2 = false
-    ) {
-        $userinfo = "[Error message: $userinfo]\n";
-        // The error is yet a MDB2 error object
-        if (PEAR::isError($code)) {
-            // because we use the static PEAR::raiseError, our global
-            // handler should be used if it is set
-            if (is_null($mode) && !empty($this->_default_error_mode)) {
-                $mode    = $this->_default_error_mode;
-                $options = $this->_default_error_options;
-            }
-            if (is_null($userinfo)) {
-                $userinfo = $code->getUserinfo();
-            }
-            $code = $code->getCode();
-        } elseif ($code == MDB2_ERROR_NOT_FOUND) {
-            // extension not loaded: don't call $this->errorInfo() or the script
-            // will die
-        } elseif (isset($this->connection)) {
-            if (!empty($this->last_query)) {
-                $userinfo.= "[Last executed query: {$this->last_query}]\n";
-            }
-            $native_errno = $native_msg = null;
-            list($code, $native_errno, $native_msg) = $this->errorInfo($code);
-            if (!is_null($native_errno) && $native_errno !== '') {
-                $userinfo.= "[Native code: $native_errno]\n";
-            }
-            if (!is_null($native_msg) && $native_msg !== '') {
-                $userinfo.= "[Native message: ". strip_tags($native_msg) ."]\n";
-            }
-            echo $userinfo;
-            if (!is_null($method)) {
-                $userinfo = $method.': '.$userinfo;
-            }
-        }
-
-        $err = PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
-        if ($err->getMode() !== PEAR_ERROR_RETURN
-            && isset($this->nested_transaction_counter) && !$this->has_transaction_error) {
-            $this->has_transaction_error =$err;
-        }
-        return $err;
-    }
-
-    // }}}
-    // {{{ function resetWarnings()
-
-    /**
-     * reset the warning array
-     *
-     * @return void
-     *
-     * @access  public
-     */
-    function resetWarnings()
-    {
-        $this->warnings = array();
-    }
-
-    // }}}
-    // {{{ function getWarnings()
-
-    /**
-     * Get all warnings in reverse order.
-     * This means that the last warning is the first element in the array
-     *
-     * @return  array   with warnings
-     *
-     * @access  public
-     * @see     resetWarnings()
-     */
-    function getWarnings()
-    {
-        return array_reverse($this->warnings);
-    }
-
-    // }}}
-    // {{{ function setFetchMode($fetchmode, $object_class = 'stdClass')
-
-    /**
-     * Sets which fetch mode should be used by default on queries
-     * on this connection
-     *
-     * @param   int     MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC
-     *                               or MDB2_FETCHMODE_OBJECT
-     * @param   string  the class name of the object to be returned
-     *                               by the fetch methods when the
-     *                               MDB2_FETCHMODE_OBJECT mode is selected.
-     *                               If no class is specified by default a cast
-     *                               to object from the assoc array row will be
-     *                               done.  There is also the possibility to use
-     *                               and extend the 'MDB2_row' class.
-     *
-     * @return  mixed   MDB2_OK or MDB2 Error Object
-     *
-     * @access  public
-     * @see     MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC, MDB2_FETCHMODE_OBJECT
-     */
-    function setFetchMode($fetchmode, $object_class = 'stdClass')
-    {
-        switch ($fetchmode) {
-        case MDB2_FETCHMODE_OBJECT:
-            $this->options['fetch_class'] = $object_class;
-        case MDB2_FETCHMODE_ORDERED:
-        case MDB2_FETCHMODE_ASSOC:
-            $this->fetchmode = $fetchmode;
-            break;
-        default:
-            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'invalid fetchmode mode', __FUNCTION__);
-        }
-
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ function setOption($option, $value)
-
-    /**
-     * set the option for the db class
-     *
-     * @param   string  option name
-     * @param   mixed   value for the option
-     *
-     * @return  mixed   MDB2_OK or MDB2 Error Object
-     *
-     * @access  public
-     */
-    function setOption($option, $value)
-    {
-        if (array_key_exists($option, $this->options)) {
-            $this->options[$option] = $value;
-            return MDB2_OK;
-        }
-        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            "unknown option $option", __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ function getOption($option)
-
-    /**
-     * Returns the value of an option
-     *
-     * @param   string  option name
-     *
-     * @return  mixed   the option value or error object
-     *
-     * @access  public
-     */
-    function getOption($option)
-    {
-        if (array_key_exists($option, $this->options)) {
-            return $this->options[$option];
-        }
-        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            "unknown option $option", __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ function debug($message, $scope = '', $is_manip = null)
-
-    /**
-     * set a debug message
-     *
-     * @param   string  message that should be appended to the debug variable
-     * @param   string  usually the method name that triggered the debug call:
-     *                  for example 'query', 'prepare', 'execute', 'parameters',
-     *                  'beginTransaction', 'commit', 'rollback'
-     * @param   array   contains context information about the debug() call
-     *                  common keys are: is_manip, time, result etc.
-     *
-     * @return void
-     *
-     * @access  public
-     */
-    function debug($message, $scope = '', $context = array())
-    {
-        if ($this->options['debug'] && $this->options['debug_handler']) {
-            if (!$this->options['debug_expanded_output']) {
-                if (!empty($context['when']) && $context['when'] !== 'pre') {
-                    return null;
-                }
-                $context = empty($context['is_manip']) ? false : $context['is_manip'];
-            }
-            return call_user_func_array($this->options['debug_handler'], array(&$this, $scope, $message, $context));
-        }
-        return null;
-    }
-
-    // }}}
-    // {{{ function getDebugOutput()
-
-    /**
-     * output debug info
-     *
-     * @return  string  content of the debug_output class variable
-     *
-     * @access  public
-     */
-    function getDebugOutput()
-    {
-        return $this->debug_output;
-    }
-
-    // }}}
-    // {{{ function escape($text)
-
-    /**
-     * Quotes a string so it can be safely used in a query. It will quote
-     * the text so it can safely be used within a query.
-     *
-     * @param   string  the input string to quote
-     * @param   bool    escape wildcards
-     *
-     * @return  string  quoted string
-     *
-     * @access  public
-     */
-    function escape($text, $escape_wildcards = false)
-    {
-        if ($escape_wildcards) {
-            $text = $this->escapePattern($text);
-        }
-
-        $text = str_replace($this->string_quoting['end'], $this->string_quoting['escape'] . $this->string_quoting['end'], $text);
-        return $text;
-    }
-
-    // }}}
-    // {{{ function escapePattern($text)
-
-    /**
-     * Quotes pattern (% and _) characters in a string)
-     *
-     * @param   string  the input string to quote
-     *
-     * @return  string  quoted string
-     *
-     * @access  public
-     */
-    function escapePattern($text)
-    {
-        if ($this->string_quoting['escape_pattern']) {
-            $text = str_replace($this->string_quoting['escape_pattern'], $this->string_quoting['escape_pattern'] . $this->string_quoting['escape_pattern'], $text);
-            foreach ($this->wildcards as $wildcard) {
-                $text = str_replace($wildcard, $this->string_quoting['escape_pattern'] . $wildcard, $text);
-            }
-        }
-        return $text;
-    }
-
-    // }}}
-    // {{{ function quoteIdentifier($str, $check_option = false)
-
-    /**
-     * Quote a string so it can be safely used as a table or column name
-     *
-     * Delimiting style depends on which database driver is being used.
-     *
-     * NOTE: just because you CAN use delimited identifiers doesn't mean
-     * you SHOULD use them.  In general, they end up causing way more
-     * problems than they solve.
-     *
-     * NOTE: if you have table names containing periods, don't use this method
-     * (@see bug #11906)
-     *
-     * Portability is broken by using the following characters inside
-     * delimited identifiers:
-     *   + backtick (<kbd>`</kbd>) -- due to MySQL
-     *   + double quote (<kbd>"</kbd>) -- due to Oracle
-     *   + brackets (<kbd>[</kbd> or <kbd>]</kbd>) -- due to Access
-     *
-     * Delimited identifiers are known to generally work correctly under
-     * the following drivers:
-     *   + mssql
-     *   + mysql
-     *   + mysqli
-     *   + oci8
-     *   + pgsql
-     *   + sqlite
-     *
-     * InterBase doesn't seem to be able to use delimited identifiers
-     * via PHP 4.  They work fine under PHP 5.
-     *
-     * @param   string  identifier name to be quoted
-     * @param   bool    check the 'quote_identifier' option
-     *
-     * @return  string  quoted identifier string
-     *
-     * @access  public
-     */
-    function quoteIdentifier($str, $check_option = false)
-    {
-        if ($check_option && !$this->options['quote_identifier']) {
-            return $str;
-        }
-        $str = str_replace($this->identifier_quoting['end'], $this->identifier_quoting['escape'] . $this->identifier_quoting['end'], $str);
-        $parts = explode('.', $str);
-        foreach (array_keys($parts) as $k) {
-            $parts[$k] = $this->identifier_quoting['start'] . $parts[$k] . $this->identifier_quoting['end'];
-        }
-        return implode('.', $parts);
-    }
-
-    // }}}
-    // {{{ function getAsKeyword()
-
-    /**
-     * Gets the string to alias column
-     *
-     * @return string to use when aliasing a column
-     */
-    function getAsKeyword()
-    {
-        return $this->as_keyword;
-    }
-
-    // }}}
-    // {{{ function getConnection()
-
-    /**
-     * Returns a native connection
-     *
-     * @return  mixed   a valid MDB2 connection object,
-     *                  or a MDB2 error object on error
-     *
-     * @access  public
-     */
-    function getConnection()
-    {
-        $result = $this->connect();
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        return $this->connection;
-    }
-
-     // }}}
-    // {{{ function _fixResultArrayValues(&$row, $mode)
-
-    /**
-     * Do all necessary conversions on result arrays to fix DBMS quirks
-     *
-     * @param   array   the array to be fixed (passed by reference)
-     * @param   array   bit-wise addition of the required portability modes
-     *
-     * @return  void
-     *
-     * @access  protected
-     */
-    function _fixResultArrayValues(&$row, $mode)
-    {
-        switch ($mode) {
-        case MDB2_PORTABILITY_EMPTY_TO_NULL:
-            foreach ($row as $key => $value) {
-                if ($value === '') {
-                    $row[$key] = null;
-                }
-            }
-            break;
-        case MDB2_PORTABILITY_RTRIM:
-            foreach ($row as $key => $value) {
-                if (is_string($value)) {
-                    $row[$key] = rtrim($value);
-                }
-            }
-            break;
-        case MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES:
-            $tmp_row = array();
-            foreach ($row as $key => $value) {
-                $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
-            }
-            $row = $tmp_row;
-            break;
-        case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL):
-            foreach ($row as $key => $value) {
-                if ($value === '') {
-                    $row[$key] = null;
-                } elseif (is_string($value)) {
-                    $row[$key] = rtrim($value);
-                }
-            }
-            break;
-        case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
-            $tmp_row = array();
-            foreach ($row as $key => $value) {
-                if (is_string($value)) {
-                    $value = rtrim($value);
-                }
-                $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
-            }
-            $row = $tmp_row;
-            break;
-        case (MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
-            $tmp_row = array();
-            foreach ($row as $key => $value) {
-                if ($value === '') {
-                    $value = null;
-                }
-                $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
-            }
-            $row = $tmp_row;
-            break;
-        case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
-            $tmp_row = array();
-            foreach ($row as $key => $value) {
-                if ($value === '') {
-                    $value = null;
-                } elseif (is_string($value)) {
-                    $value = rtrim($value);
-                }
-                $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
-            }
-            $row = $tmp_row;
-            break;
-        }
-    }
-
-    // }}}
-    // {{{ function &loadModule($module, $property = null, $phptype_specific = null)
-
-    /**
-     * loads a module
-     *
-     * @param   string  name of the module that should be loaded
-     *                  (only used for error messages)
-     * @param   string  name of the property into which the class will be loaded
-     * @param   bool    if the class to load for the module is specific to the
-     *                  phptype
-     *
-     * @return  object  on success a reference to the given module is returned
-     *                  and on failure a PEAR error
-     *
-     * @access  public
-     */
-    function &loadModule($module, $property = null, $phptype_specific = null)
-    {
-        if (!$property) {
-            $property = strtolower($module);
-        }
-
-        if (!isset($this->{$property})) {
-            $version = $phptype_specific;
-            if ($phptype_specific !== false) {
-                $version = true;
-                $class_name = 'MDB2_Driver_'.$module.'_'.$this->phptype;
-                $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
-            }
-            if ($phptype_specific === false
-                || (!MDB2::classExists($class_name) && !MDB2::fileExists($file_name))
-            ) {
-                $version = false;
-                $class_name = 'MDB2_'.$module;
-                $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
-            }
-
-            $err = MDB2::loadClass($class_name, $this->getOption('debug'));
-            if (PEAR::isError($err)) {
-                return $err;
-            }
-            // load module in a specific version
-            if ($version) {
-                if (method_exists($class_name, 'getClassName')) {
-                    $class_name_new = call_user_func(array($class_name, 'getClassName'), $this->db_index);
-                    if ($class_name != $class_name_new) {
-                        $class_name = $class_name_new;
-                        $err = MDB2::loadClass($class_name, $this->getOption('debug'));
-                        if (PEAR::isError($err)) {
-                            return $err;
-                        }
-                    }
-                }
-            }
-
-            if (!MDB2::classExists($class_name)) {
-                $err =$this->raiseError(MDB2_ERROR_LOADMODULE, null, null,
-                    "unable to load module '$module' into property '$property'", __FUNCTION__);
-                return $err;
-            }
-            $this->{$property} = new $class_name($this->db_index);
-            $this->modules[$module] =$this->{$property};
-            if ($version) {
-                // this will be used in the connect method to determine if the module
-                // needs to be loaded with a different version if the server
-                // version changed in between connects
-                $this->loaded_version_modules[] = $property;
-            }
-        }
-
-        return $this->{$property};
-    }
-
-    // }}}
-    // {{{ function __call($method, $params)
-
-    /**
-     * Calls a module method using the __call magic method
-     *
-     * @param   string  Method name.
-     * @param   array   Arguments.
-     *
-     * @return  mixed   Returned value.
-     */
-    function __call($method, $params)
-    {
-        $module = null;
-        if (preg_match('/^([a-z]+)([A-Z])(.*)$/', $method, $match)
-            && isset($this->options['modules'][$match[1]])
-        ) {
-            $module = $this->options['modules'][$match[1]];
-            $method = strtolower($match[2]).$match[3];
-            if (!isset($this->modules[$module]) || !is_object($this->modules[$module])) {
-                $result =& $this->loadModule($module);
-                if (PEAR::isError($result)) {
-                    return $result;
-                }
-            }
-        } else {
-            foreach ($this->modules as $key => $foo) {
-                if (is_object($this->modules[$key])
-                    && method_exists($this->modules[$key], $method)
-                ) {
-                    $module = $key;
-                    break;
-                }
-            }
-        }
-        if (!is_null($module)) {
-            return call_user_func_array(array(&$this->modules[$module], $method), $params);
-        }
-        trigger_error(sprintf('Call to undefined function: %s::%s().', get_class($this), $method), E_USER_ERROR);
-    }
-
-    // }}}
-    // {{{ function beginTransaction($savepoint = null)
-
-    /**
-     * Start a transaction or set a savepoint.
-     *
-     * @param   string  name of a savepoint to set
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function beginTransaction($savepoint = null)
-    {
-        $this->debug('Starting transaction', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
-        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'transactions are not supported', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ function commit($savepoint = null)
-
-    /**
-     * Commit the database changes done during a transaction that is in
-     * progress or release a savepoint. This function may only be called when
-     * auto-committing is disabled, otherwise it will fail. Therefore, a new
-     * transaction is implicitly started after committing the pending changes.
-     *
-     * @param   string  name of a savepoint to release
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function commit($savepoint = null)
-    {
-        $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
-        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'commiting transactions is not supported', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ function rollback($savepoint = null)
-
-    /**
-     * Cancel any database changes done during a transaction or since a specific
-     * savepoint that is in progress. This function may only be called when
-     * auto-committing is disabled, otherwise it will fail. Therefore, a new
-     * transaction is implicitly started after canceling the pending changes.
-     *
-     * @param   string  name of a savepoint to rollback to
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function rollback($savepoint = null)
-    {
-        $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
-        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'rolling back transactions is not supported', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ function inTransaction($ignore_nested = false)
-
-    /**
-     * If a transaction is currently open.
-     *
-     * @param   bool    if the nested transaction count should be ignored
-     * @return  int|bool    - an integer with the nesting depth is returned if a
-     *                      nested transaction is open
-     *                      - true is returned for a normal open transaction
-     *                      - false is returned if no transaction is open
-     *
-     * @access  public
-     */
-    function inTransaction($ignore_nested = false)
-    {
-        if (!$ignore_nested && isset($this->nested_transaction_counter)) {
-            return $this->nested_transaction_counter;
-        }
-        return $this->in_transaction;
-    }
-
-    // }}}
-    // {{{ function setTransactionIsolation($isolation)
-
-    /**
-     * Set the transacton isolation level.
-     *
-     * @param   string  standard isolation level
-     *                  READ UNCOMMITTED (allows dirty reads)
-     *                  READ COMMITTED (prevents dirty reads)
-     *                  REPEATABLE READ (prevents nonrepeatable reads)
-     *                  SERIALIZABLE (prevents phantom reads)
-     * @param   array some transaction options:
-     *                  'wait' => 'WAIT' | 'NO WAIT'
-     *                  'rw'   => 'READ WRITE' | 'READ ONLY'
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     * @since   2.1.1
-     */
-    static function setTransactionIsolation($isolation, $options = array())
-    {
-        $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
-        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'isolation level setting is not supported', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ function beginNestedTransaction($savepoint = false)
-
-    /**
-     * Start a nested transaction.
-     *
-     * @return  mixed   MDB2_OK on success/savepoint name, a MDB2 error on failure
-     *
-     * @access  public
-     * @since   2.1.1
-     */
-    function beginNestedTransaction()
-    {
-        if ($this->in_transaction) {
-            ++$this->nested_transaction_counter;
-            $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
-            if ($this->supports('savepoints') && $savepoint) {
-                return $this->beginTransaction($savepoint);
-            }
-            return MDB2_OK;
-        }
-        $this->has_transaction_error = false;
-        $result = $this->beginTransaction();
-        $this->nested_transaction_counter = 1;
-        return $result;
-    }
-
-    // }}}
-    // {{{ function completeNestedTransaction($force_rollback = false, $release = false)
-
-    /**
-     * Finish a nested transaction by rolling back if an error occured or
-     * committing otherwise.
-     *
-     * @param   bool    if the transaction should be rolled back regardless
-     *                  even if no error was set within the nested transaction
-     * @return  mixed   MDB_OK on commit/counter decrementing, false on rollback
-     *                  and a MDB2 error on failure
-     *
-     * @access  public
-     * @since   2.1.1
-     */
-    function completeNestedTransaction($force_rollback = false)
-    {
-        if ($this->nested_transaction_counter > 1) {
-            $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
-            if ($this->supports('savepoints') && $savepoint) {
-                if ($force_rollback || $this->has_transaction_error) {
-                    $result = $this->rollback($savepoint);
-                    if (!PEAR::isError($result)) {
-                        $result = false;
-                        $this->has_transaction_error = false;
-                    }
-                } else {
-                    $result = $this->commit($savepoint);
-                }
-            } else {
-                $result = MDB2_OK;
-            }
-            --$this->nested_transaction_counter;
-            return $result;
-        }
-
-        $this->nested_transaction_counter = null;
-        $result = MDB2_OK;
-
-        // transaction has not yet been rolled back
-        if ($this->in_transaction) {
-            if ($force_rollback || $this->has_transaction_error) {
-                $result = $this->rollback();
-                if (!PEAR::isError($result)) {
-                    $result = false;
-                }
-            } else {
-                $result = $this->commit();
-            }
-        }
-        $this->has_transaction_error = false;
-        return $result;
-    }
-
-    // }}}
-    // {{{ function failNestedTransaction($error = null, $immediately = false)
-
-    /**
-     * Force setting nested transaction to failed.
-     *
-     * @param   mixed   value to return in getNestededTransactionError()
-     * @param   bool    if the transaction should be rolled back immediately
-     * @return  bool    MDB2_OK
-     *
-     * @access  public
-     * @since   2.1.1
-     */
-    function failNestedTransaction($error = null, $immediately = false)
-    {
-        if (is_null($error)) {
-            $error = $this->has_transaction_error ? $this->has_transaction_error : true;
-        } elseif (!$error) {
-            $error = true;
-        }
-        $this->has_transaction_error = $error;
-        if (!$immediately) {
-            return MDB2_OK;
-        }
-        return $this->rollback();
-    }
-
-    // }}}
-    // {{{ function getNestedTransactionError()
-
-    /**
-     * The first error that occured since the transaction start.
-     *
-     * @return  MDB2_Error|bool     MDB2 error object if an error occured or false.
-     *
-     * @access  public
-     * @since   2.1.1
-     */
-    function getNestedTransactionError()
-    {
-        return $this->has_transaction_error;
-    }
-
-    // }}}
-    // {{{ connect()
-
-    /**
-     * Connect to the database
-     *
-     * @return true on success, MDB2 Error Object on failure
-     */
-    function connect()
-    {
-        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ databaseExists()
-
-    /**
-     * check if given database name is exists?
-     *
-     * @param string $name    name of the database that should be checked
-     *
-     * @return mixed true/false on success, a MDB2 error on failure
-     * @access public
-     */
-    function databaseExists($name)
-    {
-        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ setCharset($charset, $connection = null)
-
-    /**
-     * Set the charset on the current connection
-     *
-     * @param string    charset
-     * @param resource  connection handle
-     *
-     * @return true on success, MDB2 Error Object on failure
-     */
-    function setCharset($charset, $connection = null)
-    {
-        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ function disconnect($force = true)
-
-    /**
-     * Log out and disconnect from the database.
-     *
-     * @param boolean $force whether the disconnect should be forced even if the
-     *                       connection is opened persistently
-     *
-     * @return mixed true on success, false if not connected and error object on error
-     *
-     * @access  public
-     */
-    function disconnect($force = true)
-    {
-        $this->connection = 0;
-        $this->connected_dsn = array();
-        $this->connected_database_name = '';
-        $this->opened_persistent = null;
-        $this->connected_server_info = '';
-        $this->in_transaction = null;
-        $this->nested_transaction_counter = null;
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ function setDatabase($name)
-
-    /**
-     * Select a different database
-     *
-     * @param   string  name of the database that should be selected
-     *
-     * @return  string  name of the database previously connected to
-     *
-     * @access  public
-     */
-    function setDatabase($name)
-    {
-        $previous_database_name = (isset($this->database_name)) ? $this->database_name : '';
-        $this->database_name = $name;
-        if (!empty($this->connected_database_name) && ($this->connected_database_name != $this->database_name)) {
-            $this->disconnect(false);
-        }
-        return $previous_database_name;
-    }
-
-    // }}}
-    // {{{ function getDatabase()
-
-    /**
-     * Get the current database
-     *
-     * @return  string  name of the database
-     *
-     * @access  public
-     */
-    function getDatabase()
-    {
-        return $this->database_name;
-    }
-
-    // }}}
-    // {{{ function setDSN($dsn)
-
-    /**
-     * set the DSN
-     *
-     * @param   mixed   DSN string or array
-     *
-     * @return  MDB2_OK
-     *
-     * @access  public
-     */
-    function setDSN($dsn)
-    {
-        $dsn_default = $GLOBALS['_MDB2_dsninfo_default'];
-        $dsn = MDB2::parseDSN($dsn);
-        if (array_key_exists('database', $dsn)) {
-            $this->database_name = $dsn['database'];
-            unset($dsn['database']);
-        }
-        $this->dsn = array_merge($dsn_default, $dsn);
-        return $this->disconnect(false);
-    }
-
-    // }}}
-    // {{{ function getDSN($type = 'string', $hidepw = false)
-
-    /**
-     * return the DSN as a string
-     *
-     * @param   string  format to return ("array", "string")
-     * @param   string  string to hide the password with
-     *
-     * @return  mixed   DSN in the chosen type
-     *
-     * @access  public
-     */
-    function getDSN($type = 'string', $hidepw = false)
-    {
-        $dsn = array_merge($GLOBALS['_MDB2_dsninfo_default'], $this->dsn);
-        $dsn['phptype'] = $this->phptype;
-        $dsn['database'] = $this->database_name;
-        if ($hidepw) {
-            $dsn['password'] = $hidepw;
-        }
-        switch ($type) {
-        // expand to include all possible options
-        case 'string':
-           $dsn = $dsn['phptype'].
-               ($dsn['dbsyntax'] ? ('('.$dsn['dbsyntax'].')') : '').
-               '://'.$dsn['username'].':'.
-                $dsn['password'].'@'.$dsn['hostspec'].
-                ($dsn['port'] ? (':'.$dsn['port']) : '').
-                '/'.$dsn['database'];
-            break;
-        case 'array':
-        default:
-            break;
-        }
-        return $dsn;
-    }
-
-    // }}}
-    // {{{ _isNewLinkSet()
-
-    /**
-     * Check if the 'new_link' option is set
-     *
-     * @return boolean
-     *
-     * @access protected
-     */
-    function _isNewLinkSet()
-    {
-        return (isset($this->dsn['new_link'])
-            && ($this->dsn['new_link'] === true
-             || (is_string($this->dsn['new_link']) && preg_match('/^true$/i', $this->dsn['new_link']))
-             || (is_numeric($this->dsn['new_link']) && 0 != (int)$this->dsn['new_link'])
-            )
-        );
-    }
-
-    // }}}
-    // {{{ function &standaloneQuery($query, $types = null, $is_manip = false)
-
-   /**
-     * execute a query as database administrator
-     *
-     * @param   string  the SQL query
-     * @param   mixed   array that contains the types of the columns in
-     *                        the result set
-     * @param   bool    if the query is a manipulation query
-     *
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function &standaloneQuery($query, $types = null, $is_manip = false)
-    {
-        $offset = $this->offset;
-        $limit = $this->limit;
-        $this->offset = $this->limit = 0;
-        $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
-
-        $connection = $this->getConnection();
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-
-        $result =$this->_doQuery($query, $is_manip, $connection, false);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-
-        if ($is_manip) {
-            $affected_rows =  $this->_affectedRows($connection, $result);
-            return $affected_rows;
-        }
-        $result =$this->_wrapResult($result, $types, true, false, $limit, $offset);
-        return $result;
-    }
-
-    // }}}
-    // {{{ function _modifyQuery($query, $is_manip, $limit, $offset)
-
-    /**
-     * Changes a query string for various DBMS specific reasons
-     *
-     * @param   string  query to modify
-     * @param   bool    if it is a DML query
-     * @param   int  limit the number of rows
-     * @param   int  start reading from given offset
-     *
-     * @return  string  modified query
-     *
-     * @access  protected
-     */
-    function _modifyQuery($query, $is_manip, $limit, $offset)
-    {
-        return $query;
-    }
-
-    // }}}
-    // {{{ function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
-
-    /**
-     * Execute a query
-     * @param   string  query
-     * @param   bool    if the query is a manipulation query
-     * @param   resource connection handle
-     * @param   string  database name
-     *
-     * @return  result or error object
-     *
-     * @access  protected
-     */
-    function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
-    {
-        $this->last_query = $query;
-        $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
-        if ($result) {
-            if (PEAR::isError($result)) {
-                return $result;
-            }
-            $query = $result;
-        }
-        $err =$this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-        return $err;
-    }
-
-    // }}}
-    // {{{ function _affectedRows($connection, $result = null)
-
-    /**
-     * Returns the number of rows affected
-     *
-     * @param   resource result handle
-     * @param   resource connection handle
-     *
-     * @return  mixed   MDB2 Error Object or the number of rows affected
-     *
-     * @access  private
-     */
-    function _affectedRows($connection, $result = null)
-    {
-        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ function &exec($query)
-
-    /**
-     * Execute a manipulation query to the database and return the number of affected rows
-     *
-     * @param   string  the SQL query
-     *
-     * @return  mixed   number of affected rows on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function &exec($query)
-    {
-        $offset = $this->offset;
-        $limit = $this->limit;
-        $this->offset = $this->limit = 0;
-        $query = $this->_modifyQuery($query, true, $limit, $offset);
-
-        $connection = $this->getConnection();
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-
-        $result =$this->_doQuery($query, true, $connection, $this->database_name);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-
-        $affectedRows = $this->_affectedRows($connection, $result);
-        return $affectedRows;
-    }
-
-    // }}}
-    // {{{ function &query($query, $types = null, $result_class = true, $result_wrap_class = false)
-
-    /**
-     * Send a query to the database and return any results
-     *
-     * @param   string  the SQL query
-     * @param   mixed   array that contains the types of the columns in
-     *                        the result set
-     * @param   mixed   string which specifies which result class to use
-     * @param   mixed   string which specifies which class to wrap results in
-     *
-     * @return mixed   an MDB2_Result handle on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function &query($query, $types = null, $result_class = true, $result_wrap_class = false)
-    {
-        $offset = $this->offset;
-        $limit = $this->limit;
-        $this->offset = $this->limit = 0;
-        $query = $this->_modifyQuery($query, false, $limit, $offset);
-
-        $connection = $this->getConnection();
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-
-        $result =$this->_doQuery($query, false, $connection, $this->database_name);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-
-        $result =$this->_wrapResult($result, $types, $result_class, $result_wrap_class, $limit, $offset);
-        return $result;
-    }
-
-    // }}}
-    // {{{ function &_wrapResult($result, $types = array(), $result_class = true, $result_wrap_class = false, $limit = null, $offset = null)
-
-    /**
-     * wrap a result set into the correct class
-     *
-     * @param   resource result handle
-     * @param   mixed   array that contains the types of the columns in
-     *                        the result set
-     * @param   mixed   string which specifies which result class to use
-     * @param   mixed   string which specifies which class to wrap results in
-     * @param   string  number of rows to select
-     * @param   string  first row to select
-     *
-     * @return mixed   an MDB2_Result, a MDB2 error on failure
-     *
-     * @access  protected
-     */
-    function &_wrapResult($result, $types = array(), $result_class = true,
-        $result_wrap_class = false, $limit = null, $offset = null)
-    {
-        if ($types === true) {
-            if ($this->supports('result_introspection')) {
-                $this->loadModule('Reverse', null, true);
-                $tableInfo = $this->reverse->tableInfo($result);
-                if (PEAR::isError($tableInfo)) {
-                    return $tableInfo;
-                }
-                $types = array();
-                foreach ($tableInfo as $field) {
-                    $types[] = $field['mdb2type'];
-                }
-            } else {
-                $types = null;
-            }
-        }
-
-        if ($result_class === true) {
-            $result_class = $this->options['result_buffering']
-                ? $this->options['buffered_result_class'] : $this->options['result_class'];
-        }
-
-        if ($result_class) {
-            $class_name = sprintf($result_class, $this->phptype);
-            if (!MDB2::classExists($class_name)) {
-                $err =$this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                    'result class does not exist '.$class_name, __FUNCTION__);
-                return $err;
-            }
-            $result =new $class_name($this, $result, $limit, $offset);
-            if (!MDB2::isResultCommon($result)) {
-                $err =$this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                    'result class is not extended from MDB2_Result_Common', __FUNCTION__);
-                return $err;
-            }
-            if (!empty($types)) {
-                $err = $result->setResultTypes($types);
-                if (PEAR::isError($err)) {
-                    $result->free();
-                    return $err;
-                }
-            }
-        }
-        if ($result_wrap_class === true) {
-            $result_wrap_class = $this->options['result_wrap_class'];
-        }
-        if ($result_wrap_class) {
-            if (!MDB2::classExists($result_wrap_class)) {
-                $err =$this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                    'result wrap class does not exist '.$result_wrap_class, __FUNCTION__);
-                return $err;
-            }
-            $result = new $result_wrap_class($result, $this->fetchmode);
-        }
-        return $result;
-    }
-
-    // }}}
-    // {{{ function getServerVersion($native = false)
-
-    /**
-     * return version information about the server
-     *
-     * @param   bool    determines if the raw version string should be returned
-     *
-     * @return  mixed   array with version information or row string
-     *
-     * @access  public
-     */
-    function getServerVersion($native = false)
-    {
-        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ function setLimit($limit, $offset = null)
-
-    /**
-     * set the range of the next query
-     *
-     * @param   string  number of rows to select
-     * @param   string  first row to select
-     *
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function setLimit($limit, $offset = null)
-    {
-        if (!$this->supports('limit_queries')) {
-            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'limit is not supported by this driver', __FUNCTION__);
-        }
-        $limit = (int)$limit;
-        if ($limit < 0) {
-            return $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
-                'it was not specified a valid selected range row limit', __FUNCTION__);
-        }
-        $this->limit = $limit;
-        if (!is_null($offset)) {
-            $offset = (int)$offset;
-            if ($offset < 0) {
-                return $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
-                    'it was not specified a valid first selected range row', __FUNCTION__);
-            }
-            $this->offset = $offset;
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ function subSelect($query, $type = false)
-
-    /**
-     * simple subselect emulation: leaves the query untouched for all RDBMS
-     * that support subselects
-     *
-     * @param   string  the SQL query for the subselect that may only
-     *                      return a column
-     * @param   string  determines type of the field
-     *
-     * @return  string  the query
-     *
-     * @access  public
-     */
-    function subSelect($query, $type = false)
-    {
-        if ($this->supports('sub_selects') === true) {
-            return $query;
-        }
-
-        if (!$this->supports('sub_selects')) {
-            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'method not implemented', __FUNCTION__);
-        }
-
-        $col = $this->queryCol($query, $type);
-        if (PEAR::isError($col)) {
-            return $col;
-        }
-        if (!is_array($col) || count($col) == 0) {
-            return 'NULL';
-        }
-        if ($type) {
-            $this->loadModule('Datatype', null, true);
-            return $this->datatype->implodeArray($col, $type);
-        }
-        return implode(', ', $col);
-    }
-
-    // }}}
-    // {{{ function replace($table, $fields)
-
-    /**
-     * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
-     * query, except that if there is already a row in the table with the same
-     * key field values, the old row is deleted before the new row is inserted.
-     *
-     * The REPLACE type of query does not make part of the SQL standards. Since
-     * practically only MySQL and SQLite implement it natively, this type of
-     * query isemulated through this method for other DBMS using standard types
-     * of queries inside a transaction to assure the atomicity of the operation.
-     *
-     * @param   string  name of the table on which the REPLACE query will
-     *       be executed.
-     * @param   array   associative array   that describes the fields and the
-     *       values that will be inserted or updated in the specified table. The
-     *       indexes of the array are the names of all the fields of the table.
-     *       The values of the array are also associative arrays that describe
-     *       the values and other properties of the table fields.
-     *
-     *       Here follows a list of field properties that need to be specified:
-     *
-     *       value
-     *           Value to be assigned to the specified field. This value may be
-     *           of specified in database independent type format as this
-     *           function can perform the necessary datatype conversions.
-     *
-     *           Default: this property is required unless the Null property is
-     *           set to 1.
-     *
-     *       type
-     *           Name of the type of the field. Currently, all types MDB2
-     *           are supported except for clob and blob.
-     *
-     *           Default: no type conversion
-     *
-     *       null
-     *           bool    property that indicates that the value for this field
-     *           should be set to null.
-     *
-     *           The default value for fields missing in INSERT queries may be
-     *           specified the definition of a table. Often, the default value
-     *           is already null, but since the REPLACE may be emulated using
-     *           an UPDATE query, make sure that all fields of the table are
-     *           listed in this function argument array.
-     *
-     *           Default: 0
-     *
-     *       key
-     *           bool    property that indicates that this field should be
-     *           handled as a primary key or at least as part of the compound
-     *           unique index of the table that will determine the row that will
-     *           updated if it exists or inserted a new row otherwise.
-     *
-     *           This function will fail if no key field is specified or if the
-     *           value of a key field is set to null because fields that are
-     *           part of unique index they may not be null.
-     *
-     *           Default: 0
-     *
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function replace($table, $fields)
-    {
-        if (!$this->supports('replace')) {
-            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'replace query is not supported', __FUNCTION__);
-        }
-        $count = count($fields);
-        $condition = $values = array();
-        for ($colnum = 0, reset($fields); $colnum < $count; next($fields), $colnum++) {
-            $name = key($fields);
-            if (isset($fields[$name]['null']) && $fields[$name]['null']) {
-                $value = 'NULL';
-            } else {
-                $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
-                $value = $this->quote($fields[$name]['value'], $type);
-            }
-            $values[$name] = $value;
-            if (isset($fields[$name]['key']) && $fields[$name]['key']) {
-                if ($value === 'NULL') {
-                    return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
-                        'key value '.$name.' may not be NULL', __FUNCTION__);
-                }
-                $condition[] = $this->quoteIdentifier($name, true) . '=' . $value;
-            }
-        }
-        if (empty($condition)) {
-            return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
-                'not specified which fields are keys', __FUNCTION__);
-        }
-
-        $result = null;
-        $in_transaction = $this->in_transaction;
-        if (!$in_transaction && PEAR::isError($result = $this->beginTransaction())) {
-            return $result;
-        }
-
-        $connection = $this->getConnection();
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-
-        $condition = ' WHERE '.implode(' AND ', $condition);
-        $query = 'DELETE FROM ' . $this->quoteIdentifier($table, true) . $condition;
-        $result =$this->_doQuery($query, true, $connection);
-        if (!PEAR::isError($result)) {
-            $affected_rows = $this->_affectedRows($connection, $result);
-            $insert = '';
-            foreach ($values as $key => $value) {
-                $insert .= ($insert?', ':'') . $this->quoteIdentifier($key, true);
-            }
-            $values = implode(', ', $values);
-            $query = 'INSERT INTO '. $this->quoteIdentifier($table, true) . "($insert) VALUES ($values)";
-            $result =$this->_doQuery($query, true, $connection);
-            if (!PEAR::isError($result)) {
-                $affected_rows += $this->_affectedRows($connection, $result);;
-            }
-        }
-
-        if (!$in_transaction) {
-            if (PEAR::isError($result)) {
-                $this->rollback();
-            } else {
-                $result = $this->commit();
-            }
-        }
-
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-
-        return $affected_rows;
-    }
-
-    // }}}
-    // {{{ function &prepare($query, $types = null, $result_types = null, $lobs = array())
-
-    /**
-     * Prepares a query for multiple execution with execute().
-     * With some database backends, this is emulated.
-     * prepare() requires a generic query as string like
-     * 'INSERT INTO numbers VALUES(?,?)' or
-     * 'INSERT INTO numbers VALUES(:foo,:bar)'.
-     * The ? and :name and are placeholders which can be set using
-     * bindParam() and the query can be sent off using the execute() method.
-     * The allowed format for :name can be set with the 'bindname_format' option.
-     *
-     * @param   string  the query to prepare
-     * @param   mixed   array that contains the types of the placeholders
-     * @param   mixed   array that contains the types of the columns in
-     *                        the result set or MDB2_PREPARE_RESULT, if set to
-     *                        MDB2_PREPARE_MANIP the query is handled as a manipulation query
-     * @param   mixed   key (field) value (parameter) pair for all lob placeholders
-     *
-     * @return  mixed   resource handle for the prepared query on success, 
-     *                  a MDB2 error on failure
-     *
-     * @access  public
-     * @see     bindParam, execute
-     */
-    function &prepare($query, $types = null, $result_types = null, $lobs = array())
-    {
-        $is_manip = ($result_types === MDB2_PREPARE_MANIP);
-        $offset = $this->offset;
-        $limit = $this->limit;
-        $this->offset = $this->limit = 0;
-        $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
-        if ($result) {
-            if (PEAR::isError($result)) {
-                return $result;
-            }
-            $query = $result;
-        }
-        $placeholder_type_guess = $placeholder_type = null;
-        $question  = '?';
-        $colon     = ':';
-        $positions = array();
-        $position  = 0;
-        while ($position < strlen($query)) {
-            $q_position = strpos($query, $question, $position);
-            $c_position = strpos($query, $colon, $position);
-            if ($q_position && $c_position) {
-                $p_position = min($q_position, $c_position);
-            } elseif ($q_position) {
-                $p_position = $q_position;
-            } elseif ($c_position) {
-                $p_position = $c_position;
-            } else {
-                break;
-            }
-            if (is_null($placeholder_type)) {
-                $placeholder_type_guess = $query[$p_position];
-            }
-
-            $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
-            if (PEAR::isError($new_pos)) {
-                return $new_pos;
-            }
-            if ($new_pos != $position) {
-                $position = $new_pos;
-                continue; //evaluate again starting from the new position
-            }
-
-            if ($query[$position] == $placeholder_type_guess) {
-                if (is_null($placeholder_type)) {
-                    $placeholder_type = $query[$p_position];
-                    $question = $colon = $placeholder_type;
-                    if (!empty($types) && is_array($types)) {
-                        if ($placeholder_type == ':') {
-                            if (is_int(key($types))) {
-                                $types_tmp = $types;
-                                $types = array();
-                                $count = -1;
-                            }
-                        } else {
-                            $types = array_values($types);
-                        }
-                    }
-                }
-                if ($placeholder_type == ':') {
-                    $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
-                    $parameter = preg_replace($regexp, '\\1', $query);
-                    if ($parameter === '') {
-                        $err =$this->raiseError(MDB2_ERROR_SYNTAX, null, null,
-                            'named parameter name must match "bindname_format" option', __FUNCTION__);
-                        return $err;
-                    }
-                    $positions[$p_position] = $parameter;
-                    $query = substr_replace($query, '?', $position, strlen($parameter)+1);
-                    // use parameter name in type array
-                    if (isset($count) && isset($types_tmp[++$count])) {
-                        $types[$parameter] = $types_tmp[$count];
-                    }
-                } else {
-                    $positions[$p_position] = count($positions);
-                }
-                $position = $p_position + 1;
-            } else {
-                $position = $p_position;
-            }
-        }
-        $class_name = 'MDB2_Statement_'.$this->phptype;
-        $statement = null;
-        $obj = new $class_name($this, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
-        $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
-        return $obj;
-    }
-
-    // }}}
-    // {{{ function _skipDelimitedStrings($query, $position, $p_position)
-    
-    /**
-     * Utility method, used by prepare() to avoid replacing placeholders within delimited strings.
-     * Check if the placeholder is contained within a delimited string.
-     * If so, skip it and advance the position, otherwise return the current position,
-     * which is valid
-     *
-     * @param string $query
-     * @param integer $position current string cursor position
-     * @param integer $p_position placeholder position
-     *
-     * @return mixed integer $new_position on success
-     *               MDB2_Error on failure
-     *
-     * @access  protected
-     */
-    function _skipDelimitedStrings($query, $position, $p_position)
-    {
-        $ignores = $this->string_quoting;
-        $ignores[] = $this->identifier_quoting;
-        $ignores = array_merge($ignores, $this->sql_comments);
-        
-        foreach ($ignores as $ignore) {
-            if (!empty($ignore['start'])) {
-                if (is_int($start_quote = strpos($query, $ignore['start'], $position)) && $start_quote < $p_position) {
-                    $end_quote = $start_quote;
-                    do {
-                        if (!is_int($end_quote = strpos($query, $ignore['end'], $end_quote + 1))) {
-                            if ($ignore['end'] === "\n") {
-                                $end_quote = strlen($query) - 1;
-                            } else {
-                                $err =$this->raiseError(MDB2_ERROR_SYNTAX, null, null,
-                                    'query with an unterminated text string specified', __FUNCTION__);
-                                return $err;
-                            }
-                        }
-                    } while ($ignore['escape']
-                        && $end_quote-1 != $start_quote
-                        && $query[($end_quote - 1)] == $ignore['escape']
-                        && (   $ignore['escape_pattern'] !== $ignore['escape']
-                            || $query[($end_quote - 2)] != $ignore['escape'])
-                    );
-
-                    $position = $end_quote + 1;
-                    return $position;
-                }
-            }
-        }
-        return $position;
-    }
-    
-    // }}}
-    // {{{ function quote($value, $type = null, $quote = true)
-
-    /**
-     * Convert a text value into a DBMS specific format that is suitable to
-     * compose query statements.
-     *
-     * @param   string  text string value that is intended to be converted.
-     * @param   string  type to which the value should be converted to
-     * @param   bool    quote
-     * @param   bool    escape wildcards
-     *
-     * @return  string  text string that represents the given argument value in
-     *       a DBMS specific format.
-     *
-     * @access  public
-     */
-    function quote($value, $type = null, $quote = true, $escape_wildcards = false)
-    {
-        $result = $this->loadModule('Datatype', null, true);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-
-        return $this->datatype->quote($value, $type, $quote, $escape_wildcards);
-    }
-
-    // }}}
-    // {{{ function getDeclaration($type, $name, $field)
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare
-     * of the given type
-     *
-     * @param   string  type to which the value should be converted to
-     * @param   string  name the field to be declared.
-     * @param   string  definition of the field
-     *
-     * @return  string  DBMS specific SQL code portion that should be used to
-     *                 declare the specified field.
-     *
-     * @access  public
-     */
-    function getDeclaration($type, $name, $field)
-    {
-        $result = $this->loadModule('Datatype', null, true);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        return $this->datatype->getDeclaration($type, $name, $field);
-    }
-
-    // }}}
-    // {{{ function compareDefinition($current, $previous)
-
-    /**
-     * Obtain an array of changes that may need to applied
-     *
-     * @param   array   new definition
-     * @param   array   old definition
-     *
-     * @return  array   containing all changes that will need to be applied
-     *
-     * @access  public
-     */
-    function compareDefinition($current, $previous)
-    {
-        $result = $this->loadModule('Datatype', null, true);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        return $this->datatype->compareDefinition($current, $previous);
-    }
-
-    // }}}
-    // {{{ function supports($feature)
-
-    /**
-     * Tell whether a DB implementation or its backend extension
-     * supports a given feature.
-     *
-     * @param   string  name of the feature (see the MDB2 class doc)
-     *
-     * @return  bool|string if this DB implementation supports a given feature
-     *                      false means no, true means native,
-     *                      'emulated' means emulated
-     *
-     * @access  public
-     */
-    function supports($feature)
-    {
-        if (array_key_exists($feature, $this->supported)) {
-            return $this->supported[$feature];
-        }
-        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            "unknown support feature $feature", __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ function getSequenceName($sqn)
-
-    /**
-     * adds sequence name formatting to a sequence name
-     *
-     * @param   string  name of the sequence
-     *
-     * @return  string  formatted sequence name
-     *
-     * @access  public
-     */
-    function getSequenceName($sqn)
-    {
-        return sprintf($this->options['seqname_format'],
-            preg_replace('/[^a-z0-9_\-\$.]/i', '_', $sqn));
-    }
-
-    // }}}
-    // {{{ function getIndexName($idx)
-
-    /**
-     * adds index name formatting to a index name
-     *
-     * @param   string  name of the index
-     *
-     * @return  string  formatted index name
-     *
-     * @access  public
-     */
-    function getIndexName($idx)
-    {
-        return sprintf($this->options['idxname_format'],
-            preg_replace('/[^a-z0-9_\-\$.]/i', '_', $idx));
-    }
-
-    // }}}
-    // {{{ function nextID($seq_name, $ondemand = true)
-
-    /**
-     * Returns the next free id of a sequence
-     *
-     * @param   string  name of the sequence
-     * @param   bool    when true missing sequences are automatic created
-     *
-     * @return  mixed   MDB2 Error Object or id
-     *
-     * @access  public
-     */
-    function nextID($seq_name, $ondemand = true)
-    {
-        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ function lastInsertID($table = null, $field = null)
-
-    /**
-     * Returns the autoincrement ID if supported or $id or fetches the current
-     * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
-     *
-     * @param   string  name of the table into which a new row was inserted
-     * @param   string  name of the field into which a new row was inserted
-     *
-     * @return  mixed   MDB2 Error Object or id
-     *
-     * @access  public
-     */
-    function lastInsertID($table = null, $field = null)
-    {
-        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ function currID($seq_name)
-
-    /**
-     * Returns the current id of a sequence
-     *
-     * @param   string  name of the sequence
-     *
-     * @return  mixed   MDB2 Error Object or id
-     *
-     * @access  public
-     */
-    function currID($seq_name)
-    {
-        $this->warnings[] = 'database does not support getting current
-            sequence value, the sequence value was incremented';
-        return $this->nextID($seq_name);
-    }
-
-    // }}}
-    // {{{ function queryOne($query, $type = null, $colnum = 0)
-
-    /**
-     * Execute the specified query, fetch the value from the first column of
-     * the first row of the result set and then frees
-     * the result set.
-     *
-     * @param string $query  the SELECT query statement to be executed.
-     * @param string $type   optional argument that specifies the expected
-     *                       datatype of the result set field, so that an eventual
-     *                       conversion may be performed. The default datatype is
-     *                       text, meaning that no conversion is performed
-     * @param mixed  $colnum the column number (or name) to fetch
-     *
-     * @return  mixed   MDB2_OK or field value on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function queryOne($query, $type = null, $colnum = 0)
-    {
-        $result = $this->query($query, $type);
-        if (!MDB2::isResultCommon($result)) {
-            return $result;
-        }
-
-        $one = $result->fetchOne($colnum);
-        $result->free();
-        return $one;
-    }
-
-    // }}}
-    // {{{ function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
-
-    /**
-     * Execute the specified query, fetch the values from the first
-     * row of the result set into an array and then frees
-     * the result set.
-     *
-     * @param   string  the SELECT query statement to be executed.
-     * @param   array   optional array argument that specifies a list of
-     *       expected datatypes of the result set columns, so that the eventual
-     *       conversions may be performed. The default list of datatypes is
-     *       empty, meaning that no conversion is performed.
-     * @param   int     how the array data should be indexed
-     *
-     * @return  mixed   MDB2_OK or data array on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
-    {
-        $result = $this->query($query, $types);
-        if (!MDB2::isResultCommon($result)) {
-            return $result;
-        }
-
-        $row = $result->fetchRow($fetchmode);
-        $result->free();
-        return $row;
-    }
-
-    // }}}
-    // {{{ function queryCol($query, $type = null, $colnum = 0)
-
-    /**
-     * Execute the specified query, fetch the value from the first column of
-     * each row of the result set into an array and then frees the result set.
-     *
-     * @param string $query  the SELECT query statement to be executed.
-     * @param string $type   optional argument that specifies the expected
-     *                       datatype of the result set field, so that an eventual
-     *                       conversion may be performed. The default datatype is text,
-     *                       meaning that no conversion is performed
-     * @param mixed  $colnum the column number (or name) to fetch
-     *
-     * @return  mixed   MDB2_OK or data array on success, a MDB2 error on failure
-     * @access  public
-     */
-    function queryCol($query, $type = null, $colnum = 0)
-    {
-        $result = $this->query($query, $type);
-        if (!MDB2::isResultCommon($result)) {
-            return $result;
-        }
-
-        $col = $result->fetchCol($colnum);
-        $result->free();
-        return $col;
-    }
-
-    // }}}
-    // {{{ function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
-
-    /**
-     * Execute the specified query, fetch all the rows of the result set into
-     * a two dimensional array and then frees the result set.
-     *
-     * @param   string  the SELECT query statement to be executed.
-     * @param   array   optional array argument that specifies a list of
-     *       expected datatypes of the result set columns, so that the eventual
-     *       conversions may be performed. The default list of datatypes is
-     *       empty, meaning that no conversion is performed.
-     * @param   int     how the array data should be indexed
-     * @param   bool    if set to true, the $all will have the first
-     *       column as its first dimension
-     * @param   bool    used only when the query returns exactly
-     *       two columns. If true, the values of the returned array will be
-     *       one-element arrays instead of scalars.
-     * @param   bool    if true, the values of the returned array is
-     *       wrapped in another array.  If the same key value (in the first
-     *       column) repeats itself, the values will be appended to this array
-     *       instead of overwriting the existing values.
-     *
-     * @return  mixed   MDB2_OK or data array on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT,
-        $rekey = false, $force_array = false, $group = false)
-    {
-        $result = $this->query($query, $types);
-        if (!MDB2::isResultCommon($result)) {
-            return $result;
-        }
-
-        $all = $result->fetchAll($fetchmode, $rekey, $force_array, $group);
-        $result->free();
-        return $all;
-    }
-
-    // }}}
-}
-
-// }}}
-// {{{ class MDB2_Result
-
-/**
- * The dummy class that all user space result classes should extend from
- *
- * @package     MDB2
- * @category    Database
- * @author      Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Result
-{
-}
-
-// }}}
-// {{{ class MDB2_Result_Common extends MDB2_Result
-
-/**
- * The common result class for MDB2 result objects
- *
- * @package     MDB2
- * @category    Database
- * @author      Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Result_Common extends MDB2_Result
-{
-    // {{{ Variables (Properties)
-
-    var $db;
-    var $result;
-    var $rownum = -1;
-    var $types = array();
-    var $values = array();
-    var $offset;
-    var $offset_count = 0;
-    var $limit;
-    var $column_names;
-
-    // }}}
-    // {{{ constructor: function __construct(&$db, &$result, $limit = 0, $offset = 0)
-
-    /**
-     * Constructor
-     */
-    function __construct(&$db, &$result, $limit = 0, $offset = 0)
-    {
-        $this->db =$db;
-        $this->result =$result;
-        $this->offset = $offset;
-        $this->limit = max(0, $limit - 1);
-    }
-
-
-    // }}}
-    // {{{ function setResultTypes($types)
-
-    /**
-     * Define the list of types to be associated with the columns of a given
-     * result set.
-     *
-     * This function may be called before invoking fetchRow(), fetchOne(),
-     * fetchCol() and fetchAll() so that the necessary data type
-     * conversions are performed on the data to be retrieved by them. If this
-     * function is not called, the type of all result set columns is assumed
-     * to be text, thus leading to not perform any conversions.
-     *
-     * @param   array   variable that lists the
-     *       data types to be expected in the result set columns. If this array
-     *       contains less types than the number of columns that are returned
-     *       in the result set, the remaining columns are assumed to be of the
-     *       type text. Currently, the types clob and blob are not fully
-     *       supported.
-     *
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function setResultTypes($types)
-    {
-        $load = $this->db->loadModule('Datatype', null, true);
-        if (PEAR::isError($load)) {
-            return $load;
-        }
-        $types = $this->db->datatype->checkResultTypes($types);
-        if (PEAR::isError($types)) {
-            return $types;
-        }
-        $this->types = $types;
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ function seek($rownum = 0)
-
-    /**
-     * Seek to a specific row in a result set
-     *
-     * @param   int     number of the row where the data can be found
-     *
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function seek($rownum = 0)
-    {
-        $target_rownum = $rownum - 1;
-        if ($this->rownum > $target_rownum) {
-            return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'seeking to previous rows not implemented', __FUNCTION__);
-        }
-        while ($this->rownum < $target_rownum) {
-            $this->fetchRow();
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
-
-    /**
-     * Fetch and return a row of data
-     *
-     * @param   int     how the array data should be indexed
-     * @param   int     number of the row where the data can be found
-     *
-     * @return  int     data array on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
-    {
-        $err =$this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-        return $err;
-    }
-
-    // }}}
-    // {{{ function fetchOne($colnum = 0)
-
-    /**
-     * fetch single column from the next row from a result set
-     *
-     * @param int|string the column number (or name) to fetch
-     * @param int        number of the row where the data can be found
-     *
-     * @return string data on success, a MDB2 error on failure
-     * @access  public
-     */
-    function fetchOne($colnum = 0, $rownum = null)
-    {
-        $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
-        $row = $this->fetchRow($fetchmode, $rownum);
-        if (!is_array($row) || PEAR::isError($row)) {
-            return $row;
-        }
-        if (!array_key_exists($colnum, $row)) {
-            return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
-                'column is not defined in the result set: '.$colnum, __FUNCTION__);
-        }
-        return $row[$colnum];
-    }
-
-    // }}}
-    // {{{ function fetchCol($colnum = 0)
-
-    /**
-     * Fetch and return a column from the current row pointer position
-     *
-     * @param int|string the column number (or name) to fetch
-     *
-     * @return  mixed data array on success, a MDB2 error on failure
-     * @access  public
-     */
-    function fetchCol($colnum = 0)
-    {
-        $column = array();
-        $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
-        $row = $this->fetchRow($fetchmode);
-        if (is_array($row)) {
-            if (!array_key_exists($colnum, $row)) {
-                return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
-                    'column is not defined in the result set: '.$colnum, __FUNCTION__);
-            }
-            do {
-                $column[] = $row[$colnum];
-            } while (is_array($row = $this->fetchRow($fetchmode)));
-        }
-        if (PEAR::isError($row)) {
-            return $row;
-        }
-        return $column;
-    }
-
-    // }}}
-    // {{{ function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
-
-    /**
-     * Fetch and return all rows from the current row pointer position
-     *
-     * @param   int     $fetchmode  the fetch mode to use:
-     *                            + MDB2_FETCHMODE_ORDERED
-     *                            + MDB2_FETCHMODE_ASSOC
-     *                            + MDB2_FETCHMODE_ORDERED | MDB2_FETCHMODE_FLIPPED
-     *                            + MDB2_FETCHMODE_ASSOC | MDB2_FETCHMODE_FLIPPED
-     * @param   bool    if set to true, the $all will have the first
-     *       column as its first dimension
-     * @param   bool    used only when the query returns exactly
-     *       two columns. If true, the values of the returned array will be
-     *       one-element arrays instead of scalars.
-     * @param   bool    if true, the values of the returned array is
-     *       wrapped in another array.  If the same key value (in the first
-     *       column) repeats itself, the values will be appended to this array
-     *       instead of overwriting the existing values.
-     *
-     * @return  mixed   data array on success, a MDB2 error on failure
-     *
-     * @access  public
-     * @see     getAssoc()
-     */
-    function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false,
-        $force_array = false, $group = false)
-    {
-        $all = array();
-        $row = $this->fetchRow($fetchmode);
-        if (PEAR::isError($row)) {
-            return $row;
-        } elseif (!$row) {
-            return $all;
-        }
-
-        $shift_array = $rekey ? false : null;
-        if (!is_null($shift_array)) {
-            if (is_object($row)) {
-                $colnum = count(get_object_vars($row));
-            } else {
-                $colnum = count($row);
-            }
-            if ($colnum < 2) {
-                return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
-                    'rekey feature requires atleast 2 column', __FUNCTION__);
-            }
-            $shift_array = (!$force_array && $colnum == 2);
-        }
-
-        if ($rekey) {
-            do {
-                if (is_object($row)) {
-                    $arr = get_object_vars($row);
-                    $key = reset($arr);
-                    unset($row->{$key});
-                } else {
-                    if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
-                        $key = reset($row);
-                        unset($row[key($row)]);
-                    } else {
-                        $key = array_shift($row);
-                    }
-                    if ($shift_array) {
-                        $row = array_shift($row);
-                    }
-                }
-                if ($group) {
-                    $all[$key][] = $row;
-                } else {
-                    $all[$key] = $row;
-                }
-            } while (($row = $this->fetchRow($fetchmode)));
-        } elseif ($fetchmode & MDB2_FETCHMODE_FLIPPED) {
-            do {
-                foreach ($row as $key => $val) {
-                    $all[$key][] = $val;
-                }
-            } while (($row = $this->fetchRow($fetchmode)));
-        } else {
-            do {
-                $all[] = $row;
-            } while (($row = $this->fetchRow($fetchmode)));
-        }
-
-        return $all;
-    }
-
-    // }}}
-    // {{{ function rowCount()
-    /**
-     * Returns the actual row number that was last fetched (count from 0)
-     * @return  int
-     *
-     * @access  public
-     */
-    function rowCount()
-    {
-        return $this->rownum + 1;
-    }
-
-    // }}}
-    // {{{ function numRows()
-
-    /**
-     * Returns the number of rows in a result object
-     *
-     * @return  mixed   MDB2 Error Object or the number of rows
-     *
-     * @access  public
-     */
-    function numRows()
-    {
-        return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ function nextResult()
-
-    /**
-     * Move the internal result pointer to the next available result
-     *
-     * @return  true on success, false if there is no more result set or an error object on failure
-     *
-     * @access  public
-     */
-    function nextResult()
-    {
-        return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ function getColumnNames()
-
-    /**
-     * Retrieve the names of columns returned by the DBMS in a query result or
-     * from the cache.
-     *
-     * @param   bool    If set to true the values are the column names,
-     *                  otherwise the names of the columns are the keys.
-     * @return  mixed   Array variable that holds the names of columns or an
-     *                  MDB2 error on failure.
-     *                  Some DBMS may not return any columns when the result set
-     *                  does not contain any rows.
-     *
-     * @access  public
-     */
-    function getColumnNames($flip = false)
-    {
-        if (!isset($this->column_names)) {
-            $result = $this->_getColumnNames();
-            if (PEAR::isError($result)) {
-                return $result;
-            }
-            $this->column_names = $result;
-        }
-        if ($flip) {
-            return array_flip($this->column_names);
-        }
-        return $this->column_names;
-    }
-
-    // }}}
-    // {{{ function _getColumnNames()
-
-    /**
-     * Retrieve the names of columns returned by the DBMS in a query result.
-     *
-     * @return  mixed   Array variable that holds the names of columns as keys
-     *                  or an MDB2 error on failure.
-     *                  Some DBMS may not return any columns when the result set
-     *                  does not contain any rows.
-     *
-     * @access  private
-     */
-    function _getColumnNames()
-    {
-        return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ function numCols()
-
-    /**
-     * Count the number of columns returned by the DBMS in a query result.
-     *
-     * @return  mixed   integer value with the number of columns, a MDB2 error
-     *       on failure
-     *
-     * @access  public
-     */
-    function numCols()
-    {
-        return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ function getResource()
-
-    /**
-     * return the resource associated with the result object
-     *
-     * @return  resource
-     *
-     * @access  public
-     */
-    function getResource()
-    {
-        return $this->result;
-    }
-
-    // }}}
-    // {{{ function bindColumn($column, &$value, $type = null)
-
-    /**
-     * Set bind variable to a column.
-     *
-     * @param   int     column number or name
-     * @param   mixed   variable reference
-     * @param   string  specifies the type of the field
-     *
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function bindColumn($column, &$value, $type = null)
-    {
-        if (!is_numeric($column)) {
-            $column_names = $this->getColumnNames();
-            if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-                if ($this->db->options['field_case'] == CASE_LOWER) {
-                    $column = strtolower($column);
-                } else {
-                    $column = strtoupper($column);
-                }
-            }
-            $column = $column_names[$column];
-        }
-        $this->values[$column] =$value;
-        if (!is_null($type)) {
-            $this->types[$column] = $type;
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ function _assignBindColumns($row)
-
-    /**
-     * Bind a variable to a value in the result row.
-     *
-     * @param   array   row data
-     *
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  private
-     */
-    function _assignBindColumns($row)
-    {
-        $row = array_values($row);
-        foreach ($row as $column => $value) {
-            if (array_key_exists($column, $this->values)) {
-                $this->values[$column] = $value;
-            }
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ function free()
-
-    /**
-     * Free the internal resources associated with result.
-     *
-     * @return  bool    true on success, false if result is invalid
-     *
-     * @access  public
-     */
-    function free()
-    {
-        $this->result = false;
-        return MDB2_OK;
-    }
-
-    // }}}
-}
-
-// }}}
-// {{{ class MDB2_Row
-
-/**
- * The simple class that accepts row data as an array
- *
- * @package     MDB2
- * @category    Database
- * @author      Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Row
-{
-    // {{{ constructor: function __construct(&$row)
-
-    /**
-     * constructor
-     *
-     * @param   resource    row data as array
-     */
-    function __construct(&$row)
-    {
-        foreach ($row as $key => $value) {
-            $this->$key = &$row[$key];
-        }
-    }
-}
-
-// }}}
-// {{{ class MDB2_Statement_Common
-
-/**
- * The common statement class for MDB2 statement objects
- *
- * @package     MDB2
- * @category    Database
- * @author      Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Statement_Common
-{
-    // {{{ Variables (Properties)
-
-    var $db;
-    var $statement;
-    var $query;
-    var $result_types;
-    var $types;
-    var $values = array();
-    var $limit;
-    var $offset;
-    var $is_manip;
-
-    // }}}
-    // {{{ constructor: function __construct(&$db, &$statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
-
-    /**
-     * Constructor
-     */
-    function __construct(&$db, &$statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
-    {
-        $this->db =$db;
-        $this->statement =$statement;
-        $this->positions = $positions;
-        $this->query = $query;
-        $this->types = (array)$types;
-        $this->result_types = (array)$result_types;
-        $this->limit = $limit;
-        $this->is_manip = $is_manip;
-        $this->offset = $offset;
-    }
-
-
-    // }}}
-    // {{{ function bindValue($parameter, &$value, $type = null)
-
-    /**
-     * Set the value of a parameter of a prepared query.
-     *
-     * @param   int     the order number of the parameter in the query
-     *       statement. The order number of the first parameter is 1.
-     * @param   mixed   value that is meant to be assigned to specified
-     *       parameter. The type of the value depends on the $type argument.
-     * @param   string  specifies the type of the field
-     *
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function bindValue($parameter, $value, $type = null)
-    {
-        if (!is_numeric($parameter)) {
-            $parameter = preg_replace('/^:(.*)$/', '\\1', $parameter);
-        }
-        if (!in_array($parameter, $this->positions)) {
-            return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
-        }
-        $this->values[$parameter] = $value;
-        if (!is_null($type)) {
-            $this->types[$parameter] = $type;
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ function bindValueArray($values, $types = null)
-
-    /**
-     * Set the values of multiple a parameter of a prepared query in bulk.
-     *
-     * @param   array   specifies all necessary information
-     *       for bindValue() the array elements must use keys corresponding to
-     *       the number of the position of the parameter.
-     * @param   array   specifies the types of the fields
-     *
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     * @see     bindParam()
-     */
-    function bindValueArray($values, $types = null)
-    {
-        $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
-        $parameters = array_keys($values);
-        foreach ($parameters as $key => $parameter) {
-            $this->db->pushErrorHandling(PEAR_ERROR_RETURN);
-            $this->db->expectError(MDB2_ERROR_NOT_FOUND);
-            $err = $this->bindValue($parameter, $values[$parameter], $types[$key]);
-            $this->db->popExpect();
-            $this->db->popErrorHandling();
-            if (PEAR::isError($err)) {
-                if ($err->getCode() == MDB2_ERROR_NOT_FOUND) {
-                    //ignore (extra value for missing placeholder)
-                    continue;
-                }
-                return $err;
-            }
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ function bindParam($parameter, &$value, $type = null)
-
-    /**
-     * Bind a variable to a parameter of a prepared query.
-     *
-     * @param   int     the order number of the parameter in the query
-     *       statement. The order number of the first parameter is 1.
-     * @param   mixed   variable that is meant to be bound to specified
-     *       parameter. The type of the value depends on the $type argument.
-     * @param   string  specifies the type of the field
-     *
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function bindParam($parameter, &$value, $type = null)
-    {
-        if (!is_numeric($parameter)) {
-            $parameter = preg_replace('/^:(.*)$/', '\\1', $parameter);
-        }
-        if (!in_array($parameter, $this->positions)) {
-            return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
-        }
-        $this->values[$parameter] =$value;
-        if (!is_null($type)) {
-            $this->types[$parameter] = $type;
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ function bindParamArray(&$values, $types = null)
-
-    /**
-     * Bind the variables of multiple a parameter of a prepared query in bulk.
-     *
-     * @param   array   specifies all necessary information
-     *       for bindParam() the array elements must use keys corresponding to
-     *       the number of the position of the parameter.
-     * @param   array   specifies the types of the fields
-     *
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     * @see     bindParam()
-     */
-    function bindParamArray(&$values, $types = null)
-    {
-        $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
-        $parameters = array_keys($values);
-        foreach ($parameters as $key => $parameter) {
-            $err = $this->bindParam($parameter, $values[$parameter], $types[$key]);
-            if (PEAR::isError($err)) {
-                return $err;
-            }
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ function &execute($values = null, $result_class = true, $result_wrap_class = false)
-
-    /**
-     * Execute a prepared query statement.
-     *
-     * @param array specifies all necessary information
-     *              for bindParam() the array elements must use keys corresponding
-     *              to the number of the position of the parameter.
-     * @param mixed specifies which result class to use
-     * @param mixed specifies which class to wrap results in
-     *
-     * @return mixed MDB2_Result or integer (affected rows) on success,
-     *               a MDB2 error on failure
-     * @access public
-     */
-    function &execute($values = null, $result_class = true, $result_wrap_class = false)
-    {
-        if (is_null($this->positions)) {
-            return $this->db->raiseError(MDB2_ERROR, null, null,
-                'Prepared statement has already been freed', __FUNCTION__);
-        }
-
-        $values = (array)$values;
-        if (!empty($values)) {
-            $err = $this->bindValueArray($values);
-            if (PEAR::isError($err)) {
-                return $this->db->raiseError(MDB2_ERROR, null, null,
-                                            'Binding Values failed with message: ' . $err->getMessage(), __FUNCTION__);
-            }
-        }
-        $result =$this->_execute($result_class, $result_wrap_class);
-        return $result;
-    }
-
-    // }}}
-    // {{{ function &_execute($result_class = true, $result_wrap_class = false)
-
-    /**
-     * Execute a prepared query statement helper method.
-     *
-     * @param   mixed   specifies which result class to use
-     * @param   mixed   specifies which class to wrap results in
-     *
-     * @return mixed MDB2_Result or integer (affected rows) on success,
-     *               a MDB2 error on failure
-     * @access  private
-     */
-    function &_execute($result_class = true, $result_wrap_class = false)
-    {
-        $this->last_query = $this->query;
-        $query = '';
-        $last_position = 0;
-        foreach ($this->positions as $current_position => $parameter) {
-            if (!array_key_exists($parameter, $this->values)) {
-                return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                    'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
-            }
-            $value = $this->values[$parameter];
-            $query.= substr($this->query, $last_position, $current_position - $last_position);
-            if (!isset($value)) {
-                $value_quoted = 'NULL';
-            } else {
-                $type = !empty($this->types[$parameter]) ? $this->types[$parameter] : null;
-                $value_quoted = $this->db->quote($value, $type);
-                if (PEAR::isError($value_quoted)) {
-                    return $value_quoted;
-                }
-            }
-            $query.= $value_quoted;
-            $last_position = $current_position + 1;
-        }
-        $query.= substr($this->query, $last_position);
-
-        $this->db->offset = $this->offset;
-        $this->db->limit = $this->limit;
-        if ($this->is_manip) {
-            $result = $this->db->exec($query);
-        } else {
-            $result =$this->db->query($query, $this->result_types, $result_class, $result_wrap_class);
-        }
-        return $result;
-    }
-
-    // }}}
-    // {{{ function free()
-
-    /**
-     * Release resources allocated for the specified prepared query.
-     *
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function free()
-    {
-        if (is_null($this->positions)) {
-            return $this->db->raiseError(MDB2_ERROR, null, null,
-                'Prepared statement has already been freed', __FUNCTION__);
-        }
-
-        $this->statement = null;
-        $this->positions = null;
-        $this->query = null;
-        $this->types = null;
-        $this->result_types = null;
-        $this->limit = null;
-        $this->is_manip = null;
-        $this->offset = null;
-        $this->values = null;
-
-        return MDB2_OK;
-    }
-
-    // }}}
-}
-
-// }}}
-// {{{ class MDB2_Module_Common
-
-/**
- * The common modules class for MDB2 module objects
- *
- * @package     MDB2
- * @category    Database
- * @author      Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Module_Common
-{
-    // {{{ Variables (Properties)
-
-    /**
-     * contains the key to the global MDB2 instance array of the associated
-     * MDB2 instance
-     *
-     * @var     int
-     * @access  protected
-     */
-    var $db_index;
-
-    // }}}
-    // {{{ constructor: function __construct($db_index)
-
-    /**
-     * Constructor
-     */
-    function __construct($db_index)
-    {
-        $this->db_index = $db_index;
-    }
-
-    // }}}
-    // {{{ function &getDBInstance()
-
-    /**
-     * Get the instance of MDB2 associated with the module instance
-     *
-     * @return  object  MDB2 instance or a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function getDBInstance()
-    {
-        if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
-            $result =$GLOBALS['_MDB2_databases'][$this->db_index];
-        } else {
-            $result =$this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                'could not find MDB2 instance');
-        }
-        return $result;
-    }
-
-    // }}}
-}
-
-// }}}
-// {{{ function MDB2_closeOpenTransactions()
-
-/**
- * Close any open transactions form persistent connections
- *
- * @return  void
- *
- * @access  public
- */
-
-function MDB2_closeOpenTransactions()
-{
-    reset($GLOBALS['_MDB2_databases']);
-    while (next($GLOBALS['_MDB2_databases'])) {
-        $key = key($GLOBALS['_MDB2_databases']);
-        if ($GLOBALS['_MDB2_databases'][$key]->opened_persistent
-            && $GLOBALS['_MDB2_databases'][$key]->in_transaction
-        ) {
-            $GLOBALS['_MDB2_databases'][$key]->rollback();
-        }
-    }
-}
-
-// }}}
-// {{{ function MDB2_defaultDebugOutput(&$db, $scope, $message, $is_manip = null)
-
-/**
- * default debug output handler
- *
- * @param   object  reference to an MDB2 database object
- * @param   string  usually the method name that triggered the debug call:
- *                  for example 'query', 'prepare', 'execute', 'parameters',
- *                  'beginTransaction', 'commit', 'rollback'
- * @param   string  message that should be appended to the debug variable
- * @param   array   contains context information about the debug() call
- *                  common keys are: is_manip, time, result etc.
- *
- * @return  void|string optionally return a modified message, this allows
- *                      rewriting a query before being issued or prepared
- *
- * @access  public
- */
-function MDB2_defaultDebugOutput(&$db, $scope, $message, $context = array())
-{
-    $db->debug_output.= $scope.'('.$db->db_index.'): ';
-    $db->debug_output.= $message.$db->getOption('log_line_break');
-    return $message;
-}
-
-// }}}
-?>
+<?php\r
+// vim: set et ts=4 sw=4 fdm=marker:\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: MDB2.php 295587 2010-02-28 17:16:38Z quipo $\r
+//\r
+\r
+/**\r
+ * @package     MDB2\r
+ * @category    Database\r
+ * @author      Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+\r
+require_once 'PEAR.php';\r
+\r
+// {{{ Error constants\r
+\r
+/**\r
+ * The method mapErrorCode in each MDB2_dbtype implementation maps\r
+ * native error codes to one of these.\r
+ *\r
+ * If you add an error code here, make sure you also add a textual\r
+ * version of it in MDB2::errorMessage().\r
+ */\r
+\r
+define('MDB2_OK',                      true);\r
+define('MDB2_ERROR',                     -1);\r
+define('MDB2_ERROR_SYNTAX',              -2);\r
+define('MDB2_ERROR_CONSTRAINT',          -3);\r
+define('MDB2_ERROR_NOT_FOUND',           -4);\r
+define('MDB2_ERROR_ALREADY_EXISTS',      -5);\r
+define('MDB2_ERROR_UNSUPPORTED',         -6);\r
+define('MDB2_ERROR_MISMATCH',            -7);\r
+define('MDB2_ERROR_INVALID',             -8);\r
+define('MDB2_ERROR_NOT_CAPABLE',         -9);\r
+define('MDB2_ERROR_TRUNCATED',          -10);\r
+define('MDB2_ERROR_INVALID_NUMBER',     -11);\r
+define('MDB2_ERROR_INVALID_DATE',       -12);\r
+define('MDB2_ERROR_DIVZERO',            -13);\r
+define('MDB2_ERROR_NODBSELECTED',       -14);\r
+define('MDB2_ERROR_CANNOT_CREATE',      -15);\r
+define('MDB2_ERROR_CANNOT_DELETE',      -16);\r
+define('MDB2_ERROR_CANNOT_DROP',        -17);\r
+define('MDB2_ERROR_NOSUCHTABLE',        -18);\r
+define('MDB2_ERROR_NOSUCHFIELD',        -19);\r
+define('MDB2_ERROR_NEED_MORE_DATA',     -20);\r
+define('MDB2_ERROR_NOT_LOCKED',         -21);\r
+define('MDB2_ERROR_VALUE_COUNT_ON_ROW', -22);\r
+define('MDB2_ERROR_INVALID_DSN',        -23);\r
+define('MDB2_ERROR_CONNECT_FAILED',     -24);\r
+define('MDB2_ERROR_EXTENSION_NOT_FOUND',-25);\r
+define('MDB2_ERROR_NOSUCHDB',           -26);\r
+define('MDB2_ERROR_ACCESS_VIOLATION',   -27);\r
+define('MDB2_ERROR_CANNOT_REPLACE',     -28);\r
+define('MDB2_ERROR_CONSTRAINT_NOT_NULL',-29);\r
+define('MDB2_ERROR_DEADLOCK',           -30);\r
+define('MDB2_ERROR_CANNOT_ALTER',       -31);\r
+define('MDB2_ERROR_MANAGER',            -32);\r
+define('MDB2_ERROR_MANAGER_PARSE',      -33);\r
+define('MDB2_ERROR_LOADMODULE',         -34);\r
+define('MDB2_ERROR_INSUFFICIENT_DATA',  -35);\r
+define('MDB2_ERROR_NO_PERMISSION',      -36);\r
+define('MDB2_ERROR_DISCONNECT_FAILED',  -37);\r
+\r
+// }}}\r
+// {{{ Verbose constants\r
+/**\r
+ * These are just helper constants to more verbosely express parameters to prepare()\r
+ */\r
+\r
+define('MDB2_PREPARE_MANIP', false);\r
+define('MDB2_PREPARE_RESULT', null);\r
+\r
+// }}}\r
+// {{{ Fetchmode constants\r
+\r
+/**\r
+ * This is a special constant that tells MDB2 the user hasn't specified\r
+ * any particular get mode, so the default should be used.\r
+ */\r
+define('MDB2_FETCHMODE_DEFAULT', 0);\r
+\r
+/**\r
+ * Column data indexed by numbers, ordered from 0 and up\r
+ */\r
+define('MDB2_FETCHMODE_ORDERED', 1);\r
+\r
+/**\r
+ * Column data indexed by column names\r
+ */\r
+define('MDB2_FETCHMODE_ASSOC', 2);\r
+\r
+/**\r
+ * Column data as object properties\r
+ */\r
+define('MDB2_FETCHMODE_OBJECT', 3);\r
+\r
+/**\r
+ * For multi-dimensional results: normally the first level of arrays\r
+ * is the row number, and the second level indexed by column number or name.\r
+ * MDB2_FETCHMODE_FLIPPED switches this order, so the first level of arrays\r
+ * is the column name, and the second level the row number.\r
+ */\r
+define('MDB2_FETCHMODE_FLIPPED', 4);\r
+\r
+// }}}\r
+// {{{ Portability mode constants\r
+\r
+/**\r
+ * Portability: turn off all portability features.\r
+ * @see MDB2_Driver_Common::setOption()\r
+ */\r
+define('MDB2_PORTABILITY_NONE', 0);\r
+\r
+/**\r
+ * Portability: convert names of tables and fields to case defined in the\r
+ * "field_case" option when using the query*(), fetch*() and tableInfo() methods.\r
+ * @see MDB2_Driver_Common::setOption()\r
+ */\r
+define('MDB2_PORTABILITY_FIX_CASE', 1);\r
+\r
+/**\r
+ * Portability: right trim the data output by query*() and fetch*().\r
+ * @see MDB2_Driver_Common::setOption()\r
+ */\r
+define('MDB2_PORTABILITY_RTRIM', 2);\r
+\r
+/**\r
+ * Portability: force reporting the number of rows deleted.\r
+ * @see MDB2_Driver_Common::setOption()\r
+ */\r
+define('MDB2_PORTABILITY_DELETE_COUNT', 4);\r
+\r
+/**\r
+ * Portability: not needed in MDB2 (just left here for compatibility to DB)\r
+ * @see MDB2_Driver_Common::setOption()\r
+ */\r
+define('MDB2_PORTABILITY_NUMROWS', 8);\r
+\r
+/**\r
+ * Portability: makes certain error messages in certain drivers compatible\r
+ * with those from other DBMS's.\r
+ *\r
+ * + mysql, mysqli:  change unique/primary key constraints\r
+ *   MDB2_ERROR_ALREADY_EXISTS -> MDB2_ERROR_CONSTRAINT\r
+ *\r
+ * + odbc(access):  MS's ODBC driver reports 'no such field' as code\r
+ *   07001, which means 'too few parameters.'  When this option is on\r
+ *   that code gets mapped to MDB2_ERROR_NOSUCHFIELD.\r
+ *\r
+ * @see MDB2_Driver_Common::setOption()\r
+ */\r
+define('MDB2_PORTABILITY_ERRORS', 16);\r
+\r
+/**\r
+ * Portability: convert empty values to null strings in data output by\r
+ * query*() and fetch*().\r
+ * @see MDB2_Driver_Common::setOption()\r
+ */\r
+define('MDB2_PORTABILITY_EMPTY_TO_NULL', 32);\r
+\r
+/**\r
+ * Portability: removes database/table qualifiers from associative indexes\r
+ * @see MDB2_Driver_Common::setOption()\r
+ */\r
+define('MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES', 64);\r
+\r
+/**\r
+ * Portability: turn on all portability features.\r
+ * @see MDB2_Driver_Common::setOption()\r
+ */\r
+define('MDB2_PORTABILITY_ALL', 127);\r
+\r
+// }}}\r
+// {{{ Globals for class instance tracking\r
+\r
+/**\r
+ * These are global variables that are used to track the various class instances\r
+ */\r
+\r
+$GLOBALS['_MDB2_databases'] = array();\r
+$GLOBALS['_MDB2_dsninfo_default'] = array(\r
+    'phptype'  => false,\r
+    'dbsyntax' => false,\r
+    'username' => false,\r
+    'password' => false,\r
+    'protocol' => false,\r
+    'hostspec' => false,\r
+    'port'     => false,\r
+    'socket'   => false,\r
+    'database' => false,\r
+    'mode'     => false,\r
+);\r
+\r
+// }}}\r
+// {{{ class MDB2\r
+\r
+/**\r
+ * The main 'MDB2' class is simply a container class with some static\r
+ * methods for creating DB objects as well as some utility functions\r
+ * common to all parts of DB.\r
+ *\r
+ * The object model of MDB2 is as follows (indentation means inheritance):\r
+ *\r
+ * MDB2          The main MDB2 class.  This is simply a utility class\r
+ *              with some 'static' methods for creating MDB2 objects as\r
+ *              well as common utility functions for other MDB2 classes.\r
+ *\r
+ * MDB2_Driver_Common   The base for each MDB2 implementation.  Provides default\r
+ * |            implementations (in OO lingo virtual methods) for\r
+ * |            the actual DB implementations as well as a bunch of\r
+ * |            query utility functions.\r
+ * |\r
+ * +-MDB2_Driver_mysql  The MDB2 implementation for MySQL. Inherits MDB2_Driver_Common.\r
+ *              When calling MDB2::factory or MDB2::connect for MySQL\r
+ *              connections, the object returned is an instance of this\r
+ *              class.\r
+ * +-MDB2_Driver_pgsql  The MDB2 implementation for PostGreSQL. Inherits MDB2_Driver_Common.\r
+ *              When calling MDB2::factory or MDB2::connect for PostGreSQL\r
+ *              connections, the object returned is an instance of this\r
+ *              class.\r
+ *\r
+ * @package     MDB2\r
+ * @category    Database\r
+ * @author      Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2\r
+{\r
+    // {{{ function setOptions($db, $options)\r
+\r
+    /**\r
+     * set option array   in an exiting database object\r
+     *\r
+     * @param   MDB2_Driver_Common  MDB2 object\r
+     * @param   array   An associative array of option names and their values.\r
+     *\r
+     * @return mixed   MDB2_OK or a PEAR Error object\r
+     *\r
+     * @access  public\r
+     */\r
+    static function setOptions($db, $options)\r
+    {\r
+        if (is_array($options)) {\r
+            foreach ($options as $option => $value) {\r
+                $test = $db->setOption($option, $value);\r
+                if (PEAR::isError($test)) {\r
+                    return $test;\r
+                }\r
+            }\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function classExists($classname)\r
+\r
+    /**\r
+     * Checks if a class exists without triggering __autoload\r
+     *\r
+     * @param   string  classname\r
+     *\r
+     * @return  bool    true success and false on error\r
+     * @static\r
+     * @access  public\r
+     */\r
+    static function classExists($classname)\r
+    {\r
+        return class_exists($classname, false);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function loadClass($class_name, $debug)\r
+\r
+    /**\r
+     * Loads a PEAR class.\r
+     *\r
+     * @param   string  classname to load\r
+     * @param   bool    if errors should be suppressed\r
+     *\r
+     * @return  mixed   true success or PEAR_Error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    static function loadClass($class_name, $debug)\r
+    {\r
+        if (!MDB2::classExists($class_name)) {\r
+            $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';\r
+            if ($debug) {\r
+                $include = include_once($file_name);\r
+            } else {\r
+                $include = @include_once($file_name);\r
+            }\r
+            if (!$include) {\r
+                if (!MDB2::fileExists($file_name)) {\r
+                    $msg = "unable to find package '$class_name' file '$file_name'";\r
+                } else {\r
+                    $msg = "unable to load class '$class_name' from file '$file_name'";\r
+                }\r
+                $err = MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null, $msg);\r
+                return $err;\r
+            }\r
+            if (!MDB2::classExists($class_name)) {\r
+                $msg = "unable to load class '$class_name' from file '$file_name'";\r
+                $err = MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null, $msg);\r
+                return $err;\r
+            }\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function factory($dsn, $options = false)\r
+\r
+    /**\r
+     * Create a new MDB2 object for the specified database type\r
+     *\r
+     * @param   mixed   'data source name', see the MDB2::parseDSN\r
+     *                      method for a description of the dsn format.\r
+     *                      Can also be specified as an array of the\r
+     *                      format returned by MDB2::parseDSN.\r
+     * @param   array   An associative array of option names and\r
+     *                            their values.\r
+     *\r
+     * @return  mixed   a newly created MDB2 object, or false on error\r
+     *\r
+     * @access  public\r
+     */\r
+    static function factory($dsn, $options = false)\r
+    {\r
+        $dsninfo = MDB2::parseDSN($dsn);\r
+        if (empty($dsninfo['phptype'])) {\r
+            $err = MDB2::raiseError(MDB2_ERROR_NOT_FOUND,\r
+                null, null, 'no RDBMS driver specified');\r
+            return $err;\r
+        }\r
+        $class_name = 'MDB2_Driver_'.$dsninfo['phptype'];\r
+\r
+        $debug = (!empty($options['debug']));\r
+        $err = MDB2::loadClass($class_name, $debug);\r
+        if (PEAR::isError($err)) {\r
+            return $err;\r
+        }\r
+\r
+        $db = new $class_name();\r
+        $db->setDSN($dsninfo);\r
+        $err = MDB2::setOptions($db, $options);\r
+        if (PEAR::isError($err)) {\r
+            return $err;\r
+        }\r
+\r
+        return $db;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function connect($dsn, $options = false)\r
+\r
+    /**\r
+     * Create a new MDB2_Driver_* connection object and connect to the specified\r
+     * database\r
+     *\r
+     * @param mixed $dsn     'data source name', see the MDB2::parseDSN\r
+     *                       method for a description of the dsn format.\r
+     *                       Can also be specified as an array of the\r
+     *                       format returned by MDB2::parseDSN.\r
+     * @param array $options An associative array of option names and\r
+     *                       their values.\r
+     *\r
+     * @return mixed a newly created MDB2 connection object, or a MDB2\r
+     *               error object on error\r
+     *\r
+     * @access  public\r
+     * @see     MDB2::parseDSN\r
+     */\r
+    static function connect($dsn, $options = false)\r
+    {\r
+        $db = MDB2::factory($dsn, $options);\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $err = $db->connect();\r
+        if (PEAR::isError($err)) {\r
+            $dsn = $db->getDSN('string', 'xxx');\r
+            $db->disconnect();\r
+            $err->addUserInfo($dsn);\r
+            return $err;\r
+        }\r
+\r
+        return $db;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function singleton($dsn = null, $options = false)\r
+\r
+    /**\r
+     * Returns a MDB2 connection with the requested DSN.\r
+     * A new MDB2 connection object is only created if no object with the\r
+     * requested DSN exists yet.\r
+     *\r
+     * @param   mixed   'data source name', see the MDB2::parseDSN\r
+     *                            method for a description of the dsn format.\r
+     *                            Can also be specified as an array of the\r
+     *                            format returned by MDB2::parseDSN.\r
+     * @param   array   An associative array of option names and\r
+     *                            their values.\r
+     *\r
+     * @return  mixed   a newly created MDB2 connection object, or a MDB2\r
+     *                  error object on error\r
+     *\r
+     * @access  public\r
+     * @see     MDB2::parseDSN\r
+     */\r
+    static function singleton($dsn = null, $options = false)\r
+    {\r
+        if ($dsn) {\r
+            $dsninfo = MDB2::parseDSN($dsn);\r
+            $dsninfo = array_merge($GLOBALS['_MDB2_dsninfo_default'], $dsninfo);\r
+            $keys = array_keys($GLOBALS['_MDB2_databases']);\r
+            for ($i=0, $j=count($keys); $i<$j; ++$i) {\r
+                if (isset($GLOBALS['_MDB2_databases'][$keys[$i]])) {\r
+                    $tmp_dsn = $GLOBALS['_MDB2_databases'][$keys[$i]]->getDSN('array');\r
+                    if (count(array_diff_assoc($tmp_dsn, $dsninfo)) == 0) {\r
+                        MDB2::setOptions($GLOBALS['_MDB2_databases'][$keys[$i]], $options);\r
+                        return $GLOBALS['_MDB2_databases'][$keys[$i]];\r
+                    }\r
+                }\r
+            }\r
+        } elseif (is_array($GLOBALS['_MDB2_databases']) && reset($GLOBALS['_MDB2_databases'])) {\r
+            return $GLOBALS['_MDB2_databases'][key($GLOBALS['_MDB2_databases'])];\r
+        }\r
+        $db = MDB2::factory($dsn, $options);\r
+        return $db;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function areEquals()\r
+\r
+    /**\r
+     * It looks like there's a memory leak in array_diff() in PHP 5.1.x,\r
+     * so use this method instead.\r
+     * @see http://pear.php.net/bugs/bug.php?id=11790\r
+     *\r
+     * @param array $arr1\r
+     * @param array $arr2\r
+     * @return boolean\r
+     */\r
+    static function areEquals($arr1, $arr2)\r
+    {\r
+        if (count($arr1) != count($arr2)) {\r
+            return false;\r
+        }\r
+        foreach (array_keys($arr1) as $k) {\r
+            if (!array_key_exists($k, $arr2) || $arr1[$k] != $arr2[$k]) {\r
+                return false;\r
+            }\r
+        }\r
+        return true;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function loadFile($file)\r
+\r
+    /**\r
+     * load a file (like 'Date')\r
+     *\r
+     * @param string $file name of the file in the MDB2 directory (without '.php')\r
+     *\r
+     * @return string name of the file that was included\r
+     *\r
+     * @access  public\r
+     */\r
+    static function loadFile($file)\r
+    {\r
+        $file_name = 'MDB2'.DIRECTORY_SEPARATOR.$file.'.php';\r
+        if (!MDB2::fileExists($file_name)) {\r
+            return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                'unable to find: '.$file_name);\r
+        }\r
+        if (!include_once($file_name)) {\r
+            return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                'unable to load driver class: '.$file_name);\r
+        }\r
+        return $file_name;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function apiVersion()\r
+\r
+    /**\r
+     * Return the MDB2 API version\r
+     *\r
+     * @return  string  the MDB2 API version number\r
+     *\r
+     * @access  public\r
+     */\r
+    function apiVersion()\r
+    {\r
+        return '2.5.0b3';\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)\r
+\r
+    /**\r
+     * This method is used to communicate an error and invoke error\r
+     * callbacks etc.  Basically a wrapper for PEAR::raiseError\r
+     * without the message string.\r
+     *\r
+     * @param   mixed  int error code\r
+     *\r
+     * @param   int    error mode, see PEAR_Error docs\r
+     *\r
+     * @param   mixed  If error mode is PEAR_ERROR_TRIGGER, this is the\r
+     *                 error level (E_USER_NOTICE etc).  If error mode is\r
+     *                 PEAR_ERROR_CALLBACK, this is the callback function,\r
+     *                 either as a function name, or as an array of an\r
+     *                 object and method name.  For other error modes this\r
+     *                 parameter is ignored.\r
+     *\r
+     * @param   string Extra debug information.  Defaults to the last\r
+     *                 query and native error code.\r
+     *\r
+     * @return PEAR_Error instance of a PEAR Error object\r
+     *\r
+     * @access  private\r
+     * @see     PEAR_Error\r
+     */\r
+    function &raiseError($code = null,\r
+                         $mode = null,\r
+                         $options = null,\r
+                         $userinfo = null,\r
+                         $dummy1 = null,\r
+                         $dummy2 = null,\r
+                         $dummy3 = false)\r
+    {\r
+        $err =& PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);\r
+        return $err;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function isError($data, $code = null)\r
+\r
+    /**\r
+     * Tell whether a value is a MDB2 error.\r
+     *\r
+     * @param   mixed   the value to test\r
+     * @param   int     if is an error object, return true\r
+     *                        only if $code is a string and\r
+     *                        $db->getMessage() == $code or\r
+     *                        $code is an integer and $db->getCode() == $code\r
+     *\r
+     * @return  bool    true if parameter is an error\r
+     *\r
+     * @access  public\r
+     */\r
+    static function isError($data, $code = null)\r
+    {\r
+        if ($data instanceof MDB2_Error) {\r
+            if (null === $code) {\r
+                return true;\r
+            }\r
+            if (is_string($code)) {\r
+                return $data->getMessage() === $code;\r
+            }\r
+            return in_array($data->getCode(), (array)$code);\r
+        }\r
+        return false;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function isConnection($value)\r
+\r
+    /**\r
+     * Tell whether a value is a MDB2 connection\r
+     *\r
+     * @param   mixed   value to test\r
+     *\r
+     * @return  bool    whether $value is a MDB2 connection\r
+     * @access  public\r
+     */\r
+    function isConnection($value)\r
+    {\r
+        return ($value instanceof MDB2_Driver_Common);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function isResult($value)\r
+\r
+    /**\r
+     * Tell whether a value is a MDB2 result\r
+     *\r
+     * @param mixed $value value to test\r
+     *\r
+     * @return bool whether $value is a MDB2 result\r
+     *\r
+     * @access public\r
+     */\r
+    function isResult($value)\r
+    {\r
+        return ($value instanceof MDB2_Result);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function isResultCommon($value)\r
+\r
+    /**\r
+     * Tell whether a value is a MDB2 result implementing the common interface\r
+     *\r
+     * @param mixed $value value to test\r
+     *\r
+     * @return bool whether $value is a MDB2 result implementing the common interface\r
+     *\r
+     * @access  public\r
+     */\r
+    static function isResultCommon($value)\r
+    {\r
+        return ($value instanceof MDB2_Result_Common);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function isStatement($value)\r
+\r
+    /**\r
+     * Tell whether a value is a MDB2 statement interface\r
+     *\r
+     * @param   mixed   value to test\r
+     *\r
+     * @return  bool    whether $value is a MDB2 statement interface\r
+     *\r
+     * @access  public\r
+     */\r
+    function isStatement($value)\r
+    {\r
+        return ($value instanceof MDB2_Statement_Common);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function errorMessage($value = null)\r
+\r
+    /**\r
+     * Return a textual error message for a MDB2 error code\r
+     *\r
+     * @param   int|array   integer error code,\r
+                                null to get the current error code-message map,\r
+                                or an array with a new error code-message map\r
+     *\r
+     * @return  string  error message, or false if the error code was\r
+     *                  not recognized\r
+     *\r
+     * @access  public\r
+     */\r
+    function errorMessage($value = null)\r
+    {\r
+        static $errorMessages;\r
+\r
+        if (is_array($value)) {\r
+            $errorMessages = $value;\r
+            return MDB2_OK;\r
+        }\r
+\r
+        if (!isset($errorMessages)) {\r
+            $errorMessages = array(\r
+                MDB2_OK                       => 'no error',\r
+                MDB2_ERROR                    => 'unknown error',\r
+                MDB2_ERROR_ALREADY_EXISTS     => 'already exists',\r
+                MDB2_ERROR_CANNOT_CREATE      => 'can not create',\r
+                MDB2_ERROR_CANNOT_ALTER       => 'can not alter',\r
+                MDB2_ERROR_CANNOT_REPLACE     => 'can not replace',\r
+                MDB2_ERROR_CANNOT_DELETE      => 'can not delete',\r
+                MDB2_ERROR_CANNOT_DROP        => 'can not drop',\r
+                MDB2_ERROR_CONSTRAINT         => 'constraint violation',\r
+                MDB2_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',\r
+                MDB2_ERROR_DIVZERO            => 'division by zero',\r
+                MDB2_ERROR_INVALID            => 'invalid',\r
+                MDB2_ERROR_INVALID_DATE       => 'invalid date or time',\r
+                MDB2_ERROR_INVALID_NUMBER     => 'invalid number',\r
+                MDB2_ERROR_MISMATCH           => 'mismatch',\r
+                MDB2_ERROR_NODBSELECTED       => 'no database selected',\r
+                MDB2_ERROR_NOSUCHFIELD        => 'no such field',\r
+                MDB2_ERROR_NOSUCHTABLE        => 'no such table',\r
+                MDB2_ERROR_NOT_CAPABLE        => 'MDB2 backend not capable',\r
+                MDB2_ERROR_NOT_FOUND          => 'not found',\r
+                MDB2_ERROR_NOT_LOCKED         => 'not locked',\r
+                MDB2_ERROR_SYNTAX             => 'syntax error',\r
+                MDB2_ERROR_UNSUPPORTED        => 'not supported',\r
+                MDB2_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',\r
+                MDB2_ERROR_INVALID_DSN        => 'invalid DSN',\r
+                MDB2_ERROR_CONNECT_FAILED     => 'connect failed',\r
+                MDB2_ERROR_NEED_MORE_DATA     => 'insufficient data supplied',\r
+                MDB2_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',\r
+                MDB2_ERROR_NOSUCHDB           => 'no such database',\r
+                MDB2_ERROR_ACCESS_VIOLATION   => 'insufficient permissions',\r
+                MDB2_ERROR_LOADMODULE         => 'error while including on demand module',\r
+                MDB2_ERROR_TRUNCATED          => 'truncated',\r
+                MDB2_ERROR_DEADLOCK           => 'deadlock detected',\r
+                MDB2_ERROR_NO_PERMISSION      => 'no permission',\r
+                MDB2_ERROR_DISCONNECT_FAILED  => 'disconnect failed',\r
+            );\r
+        }\r
+\r
+        if (null === $value) {\r
+            return $errorMessages;\r
+        }\r
+\r
+        if (PEAR::isError($value)) {\r
+            $value = $value->getCode();\r
+        }\r
+\r
+        return isset($errorMessages[$value]) ?\r
+           $errorMessages[$value] : $errorMessages[MDB2_ERROR];\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function parseDSN($dsn)\r
+\r
+    /**\r
+     * Parse a data source name.\r
+     *\r
+     * Additional keys can be added by appending a URI query string to the\r
+     * end of the DSN.\r
+     *\r
+     * The format of the supplied DSN is in its fullest form:\r
+     * <code>\r
+     *  phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true\r
+     * </code>\r
+     *\r
+     * Most variations are allowed:\r
+     * <code>\r
+     *  phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644\r
+     *  phptype://username:password@hostspec/database_name\r
+     *  phptype://username:password@hostspec\r
+     *  phptype://username@hostspec\r
+     *  phptype://hostspec/database\r
+     *  phptype://hostspec\r
+     *  phptype(dbsyntax)\r
+     *  phptype\r
+     * </code>\r
+     *\r
+     * @param   string  Data Source Name to be parsed\r
+     *\r
+     * @return  array   an associative array with the following keys:\r
+     *  + phptype:  Database backend used in PHP (mysql, odbc etc.)\r
+     *  + dbsyntax: Database used with regards to SQL syntax etc.\r
+     *  + protocol: Communication protocol to use (tcp, unix etc.)\r
+     *  + hostspec: Host specification (hostname[:port])\r
+     *  + database: Database to use on the DBMS server\r
+     *  + username: User name for login\r
+     *  + password: Password for login\r
+     *\r
+     * @access  public\r
+     * @author  Tomas V.V.Cox <cox@idecnet.com>\r
+     */\r
+    static function parseDSN($dsn)\r
+    {\r
+        $parsed = $GLOBALS['_MDB2_dsninfo_default'];\r
+\r
+        if (is_array($dsn)) {\r
+            $dsn = array_merge($parsed, $dsn);\r
+            if (!$dsn['dbsyntax']) {\r
+                $dsn['dbsyntax'] = $dsn['phptype'];\r
+            }\r
+            return $dsn;\r
+        }\r
+\r
+        // Find phptype and dbsyntax\r
+        if (($pos = strpos($dsn, '://')) !== false) {\r
+            $str = substr($dsn, 0, $pos);\r
+            $dsn = substr($dsn, $pos + 3);\r
+        } else {\r
+            $str = $dsn;\r
+            $dsn = null;\r
+        }\r
+\r
+        // Get phptype and dbsyntax\r
+        // $str => phptype(dbsyntax)\r
+        if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {\r
+            $parsed['phptype']  = $arr[1];\r
+            $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];\r
+        } else {\r
+            $parsed['phptype']  = $str;\r
+            $parsed['dbsyntax'] = $str;\r
+        }\r
+\r
+        if (!count($dsn)) {\r
+            return $parsed;\r
+        }\r
+\r
+        // Get (if found): username and password\r
+        // $dsn => username:password@protocol+hostspec/database\r
+        if (($at = strrpos($dsn,'@')) !== false) {\r
+            $str = substr($dsn, 0, $at);\r
+            $dsn = substr($dsn, $at + 1);\r
+            if (($pos = strpos($str, ':')) !== false) {\r
+                $parsed['username'] = rawurldecode(substr($str, 0, $pos));\r
+                $parsed['password'] = rawurldecode(substr($str, $pos + 1));\r
+            } else {\r
+                $parsed['username'] = rawurldecode($str);\r
+            }\r
+        }\r
+\r
+        // Find protocol and hostspec\r
+\r
+        // $dsn => proto(proto_opts)/database\r
+        if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {\r
+            $proto       = $match[1];\r
+            $proto_opts  = $match[2] ? $match[2] : false;\r
+            $dsn         = $match[3];\r
+\r
+        // $dsn => protocol+hostspec/database (old format)\r
+        } else {\r
+            if (strpos($dsn, '+') !== false) {\r
+                list($proto, $dsn) = explode('+', $dsn, 2);\r
+            }\r
+            if (   strpos($dsn, '//') === 0\r
+                && strpos($dsn, '/', 2) !== false\r
+                && $parsed['phptype'] == 'oci8'\r
+            ) {\r
+                //oracle's "Easy Connect" syntax:\r
+                //"username/password@[//]host[:port][/service_name]"\r
+                //e.g. "scott/tiger@//mymachine:1521/oracle"\r
+                $proto_opts = $dsn;\r
+                $pos = strrpos($proto_opts, '/');\r
+                $dsn = substr($proto_opts, $pos + 1);\r
+                $proto_opts = substr($proto_opts, 0, $pos);\r
+            } elseif (strpos($dsn, '/') !== false) {\r
+                list($proto_opts, $dsn) = explode('/', $dsn, 2);\r
+            } else {\r
+                $proto_opts = $dsn;\r
+                $dsn = null;\r
+            }\r
+        }\r
+\r
+        // process the different protocol options\r
+        $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';\r
+        $proto_opts = rawurldecode($proto_opts);\r
+        if (strpos($proto_opts, ':') !== false) {\r
+            list($proto_opts, $parsed['port']) = explode(':', $proto_opts);\r
+        }\r
+        if ($parsed['protocol'] == 'tcp') {\r
+            $parsed['hostspec'] = $proto_opts;\r
+        } elseif ($parsed['protocol'] == 'unix') {\r
+            $parsed['socket'] = $proto_opts;\r
+        }\r
+\r
+        // Get dabase if any\r
+        // $dsn => database\r
+        if ($dsn) {\r
+            // /database\r
+            if (($pos = strpos($dsn, '?')) === false) {\r
+                $parsed['database'] = $dsn;\r
+            // /database?param1=value1&param2=value2\r
+            } else {\r
+                $parsed['database'] = substr($dsn, 0, $pos);\r
+                $dsn = substr($dsn, $pos + 1);\r
+                if (strpos($dsn, '&') !== false) {\r
+                    $opts = explode('&', $dsn);\r
+                } else { // database?param1=value1\r
+                    $opts = array($dsn);\r
+                }\r
+                foreach ($opts as $opt) {\r
+                    list($key, $value) = explode('=', $opt);\r
+                    if (!array_key_exists($key, $parsed) || false === $parsed[$key]) {\r
+                        // don't allow params overwrite\r
+                        $parsed[$key] = rawurldecode($value);\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+        return $parsed;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function fileExists($file)\r
+\r
+    /**\r
+     * Checks if a file exists in the include path\r
+     *\r
+     * @param   string  filename\r
+     *\r
+     * @return  bool    true success and false on error\r
+     *\r
+     * @access  public\r
+     */\r
+    static function fileExists($file)\r
+    {\r
+        // safe_mode does notwork with is_readable()\r
+        if (!@ini_get('safe_mode')) {\r
+             $dirs = explode(PATH_SEPARATOR, ini_get('include_path'));\r
+             foreach ($dirs as $dir) {\r
+                 if (is_readable($dir . DIRECTORY_SEPARATOR . $file)) {\r
+                     return true;\r
+                 }\r
+            }\r
+        } else {\r
+            $fp = @fopen($file, 'r', true);\r
+            if (is_resource($fp)) {\r
+                @fclose($fp);\r
+                return true;\r
+            }\r
+        }\r
+        return false;\r
+    }\r
+    // }}}\r
+}\r
+\r
+// }}}\r
+// {{{ class MDB2_Error extends PEAR_Error\r
+\r
+/**\r
+ * MDB2_Error implements a class for reporting portable database error\r
+ * messages.\r
+ *\r
+ * @package     MDB2\r
+ * @category    Database\r
+ * @author Stig Bakken <ssb@fast.no>\r
+ */\r
+class MDB2_Error extends PEAR_Error\r
+{\r
+    // {{{ constructor: function MDB2_Error($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN, $level = E_USER_NOTICE, $debuginfo = null)\r
+\r
+    /**\r
+     * MDB2_Error constructor.\r
+     *\r
+     * @param   mixed   MDB2 error code, or string with error message.\r
+     * @param   int     what 'error mode' to operate in\r
+     * @param   int     what error level to use for $mode & PEAR_ERROR_TRIGGER\r
+     * @param   mixed   additional debug info, such as the last query\r
+     */\r
+    function __construct($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN,\r
+              $level = E_USER_NOTICE, $debuginfo = null, $dummy = null)\r
+    {\r
+        if (null === $code) {\r
+            $code = MDB2_ERROR;\r
+        }\r
+        $this->PEAR_Error('MDB2 Error: '.MDB2::errorMessage($code), $code,\r
+            $mode, $level, $debuginfo);\r
+    }\r
+\r
+    // }}}\r
+}\r
+\r
+// }}}\r
+// {{{ class MDB2_Driver_Common extends PEAR\r
+\r
+/**\r
+ * MDB2_Driver_Common: Base class that is extended by each MDB2 driver\r
+ *\r
+ * @package     MDB2\r
+ * @category    Database\r
+ * @author      Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Driver_Common extends PEAR\r
+{\r
+    // {{{ Variables (Properties)\r
+\r
+    /**\r
+     * index of the MDB2 object within the $GLOBALS['_MDB2_databases'] array\r
+     * @var     int\r
+     * @access  public\r
+     */\r
+    var $db_index = 0;\r
+\r
+    /**\r
+     * DSN used for the next query\r
+     * @var     array\r
+     * @access  protected\r
+     */\r
+    var $dsn = array();\r
+\r
+    /**\r
+     * DSN that was used to create the current connection\r
+     * @var     array\r
+     * @access  protected\r
+     */\r
+    var $connected_dsn = array();\r
+\r
+    /**\r
+     * connection resource\r
+     * @var     mixed\r
+     * @access  protected\r
+     */\r
+    var $connection = 0;\r
+\r
+    /**\r
+     * if the current opened connection is a persistent connection\r
+     * @var     bool\r
+     * @access  protected\r
+     */\r
+    var $opened_persistent;\r
+\r
+    /**\r
+     * the name of the database for the next query\r
+     * @var     string\r
+     * @access  protected\r
+     */\r
+    var $database_name = '';\r
+\r
+    /**\r
+     * the name of the database currently selected\r
+     * @var     string\r
+     * @access  protected\r
+     */\r
+    var $connected_database_name = '';\r
+\r
+    /**\r
+     * server version information\r
+     * @var     string\r
+     * @access  protected\r
+     */\r
+    var $connected_server_info = '';\r
+\r
+    /**\r
+     * list of all supported features of the given driver\r
+     * @var     array\r
+     * @access  public\r
+     */\r
+    var $supported = array(\r
+        'sequences' => false,\r
+        'indexes' => false,\r
+        'affected_rows' => false,\r
+        'summary_functions' => false,\r
+        'order_by_text' => false,\r
+        'transactions' => false,\r
+        'savepoints' => false,\r
+        'current_id' => false,\r
+        'limit_queries' => false,\r
+        'LOBs' => false,\r
+        'replace' => false,\r
+        'sub_selects' => false,\r
+        'triggers' => false,\r
+        'auto_increment' => false,\r
+        'primary_key' => false,\r
+        'result_introspection' => false,\r
+        'prepared_statements' => false,\r
+        'identifier_quoting' => false,\r
+        'pattern_escaping' => false,\r
+        'new_link' => false,\r
+    );\r
+\r
+    /**\r
+     * Array of supported options that can be passed to the MDB2 instance.\r
+     * \r
+     * The options can be set during object creation, using\r
+     * MDB2::connect(), MDB2::factory() or MDB2::singleton(). The options can \r
+     * also be set after the object is created, using MDB2::setOptions() or \r
+     * MDB2_Driver_Common::setOption().\r
+     * The list of available option includes:\r
+     * <ul>\r
+     *  <li>$options['ssl'] -> boolean: determines if ssl should be used for connections</li>\r
+     *  <li>$options['field_case'] -> CASE_LOWER|CASE_UPPER: determines what case to force on field/table names</li>\r
+     *  <li>$options['disable_query'] -> boolean: determines if queries should be executed</li>\r
+     *  <li>$options['result_class'] -> string: class used for result sets</li>\r
+     *  <li>$options['buffered_result_class'] -> string: class used for buffered result sets</li>\r
+     *  <li>$options['result_wrap_class'] -> string: class used to wrap result sets into</li>\r
+     *  <li>$options['result_buffering'] -> boolean should results be buffered or not?</li>\r
+     *  <li>$options['fetch_class'] -> string: class to use when fetch mode object is used</li>\r
+     *  <li>$options['persistent'] -> boolean: persistent connection?</li>\r
+     *  <li>$options['debug'] -> integer: numeric debug level</li>\r
+     *  <li>$options['debug_handler'] -> string: function/method that captures debug messages</li>\r
+     *  <li>$options['debug_expanded_output'] -> bool: BC option to determine if more context information should be send to the debug handler</li>\r
+     *  <li>$options['default_text_field_length'] -> integer: default text field length to use</li>\r
+     *  <li>$options['lob_buffer_length'] -> integer: LOB buffer length</li>\r
+     *  <li>$options['log_line_break'] -> string: line-break format</li>\r
+     *  <li>$options['idxname_format'] -> string: pattern for index name</li>\r
+     *  <li>$options['seqname_format'] -> string: pattern for sequence name</li>\r
+     *  <li>$options['savepoint_format'] -> string: pattern for auto generated savepoint names</li>\r
+     *  <li>$options['statement_format'] -> string: pattern for prepared statement names</li>\r
+     *  <li>$options['seqcol_name'] -> string: sequence column name</li>\r
+     *  <li>$options['quote_identifier'] -> boolean: if identifier quoting should be done when check_option is used</li>\r
+     *  <li>$options['use_transactions'] -> boolean: if transaction use should be enabled</li>\r
+     *  <li>$options['decimal_places'] -> integer: number of decimal places to handle</li>\r
+     *  <li>$options['portability'] -> integer: portability constant</li>\r
+     *  <li>$options['modules'] -> array: short to long module name mapping for __call()</li>\r
+     *  <li>$options['emulate_prepared'] -> boolean: force prepared statements to be emulated</li>\r
+     *  <li>$options['datatype_map'] -> array: map user defined datatypes to other primitive datatypes</li>\r
+     *  <li>$options['datatype_map_callback'] -> array: callback function/method that should be called</li>\r
+     *  <li>$options['bindname_format'] -> string: regular expression pattern for named parameters</li>\r
+     *  <li>$options['multi_query'] -> boolean: determines if queries returning multiple result sets should be executed</li>\r
+     *  <li>$options['max_identifiers_length'] -> integer: max identifier length</li>\r
+     *  <li>$options['default_fk_action_onupdate'] -> string: default FOREIGN KEY ON UPDATE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']</li>\r
+     *  <li>$options['default_fk_action_ondelete'] -> string: default FOREIGN KEY ON DELETE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']</li>\r
+     * </ul>\r
+     *\r
+     * @var     array\r
+     * @access  public\r
+     * @see     MDB2::connect()\r
+     * @see     MDB2::factory()\r
+     * @see     MDB2::singleton()\r
+     * @see     MDB2_Driver_Common::setOption()\r
+     */\r
+    var $options = array(\r
+        'ssl' => false,\r
+        'field_case' => CASE_LOWER,\r
+        'disable_query' => false,\r
+        'result_class' => 'MDB2_Result_%s',\r
+        'buffered_result_class' => 'MDB2_BufferedResult_%s',\r
+        'result_wrap_class' => false,\r
+        'result_buffering' => true,\r
+        'fetch_class' => 'stdClass',\r
+        'persistent' => false,\r
+        'debug' => 0,\r
+        'debug_handler' => 'MDB2_defaultDebugOutput',\r
+        'debug_expanded_output' => false,\r
+        'default_text_field_length' => 4096,\r
+        'lob_buffer_length' => 8192,\r
+        'log_line_break' => "\n",\r
+        'idxname_format' => '%s_idx',\r
+        'seqname_format' => '%s_seq',\r
+        'savepoint_format' => 'MDB2_SAVEPOINT_%s',\r
+        'statement_format' => 'MDB2_STATEMENT_%1$s_%2$s',\r
+        'seqcol_name' => 'sequence',\r
+        'quote_identifier' => false,\r
+        'use_transactions' => true,\r
+        'decimal_places' => 2,\r
+        'portability' => MDB2_PORTABILITY_ALL,\r
+        'modules' => array(\r
+            'ex' => 'Extended',\r
+            'dt' => 'Datatype',\r
+            'mg' => 'Manager',\r
+            'rv' => 'Reverse',\r
+            'na' => 'Native',\r
+            'fc' => 'Function',\r
+        ),\r
+        'emulate_prepared' => false,\r
+        'datatype_map' => array(),\r
+        'datatype_map_callback' => array(),\r
+        'nativetype_map_callback' => array(),\r
+        'lob_allow_url_include' => false,\r
+        'bindname_format' => '(?:\d+)|(?:[a-zA-Z][a-zA-Z0-9_]*)',\r
+        'max_identifiers_length' => 30,\r
+        'default_fk_action_onupdate' => 'RESTRICT',\r
+        'default_fk_action_ondelete' => 'RESTRICT',\r
+    );\r
+\r
+    /**\r
+     * string array\r
+     * @var     string\r
+     * @access  protected\r
+     */\r
+    var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => false, 'escape_pattern' => false);\r
+\r
+    /**\r
+     * identifier quoting\r
+     * @var     array\r
+     * @access  protected\r
+     */\r
+    var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');\r
+\r
+    /**\r
+     * sql comments\r
+     * @var     array\r
+     * @access  protected\r
+     */\r
+    var $sql_comments = array(\r
+        array('start' => '--', 'end' => "\n", 'escape' => false),\r
+        array('start' => '/*', 'end' => '*/', 'escape' => false),\r
+    );\r
+\r
+    /**\r
+     * comparision wildcards\r
+     * @var     array\r
+     * @access  protected\r
+     */\r
+    var $wildcards = array('%', '_');\r
+\r
+    /**\r
+     * column alias keyword\r
+     * @var     string\r
+     * @access  protected\r
+     */\r
+    var $as_keyword = ' AS ';\r
+\r
+    /**\r
+     * warnings\r
+     * @var     array\r
+     * @access  protected\r
+     */\r
+    var $warnings = array();\r
+\r
+    /**\r
+     * string with the debugging information\r
+     * @var     string\r
+     * @access  public\r
+     */\r
+    var $debug_output = '';\r
+\r
+    /**\r
+     * determine if there is an open transaction\r
+     * @var     bool\r
+     * @access  protected\r
+     */\r
+    var $in_transaction = false;\r
+\r
+    /**\r
+     * the smart transaction nesting depth\r
+     * @var     int\r
+     * @access  protected\r
+     */\r
+    var $nested_transaction_counter = null;\r
+\r
+    /**\r
+     * the first error that occured inside a nested transaction\r
+     * @var     MDB2_Error|bool\r
+     * @access  protected\r
+     */\r
+    var $has_transaction_error = false;\r
+\r
+    /**\r
+     * result offset used in the next query\r
+     * @var     int\r
+     * @access  protected\r
+     */\r
+    var $offset = 0;\r
+\r
+    /**\r
+     * result limit used in the next query\r
+     * @var     int\r
+     * @access  protected\r
+     */\r
+    var $limit = 0;\r
+\r
+    /**\r
+     * Database backend used in PHP (mysql, odbc etc.)\r
+     * @var     string\r
+     * @access  public\r
+     */\r
+    var $phptype;\r
+\r
+    /**\r
+     * Database used with regards to SQL syntax etc.\r
+     * @var     string\r
+     * @access  public\r
+     */\r
+    var $dbsyntax;\r
+\r
+    /**\r
+     * the last query sent to the driver\r
+     * @var     string\r
+     * @access  public\r
+     */\r
+    var $last_query;\r
+\r
+    /**\r
+     * the default fetchmode used\r
+     * @var     int\r
+     * @access  protected\r
+     */\r
+    var $fetchmode = MDB2_FETCHMODE_ORDERED;\r
+\r
+    /**\r
+     * array of module instances\r
+     * @var     array\r
+     * @access  protected\r
+     */\r
+    var $modules = array();\r
+\r
+    /**\r
+     * determines of the PHP4 destructor emulation has been enabled yet\r
+     * @var     array\r
+     * @access  protected\r
+     */\r
+    var $destructor_registered = true;\r
+\r
+    // }}}\r
+    // {{{ constructor: function __construct()\r
+\r
+    /**\r
+     * Constructor\r
+     */\r
+    function __construct()\r
+    {\r
+        end($GLOBALS['_MDB2_databases']);\r
+        $db_index = key($GLOBALS['_MDB2_databases']) + 1;\r
+        $GLOBALS['_MDB2_databases'][$db_index] = &$this;\r
+        $this->db_index = $db_index;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ destructor: function __destruct()\r
+\r
+    /**\r
+     *  Destructor\r
+     */\r
+    function __destruct()\r
+    {\r
+        $this->disconnect(false);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function free()\r
+\r
+    /**\r
+     * Free the internal references so that the instance can be destroyed\r
+     *\r
+     * @return  bool    true on success, false if result is invalid\r
+     *\r
+     * @access  public\r
+     */\r
+    function free()\r
+    {\r
+        unset($GLOBALS['_MDB2_databases'][$this->db_index]);\r
+        unset($this->db_index);\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function __toString()\r
+\r
+    /**\r
+     * String conversation\r
+     *\r
+     * @return  string representation of the object\r
+     *\r
+     * @access  public\r
+     */\r
+    function __toString()\r
+    {\r
+        $info = get_class($this);\r
+        $info.= ': (phptype = '.$this->phptype.', dbsyntax = '.$this->dbsyntax.')';\r
+        if ($this->connection) {\r
+            $info.= ' [connected]';\r
+        }\r
+        return $info;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function errorInfo($error = null)\r
+\r
+    /**\r
+     * This method is used to collect information about an error\r
+     *\r
+     * @param   mixed   error code or resource\r
+     *\r
+     * @return  array   with MDB2 errorcode, native error code, native message\r
+     *\r
+     * @access  public\r
+     */\r
+    function errorInfo($error = null)\r
+    {\r
+        return array($error, null, null);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)\r
+\r
+    /**\r
+     * This method is used to communicate an error and invoke error\r
+     * callbacks etc.  Basically a wrapper for PEAR::raiseError\r
+     * without the message string.\r
+     *\r
+     * @param mixed  $code     integer error code, or a PEAR error object (all \r
+     *                         other parameters are ignored if this parameter is\r
+     *                         an object\r
+     * @param int    $mode     error mode, see PEAR_Error docs\r
+     * @param mixed  $options  If error mode is PEAR_ERROR_TRIGGER, this is the\r
+     *                         error level (E_USER_NOTICE etc). If error mode is\r
+     *                         PEAR_ERROR_CALLBACK, this is the callback function,\r
+     *                         either as a function name, or as an array of an\r
+     *                         object and method name. For other error modes this\r
+     *                         parameter is ignored.\r
+     * @param string $userinfo Extra debug information. Defaults to the last\r
+     *                         query and native error code.\r
+     * @param string $method   name of the method that triggered the error\r
+     * @param string $dummy1   not used\r
+     * @param bool   $dummy2   not used\r
+     *\r
+     * @return PEAR_Error instance of a PEAR Error object\r
+     * @access public\r
+     * @see    PEAR_Error\r
+     */\r
+    function &raiseError($code = null,\r
+                         $mode = null,\r
+                         $options = null,\r
+                         $userinfo = null,\r
+                         $method = null,\r
+                         $dummy1 = null,\r
+                         $dummy2 = false\r
+    ) {\r
+        $userinfo = "[Error message: $userinfo]\n";\r
+        // The error is yet a MDB2 error object\r
+        if (PEAR::isError($code)) {\r
+            // because we use the static PEAR::raiseError, our global\r
+            // handler should be used if it is set\r
+            if ((null === $mode) && !empty($this->_default_error_mode)) {\r
+                $mode    = $this->_default_error_mode;\r
+                $options = $this->_default_error_options;\r
+            }\r
+            if (null === $userinfo) {\r
+                $userinfo = $code->getUserinfo();\r
+            }\r
+            $code = $code->getCode();\r
+        } elseif ($code == MDB2_ERROR_NOT_FOUND) {\r
+            // extension not loaded: don't call $this->errorInfo() or the script\r
+            // will die\r
+        } elseif (isset($this->connection)) {\r
+            if (!empty($this->last_query)) {\r
+                $userinfo.= "[Last executed query: {$this->last_query}]\n";\r
+            }\r
+            $native_errno = $native_msg = null;\r
+            list($code, $native_errno, $native_msg) = $this->errorInfo($code);\r
+            if ((null !== $native_errno) && $native_errno !== '') {\r
+                $userinfo.= "[Native code: $native_errno]\n";\r
+            }\r
+            if ((null !== $native_msg) && $native_msg !== '') {\r
+                $userinfo.= "[Native message: ". strip_tags($native_msg) ."]\n";\r
+            }\r
+            if (null !== $method) {\r
+                $userinfo = $method.': '.$userinfo;\r
+            }\r
+        }\r
+\r
+        $err = PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);\r
+        if ($err->getMode() !== PEAR_ERROR_RETURN\r
+            && isset($this->nested_transaction_counter) && !$this->has_transaction_error) {\r
+            $this->has_transaction_error = $err;\r
+        }\r
+        return $err;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function resetWarnings()\r
+\r
+    /**\r
+     * reset the warning array\r
+     *\r
+     * @return void\r
+     *\r
+     * @access  public\r
+     */\r
+    function resetWarnings()\r
+    {\r
+        $this->warnings = array();\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function getWarnings()\r
+\r
+    /**\r
+     * Get all warnings in reverse order.\r
+     * This means that the last warning is the first element in the array\r
+     *\r
+     * @return  array   with warnings\r
+     *\r
+     * @access  public\r
+     * @see     resetWarnings()\r
+     */\r
+    function getWarnings()\r
+    {\r
+        return array_reverse($this->warnings);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function setFetchMode($fetchmode, $object_class = 'stdClass')\r
+\r
+    /**\r
+     * Sets which fetch mode should be used by default on queries\r
+     * on this connection\r
+     *\r
+     * @param   int     MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC\r
+     *                               or MDB2_FETCHMODE_OBJECT\r
+     * @param   string  the class name of the object to be returned\r
+     *                               by the fetch methods when the\r
+     *                               MDB2_FETCHMODE_OBJECT mode is selected.\r
+     *                               If no class is specified by default a cast\r
+     *                               to object from the assoc array row will be\r
+     *                               done.  There is also the possibility to use\r
+     *                               and extend the 'MDB2_row' class.\r
+     *\r
+     * @return  mixed   MDB2_OK or MDB2 Error Object\r
+     *\r
+     * @access  public\r
+     * @see     MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC, MDB2_FETCHMODE_OBJECT\r
+     */\r
+    function setFetchMode($fetchmode, $object_class = 'stdClass')\r
+    {\r
+        switch ($fetchmode) {\r
+        case MDB2_FETCHMODE_OBJECT:\r
+            $this->options['fetch_class'] = $object_class;\r
+        case MDB2_FETCHMODE_ORDERED:\r
+        case MDB2_FETCHMODE_ASSOC:\r
+            $this->fetchmode = $fetchmode;\r
+            break;\r
+        default:\r
+            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'invalid fetchmode mode', __FUNCTION__);\r
+        }\r
+\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function setOption($option, $value)\r
+\r
+    /**\r
+     * set the option for the db class\r
+     *\r
+     * @param   string  option name\r
+     * @param   mixed   value for the option\r
+     *\r
+     * @return  mixed   MDB2_OK or MDB2 Error Object\r
+     *\r
+     * @access  public\r
+     */\r
+    function setOption($option, $value)\r
+    {\r
+        if (array_key_exists($option, $this->options)) {\r
+            $this->options[$option] = $value;\r
+            return MDB2_OK;\r
+        }\r
+        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            "unknown option $option", __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function getOption($option)\r
+\r
+    /**\r
+     * Returns the value of an option\r
+     *\r
+     * @param   string  option name\r
+     *\r
+     * @return  mixed   the option value or error object\r
+     *\r
+     * @access  public\r
+     */\r
+    function getOption($option)\r
+    {\r
+        if (array_key_exists($option, $this->options)) {\r
+            return $this->options[$option];\r
+        }\r
+        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            "unknown option $option", __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function debug($message, $scope = '', $is_manip = null)\r
+\r
+    /**\r
+     * set a debug message\r
+     *\r
+     * @param   string  message that should be appended to the debug variable\r
+     * @param   string  usually the method name that triggered the debug call:\r
+     *                  for example 'query', 'prepare', 'execute', 'parameters',\r
+     *                  'beginTransaction', 'commit', 'rollback'\r
+     * @param   array   contains context information about the debug() call\r
+     *                  common keys are: is_manip, time, result etc.\r
+     *\r
+     * @return void\r
+     *\r
+     * @access  public\r
+     */\r
+    function debug($message, $scope = '', $context = array())\r
+    {\r
+        if ($this->options['debug'] && $this->options['debug_handler']) {\r
+            if (!$this->options['debug_expanded_output']) {\r
+                if (!empty($context['when']) && $context['when'] !== 'pre') {\r
+                    return null;\r
+                }\r
+                $context = empty($context['is_manip']) ? false : $context['is_manip'];\r
+            }\r
+            return call_user_func_array($this->options['debug_handler'], array(&$this, $scope, $message, $context));\r
+        }\r
+        return null;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function getDebugOutput()\r
+\r
+    /**\r
+     * output debug info\r
+     *\r
+     * @return  string  content of the debug_output class variable\r
+     *\r
+     * @access  public\r
+     */\r
+    function getDebugOutput()\r
+    {\r
+        return $this->debug_output;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function escape($text)\r
+\r
+    /**\r
+     * Quotes a string so it can be safely used in a query. It will quote\r
+     * the text so it can safely be used within a query.\r
+     *\r
+     * @param   string  the input string to quote\r
+     * @param   bool    escape wildcards\r
+     *\r
+     * @return  string  quoted string\r
+     *\r
+     * @access  public\r
+     */\r
+    function escape($text, $escape_wildcards = false)\r
+    {\r
+        if ($escape_wildcards) {\r
+            $text = $this->escapePattern($text);\r
+        }\r
+\r
+        $text = str_replace($this->string_quoting['end'], $this->string_quoting['escape'] . $this->string_quoting['end'], $text);\r
+        return $text;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function escapePattern($text)\r
+\r
+    /**\r
+     * Quotes pattern (% and _) characters in a string)\r
+     *\r
+     * @param   string  the input string to quote\r
+     *\r
+     * @return  string  quoted string\r
+     *\r
+     * @access  public\r
+     */\r
+    function escapePattern($text)\r
+    {\r
+        if ($this->string_quoting['escape_pattern']) {\r
+            $text = str_replace($this->string_quoting['escape_pattern'], $this->string_quoting['escape_pattern'] . $this->string_quoting['escape_pattern'], $text);\r
+            foreach ($this->wildcards as $wildcard) {\r
+                $text = str_replace($wildcard, $this->string_quoting['escape_pattern'] . $wildcard, $text);\r
+            }\r
+        }\r
+        return $text;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function quoteIdentifier($str, $check_option = false)\r
+\r
+    /**\r
+     * Quote a string so it can be safely used as a table or column name\r
+     *\r
+     * Delimiting style depends on which database driver is being used.\r
+     *\r
+     * NOTE: just because you CAN use delimited identifiers doesn't mean\r
+     * you SHOULD use them.  In general, they end up causing way more\r
+     * problems than they solve.\r
+     *\r
+     * NOTE: if you have table names containing periods, don't use this method\r
+     * (@see bug #11906)\r
+     *\r
+     * Portability is broken by using the following characters inside\r
+     * delimited identifiers:\r
+     *   + backtick (<kbd>`</kbd>) -- due to MySQL\r
+     *   + double quote (<kbd>"</kbd>) -- due to Oracle\r
+     *   + brackets (<kbd>[</kbd> or <kbd>]</kbd>) -- due to Access\r
+     *\r
+     * Delimited identifiers are known to generally work correctly under\r
+     * the following drivers:\r
+     *   + mssql\r
+     *   + mysql\r
+     *   + mysqli\r
+     *   + oci8\r
+     *   + pgsql\r
+     *   + sqlite\r
+     *\r
+     * InterBase doesn't seem to be able to use delimited identifiers\r
+     * via PHP 4.  They work fine under PHP 5.\r
+     *\r
+     * @param   string  identifier name to be quoted\r
+     * @param   bool    check the 'quote_identifier' option\r
+     *\r
+     * @return  string  quoted identifier string\r
+     *\r
+     * @access  public\r
+     */\r
+    function quoteIdentifier($str, $check_option = false)\r
+    {\r
+        if ($check_option && !$this->options['quote_identifier']) {\r
+            return $str;\r
+        }\r
+        $str = str_replace($this->identifier_quoting['end'], $this->identifier_quoting['escape'] . $this->identifier_quoting['end'], $str);\r
+        $parts = explode('.', $str);\r
+        foreach (array_keys($parts) as $k) {\r
+            $parts[$k] = $this->identifier_quoting['start'] . $parts[$k] . $this->identifier_quoting['end'];\r
+        }\r
+        return implode('.', $parts);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function getAsKeyword()\r
+\r
+    /**\r
+     * Gets the string to alias column\r
+     *\r
+     * @return string to use when aliasing a column\r
+     */\r
+    function getAsKeyword()\r
+    {\r
+        return $this->as_keyword;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function getConnection()\r
+\r
+    /**\r
+     * Returns a native connection\r
+     *\r
+     * @return  mixed   a valid MDB2 connection object,\r
+     *                  or a MDB2 error object on error\r
+     *\r
+     * @access  public\r
+     */\r
+    function getConnection()\r
+    {\r
+        $result = $this->connect();\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        return $this->connection;\r
+    }\r
+\r
+     // }}}\r
+    // {{{ function _fixResultArrayValues(&$row, $mode)\r
+\r
+    /**\r
+     * Do all necessary conversions on result arrays to fix DBMS quirks\r
+     *\r
+     * @param   array   the array to be fixed (passed by reference)\r
+     * @param   array   bit-wise addition of the required portability modes\r
+     *\r
+     * @return  void\r
+     *\r
+     * @access  protected\r
+     */\r
+    function _fixResultArrayValues(&$row, $mode)\r
+    {\r
+        switch ($mode) {\r
+        case MDB2_PORTABILITY_EMPTY_TO_NULL:\r
+            foreach ($row as $key => $value) {\r
+                if ($value === '') {\r
+                    $row[$key] = null;\r
+                }\r
+            }\r
+            break;\r
+        case MDB2_PORTABILITY_RTRIM:\r
+            foreach ($row as $key => $value) {\r
+                if (is_string($value)) {\r
+                    $row[$key] = rtrim($value);\r
+                }\r
+            }\r
+            break;\r
+        case MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES:\r
+            $tmp_row = array();\r
+            foreach ($row as $key => $value) {\r
+                $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;\r
+            }\r
+            $row = $tmp_row;\r
+            break;\r
+        case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL):\r
+            foreach ($row as $key => $value) {\r
+                if ($value === '') {\r
+                    $row[$key] = null;\r
+                } elseif (is_string($value)) {\r
+                    $row[$key] = rtrim($value);\r
+                }\r
+            }\r
+            break;\r
+        case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):\r
+            $tmp_row = array();\r
+            foreach ($row as $key => $value) {\r
+                if (is_string($value)) {\r
+                    $value = rtrim($value);\r
+                }\r
+                $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;\r
+            }\r
+            $row = $tmp_row;\r
+            break;\r
+        case (MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):\r
+            $tmp_row = array();\r
+            foreach ($row as $key => $value) {\r
+                if ($value === '') {\r
+                    $value = null;\r
+                }\r
+                $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;\r
+            }\r
+            $row = $tmp_row;\r
+            break;\r
+        case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):\r
+            $tmp_row = array();\r
+            foreach ($row as $key => $value) {\r
+                if ($value === '') {\r
+                    $value = null;\r
+                } elseif (is_string($value)) {\r
+                    $value = rtrim($value);\r
+                }\r
+                $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;\r
+            }\r
+            $row = $tmp_row;\r
+            break;\r
+        }\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function loadModule($module, $property = null, $phptype_specific = null)\r
+\r
+    /**\r
+     * loads a module\r
+     *\r
+     * @param   string  name of the module that should be loaded\r
+     *                  (only used for error messages)\r
+     * @param   string  name of the property into which the class will be loaded\r
+     * @param   bool    if the class to load for the module is specific to the\r
+     *                  phptype\r
+     *\r
+     * @return  object  on success a reference to the given module is returned\r
+     *                  and on failure a PEAR error\r
+     *\r
+     * @access  public\r
+     */\r
+    function loadModule($module, $property = null, $phptype_specific = null)\r
+    {\r
+        if (!$property) {\r
+            $property = strtolower($module);\r
+        }\r
+\r
+        if (!isset($this->{$property})) {\r
+            $version = $phptype_specific;\r
+            if ($phptype_specific !== false) {\r
+                $version = true;\r
+                $class_name = 'MDB2_Driver_'.$module.'_'.$this->phptype;\r
+                $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';\r
+            }\r
+            if ($phptype_specific === false\r
+                || (!MDB2::classExists($class_name) && !MDB2::fileExists($file_name))\r
+            ) {\r
+                $version = false;\r
+                $class_name = 'MDB2_'.$module;\r
+                $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';\r
+            }\r
+\r
+            $err = MDB2::loadClass($class_name, $this->getOption('debug'));\r
+            if (PEAR::isError($err)) {\r
+                return $err;\r
+            }\r
+\r
+            // load module in a specific version\r
+            if ($version) {\r
+                if (method_exists($class_name, 'getClassName')) {\r
+                    $class_name_new = call_user_func(array($class_name, 'getClassName'), $this->db_index);\r
+                    if ($class_name != $class_name_new) {\r
+                        $class_name = $class_name_new;\r
+                        $err = MDB2::loadClass($class_name, $this->getOption('debug'));\r
+                        if (PEAR::isError($err)) {\r
+                            return $err;\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+\r
+            if (!MDB2::classExists($class_name)) {\r
+                $err = $this->raiseError(MDB2_ERROR_LOADMODULE, null, null,\r
+                    "unable to load module '$module' into property '$property'", __FUNCTION__);\r
+                return $err;\r
+            }\r
+            $this->{$property} = new $class_name($this->db_index);\r
+            $this->modules[$module] = $this->{$property};\r
+            if ($version) {\r
+                // this will be used in the connect method to determine if the module\r
+                // needs to be loaded with a different version if the server\r
+                // version changed in between connects\r
+                $this->loaded_version_modules[] = $property;\r
+            }\r
+        }\r
+\r
+        return $this->{$property};\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function __call($method, $params)\r
+\r
+    /**\r
+     * Calls a module method using the __call magic method\r
+     *\r
+     * @param   string  Method name.\r
+     * @param   array   Arguments.\r
+     *\r
+     * @return  mixed   Returned value.\r
+     */\r
+    function __call($method, $params)\r
+    {\r
+        $module = null;\r
+        if (preg_match('/^([a-z]+)([A-Z])(.*)$/', $method, $match)\r
+            && isset($this->options['modules'][$match[1]])\r
+        ) {\r
+            $module = $this->options['modules'][$match[1]];\r
+            $method = strtolower($match[2]).$match[3];\r
+            if (!isset($this->modules[$module]) || !is_object($this->modules[$module])) {\r
+                $result = $this->loadModule($module);\r
+                if (PEAR::isError($result)) {\r
+                    return $result;\r
+                }\r
+            }\r
+        } else {\r
+            foreach ($this->modules as $key => $foo) {\r
+                if (is_object($this->modules[$key])\r
+                    && method_exists($this->modules[$key], $method)\r
+                ) {\r
+                    $module = $key;\r
+                    break;\r
+                }\r
+            }\r
+        }\r
+        if (null !== $module) {\r
+            return call_user_func_array(array(&$this->modules[$module], $method), $params);\r
+        }\r
+        trigger_error(sprintf('Call to undefined function: %s::%s().', get_class($this), $method), E_USER_ERROR);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function beginTransaction($savepoint = null)\r
+\r
+    /**\r
+     * Start a transaction or set a savepoint.\r
+     *\r
+     * @param   string  name of a savepoint to set\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function beginTransaction($savepoint = null)\r
+    {\r
+        $this->debug('Starting transaction', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));\r
+        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'transactions are not supported', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function commit($savepoint = null)\r
+\r
+    /**\r
+     * Commit the database changes done during a transaction that is in\r
+     * progress or release a savepoint. This function may only be called when\r
+     * auto-committing is disabled, otherwise it will fail. Therefore, a new\r
+     * transaction is implicitly started after committing the pending changes.\r
+     *\r
+     * @param   string  name of a savepoint to release\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function commit($savepoint = null)\r
+    {\r
+        $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));\r
+        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'commiting transactions is not supported', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function rollback($savepoint = null)\r
+\r
+    /**\r
+     * Cancel any database changes done during a transaction or since a specific\r
+     * savepoint that is in progress. This function may only be called when\r
+     * auto-committing is disabled, otherwise it will fail. Therefore, a new\r
+     * transaction is implicitly started after canceling the pending changes.\r
+     *\r
+     * @param   string  name of a savepoint to rollback to\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function rollback($savepoint = null)\r
+    {\r
+        $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));\r
+        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'rolling back transactions is not supported', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function inTransaction($ignore_nested = false)\r
+\r
+    /**\r
+     * If a transaction is currently open.\r
+     *\r
+     * @param   bool    if the nested transaction count should be ignored\r
+     * @return  int|bool    - an integer with the nesting depth is returned if a\r
+     *                      nested transaction is open\r
+     *                      - true is returned for a normal open transaction\r
+     *                      - false is returned if no transaction is open\r
+     *\r
+     * @access  public\r
+     */\r
+    function inTransaction($ignore_nested = false)\r
+    {\r
+        if (!$ignore_nested && isset($this->nested_transaction_counter)) {\r
+            return $this->nested_transaction_counter;\r
+        }\r
+        return $this->in_transaction;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function setTransactionIsolation($isolation)\r
+\r
+    /**\r
+     * Set the transacton isolation level.\r
+     *\r
+     * @param   string  standard isolation level\r
+     *                  READ UNCOMMITTED (allows dirty reads)\r
+     *                  READ COMMITTED (prevents dirty reads)\r
+     *                  REPEATABLE READ (prevents nonrepeatable reads)\r
+     *                  SERIALIZABLE (prevents phantom reads)\r
+     * @param   array some transaction options:\r
+     *                  'wait' => 'WAIT' | 'NO WAIT'\r
+     *                  'rw'   => 'READ WRITE' | 'READ ONLY'\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     * @since   2.1.1\r
+     */\r
+    function setTransactionIsolation($isolation, $options = array())\r
+    {\r
+        $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));\r
+        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'isolation level setting is not supported', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function beginNestedTransaction($savepoint = false)\r
+\r
+    /**\r
+     * Start a nested transaction.\r
+     *\r
+     * @return  mixed   MDB2_OK on success/savepoint name, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     * @since   2.1.1\r
+     */\r
+    function beginNestedTransaction()\r
+    {\r
+        if ($this->in_transaction) {\r
+            ++$this->nested_transaction_counter;\r
+            $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);\r
+            if ($this->supports('savepoints') && $savepoint) {\r
+                return $this->beginTransaction($savepoint);\r
+            }\r
+            return MDB2_OK;\r
+        }\r
+        $this->has_transaction_error = false;\r
+        $result = $this->beginTransaction();\r
+        $this->nested_transaction_counter = 1;\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function completeNestedTransaction($force_rollback = false, $release = false)\r
+\r
+    /**\r
+     * Finish a nested transaction by rolling back if an error occured or\r
+     * committing otherwise.\r
+     *\r
+     * @param   bool    if the transaction should be rolled back regardless\r
+     *                  even if no error was set within the nested transaction\r
+     * @return  mixed   MDB_OK on commit/counter decrementing, false on rollback\r
+     *                  and a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     * @since   2.1.1\r
+     */\r
+    function completeNestedTransaction($force_rollback = false)\r
+    {\r
+        if ($this->nested_transaction_counter > 1) {\r
+            $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);\r
+            if ($this->supports('savepoints') && $savepoint) {\r
+                if ($force_rollback || $this->has_transaction_error) {\r
+                    $result = $this->rollback($savepoint);\r
+                    if (!PEAR::isError($result)) {\r
+                        $result = false;\r
+                        $this->has_transaction_error = false;\r
+                    }\r
+                } else {\r
+                    $result = $this->commit($savepoint);\r
+                }\r
+            } else {\r
+                $result = MDB2_OK;\r
+            }\r
+            --$this->nested_transaction_counter;\r
+            return $result;\r
+        }\r
+\r
+        $this->nested_transaction_counter = null;\r
+        $result = MDB2_OK;\r
+\r
+        // transaction has not yet been rolled back\r
+        if ($this->in_transaction) {\r
+            if ($force_rollback || $this->has_transaction_error) {\r
+                $result = $this->rollback();\r
+                if (!PEAR::isError($result)) {\r
+                    $result = false;\r
+                }\r
+            } else {\r
+                $result = $this->commit();\r
+            }\r
+        }\r
+        $this->has_transaction_error = false;\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function failNestedTransaction($error = null, $immediately = false)\r
+\r
+    /**\r
+     * Force setting nested transaction to failed.\r
+     *\r
+     * @param   mixed   value to return in getNestededTransactionError()\r
+     * @param   bool    if the transaction should be rolled back immediately\r
+     * @return  bool    MDB2_OK\r
+     *\r
+     * @access  public\r
+     * @since   2.1.1\r
+     */\r
+    function failNestedTransaction($error = null, $immediately = false)\r
+    {\r
+        if (null !== $error) {\r
+            $error = $this->has_transaction_error ? $this->has_transaction_error : true;\r
+        } elseif (!$error) {\r
+            $error = true;\r
+        }\r
+        $this->has_transaction_error = $error;\r
+        if (!$immediately) {\r
+            return MDB2_OK;\r
+        }\r
+        return $this->rollback();\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function getNestedTransactionError()\r
+\r
+    /**\r
+     * The first error that occured since the transaction start.\r
+     *\r
+     * @return  MDB2_Error|bool     MDB2 error object if an error occured or false.\r
+     *\r
+     * @access  public\r
+     * @since   2.1.1\r
+     */\r
+    function getNestedTransactionError()\r
+    {\r
+        return $this->has_transaction_error;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ connect()\r
+\r
+    /**\r
+     * Connect to the database\r
+     *\r
+     * @return true on success, MDB2 Error Object on failure\r
+     */\r
+    function connect()\r
+    {\r
+        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ databaseExists()\r
+\r
+    /**\r
+     * check if given database name is exists?\r
+     *\r
+     * @param string $name    name of the database that should be checked\r
+     *\r
+     * @return mixed true/false on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function databaseExists($name)\r
+    {\r
+        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ setCharset($charset, $connection = null)\r
+\r
+    /**\r
+     * Set the charset on the current connection\r
+     *\r
+     * @param string    charset\r
+     * @param resource  connection handle\r
+     *\r
+     * @return true on success, MDB2 Error Object on failure\r
+     */\r
+    function setCharset($charset, $connection = null)\r
+    {\r
+        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function disconnect($force = true)\r
+\r
+    /**\r
+     * Log out and disconnect from the database.\r
+     *\r
+     * @param boolean $force whether the disconnect should be forced even if the\r
+     *                       connection is opened persistently\r
+     *\r
+     * @return mixed true on success, false if not connected and error object on error\r
+     *\r
+     * @access  public\r
+     */\r
+    function disconnect($force = true)\r
+    {\r
+        $this->connection = 0;\r
+        $this->connected_dsn = array();\r
+        $this->connected_database_name = '';\r
+        $this->opened_persistent = null;\r
+        $this->connected_server_info = '';\r
+        $this->in_transaction = null;\r
+        $this->nested_transaction_counter = null;\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function setDatabase($name)\r
+\r
+    /**\r
+     * Select a different database\r
+     *\r
+     * @param   string  name of the database that should be selected\r
+     *\r
+     * @return  string  name of the database previously connected to\r
+     *\r
+     * @access  public\r
+     */\r
+    function setDatabase($name)\r
+    {\r
+        $previous_database_name = (isset($this->database_name)) ? $this->database_name : '';\r
+        $this->database_name = $name;\r
+        if (!empty($this->connected_database_name) && ($this->connected_database_name != $this->database_name)) {\r
+            $this->disconnect(false);\r
+        }\r
+        return $previous_database_name;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function getDatabase()\r
+\r
+    /**\r
+     * Get the current database\r
+     *\r
+     * @return  string  name of the database\r
+     *\r
+     * @access  public\r
+     */\r
+    function getDatabase()\r
+    {\r
+        return $this->database_name;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function setDSN($dsn)\r
+\r
+    /**\r
+     * set the DSN\r
+     *\r
+     * @param   mixed   DSN string or array\r
+     *\r
+     * @return  MDB2_OK\r
+     *\r
+     * @access  public\r
+     */\r
+    function setDSN($dsn)\r
+    {\r
+        $dsn_default = $GLOBALS['_MDB2_dsninfo_default'];\r
+        $dsn = MDB2::parseDSN($dsn);\r
+        if (array_key_exists('database', $dsn)) {\r
+            $this->database_name = $dsn['database'];\r
+            unset($dsn['database']);\r
+        }\r
+        $this->dsn = array_merge($dsn_default, $dsn);\r
+        return $this->disconnect(false);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function getDSN($type = 'string', $hidepw = false)\r
+\r
+    /**\r
+     * return the DSN as a string\r
+     *\r
+     * @param   string  format to return ("array", "string")\r
+     * @param   string  string to hide the password with\r
+     *\r
+     * @return  mixed   DSN in the chosen type\r
+     *\r
+     * @access  public\r
+     */\r
+    function getDSN($type = 'string', $hidepw = false)\r
+    {\r
+        $dsn = array_merge($GLOBALS['_MDB2_dsninfo_default'], $this->dsn);\r
+        $dsn['phptype'] = $this->phptype;\r
+        $dsn['database'] = $this->database_name;\r
+        if ($hidepw) {\r
+            $dsn['password'] = $hidepw;\r
+        }\r
+        switch ($type) {\r
+        // expand to include all possible options\r
+        case 'string':\r
+           $dsn = $dsn['phptype'].\r
+               ($dsn['dbsyntax'] ? ('('.$dsn['dbsyntax'].')') : '').\r
+               '://'.$dsn['username'].':'.\r
+                $dsn['password'].'@'.$dsn['hostspec'].\r
+                ($dsn['port'] ? (':'.$dsn['port']) : '').\r
+                '/'.$dsn['database'];\r
+            break;\r
+        case 'array':\r
+        default:\r
+            break;\r
+        }\r
+        return $dsn;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _isNewLinkSet()\r
+\r
+    /**\r
+     * Check if the 'new_link' option is set\r
+     *\r
+     * @return boolean\r
+     *\r
+     * @access protected\r
+     */\r
+    function _isNewLinkSet()\r
+    {\r
+        return (isset($this->dsn['new_link'])\r
+            && ($this->dsn['new_link'] === true\r
+             || (is_string($this->dsn['new_link']) && preg_match('/^true$/i', $this->dsn['new_link']))\r
+             || (is_numeric($this->dsn['new_link']) && 0 != (int)$this->dsn['new_link'])\r
+            )\r
+        );\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function &standaloneQuery($query, $types = null, $is_manip = false)\r
+\r
+   /**\r
+     * execute a query as database administrator\r
+     *\r
+     * @param   string  the SQL query\r
+     * @param   mixed   array that contains the types of the columns in\r
+     *                        the result set\r
+     * @param   bool    if the query is a manipulation query\r
+     *\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function standaloneQuery($query, $types = null, $is_manip = false)\r
+    {\r
+        $offset = $this->offset;\r
+        $limit = $this->limit;\r
+        $this->offset = $this->limit = 0;\r
+        $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);\r
+\r
+        $connection = $this->getConnection();\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+\r
+        $result = $this->_doQuery($query, $is_manip, $connection, false);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+\r
+        if ($is_manip) {\r
+            $affected_rows =  $this->_affectedRows($connection, $result);\r
+            return $affected_rows;\r
+        }\r
+        $result = $this->_wrapResult($result, $types, true, false, $limit, $offset);\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function _modifyQuery($query, $is_manip, $limit, $offset)\r
+\r
+    /**\r
+     * Changes a query string for various DBMS specific reasons\r
+     *\r
+     * @param   string  query to modify\r
+     * @param   bool    if it is a DML query\r
+     * @param   int  limit the number of rows\r
+     * @param   int  start reading from given offset\r
+     *\r
+     * @return  string  modified query\r
+     *\r
+     * @access  protected\r
+     */\r
+    function _modifyQuery($query, $is_manip, $limit, $offset)\r
+    {\r
+        return $query;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)\r
+\r
+    /**\r
+     * Execute a query\r
+     * @param   string  query\r
+     * @param   bool    if the query is a manipulation query\r
+     * @param   resource connection handle\r
+     * @param   string  database name\r
+     *\r
+     * @return  result or error object\r
+     *\r
+     * @access  protected\r
+     */\r
+    function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)\r
+    {\r
+        $this->last_query = $query;\r
+        $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));\r
+        if ($result) {\r
+            if (PEAR::isError($result)) {\r
+                return $result;\r
+            }\r
+            $query = $result;\r
+        }\r
+        $err = $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+        return $err;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function _affectedRows($connection, $result = null)\r
+\r
+    /**\r
+     * Returns the number of rows affected\r
+     *\r
+     * @param   resource result handle\r
+     * @param   resource connection handle\r
+     *\r
+     * @return  mixed   MDB2 Error Object or the number of rows affected\r
+     *\r
+     * @access  private\r
+     */\r
+    function _affectedRows($connection, $result = null)\r
+    {\r
+        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function &exec($query)\r
+\r
+    /**\r
+     * Execute a manipulation query to the database and return the number of affected rows\r
+     *\r
+     * @param   string  the SQL query\r
+     *\r
+     * @return  mixed   number of affected rows on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function exec($query)\r
+    {\r
+        $offset = $this->offset;\r
+        $limit = $this->limit;\r
+        $this->offset = $this->limit = 0;\r
+        $query = $this->_modifyQuery($query, true, $limit, $offset);\r
+\r
+        $connection = $this->getConnection();\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+\r
+        $result = $this->_doQuery($query, true, $connection, $this->database_name);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+\r
+        $affectedRows = $this->_affectedRows($connection, $result);\r
+        return $affectedRows;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function &query($query, $types = null, $result_class = true, $result_wrap_class = false)\r
+\r
+    /**\r
+     * Send a query to the database and return any results\r
+     *\r
+     * @param   string  the SQL query\r
+     * @param   mixed   array that contains the types of the columns in\r
+     *                        the result set\r
+     * @param   mixed   string which specifies which result class to use\r
+     * @param   mixed   string which specifies which class to wrap results in\r
+     *\r
+     * @return mixed   an MDB2_Result handle on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function query($query, $types = null, $result_class = true, $result_wrap_class = false)\r
+    {\r
+        $offset = $this->offset;\r
+        $limit = $this->limit;\r
+        $this->offset = $this->limit = 0;\r
+        $query = $this->_modifyQuery($query, false, $limit, $offset);\r
+\r
+        $connection = $this->getConnection();\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+\r
+        $result = $this->_doQuery($query, false, $connection, $this->database_name);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+\r
+        $result = $this->_wrapResult($result, $types, $result_class, $result_wrap_class, $limit, $offset);\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function _wrapResult($result_resource, $types = array(), $result_class = true, $result_wrap_class = false, $limit = null, $offset = null)\r
+\r
+    /**\r
+     * wrap a result set into the correct class\r
+     *\r
+     * @param   resource result handle\r
+     * @param   mixed   array that contains the types of the columns in\r
+     *                        the result set\r
+     * @param   mixed   string which specifies which result class to use\r
+     * @param   mixed   string which specifies which class to wrap results in\r
+     * @param   string  number of rows to select\r
+     * @param   string  first row to select\r
+     *\r
+     * @return mixed   an MDB2_Result, a MDB2 error on failure\r
+     *\r
+     * @access  protected\r
+     */\r
+    function _wrapResult($result_resource, $types = array(), $result_class = true,\r
+        $result_wrap_class = false, $limit = null, $offset = null)\r
+    {\r
+        if ($types === true) {\r
+            if ($this->supports('result_introspection')) {\r
+                $this->loadModule('Reverse', null, true);\r
+                $tableInfo = $this->reverse->tableInfo($result_resource);\r
+                if (PEAR::isError($tableInfo)) {\r
+                    return $tableInfo;\r
+                }\r
+                $types = array();\r
+                foreach ($tableInfo as $field) {\r
+                    $types[] = $field['mdb2type'];\r
+                }\r
+            } else {\r
+                $types = null;\r
+            }\r
+        }\r
+\r
+        if ($result_class === true) {\r
+            $result_class = $this->options['result_buffering']\r
+                ? $this->options['buffered_result_class'] : $this->options['result_class'];\r
+        }\r
+\r
+        if ($result_class) {\r
+            $class_name = sprintf($result_class, $this->phptype);\r
+            if (!MDB2::classExists($class_name)) {\r
+                $err = $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                    'result class does not exist '.$class_name, __FUNCTION__);\r
+                return $err;\r
+            }\r
+            $result = new $class_name($this, $result_resource, $limit, $offset);\r
+            if (!MDB2::isResultCommon($result)) {\r
+                $err = $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                    'result class is not extended from MDB2_Result_Common', __FUNCTION__);\r
+                return $err;\r
+            }\r
+            if (!empty($types)) {\r
+                $err = $result->setResultTypes($types);\r
+                if (PEAR::isError($err)) {\r
+                    $result->free();\r
+                    return $err;\r
+                }\r
+            }\r
+        }\r
+        if ($result_wrap_class === true) {\r
+            $result_wrap_class = $this->options['result_wrap_class'];\r
+        }\r
+        if ($result_wrap_class) {\r
+            if (!MDB2::classExists($result_wrap_class)) {\r
+                $err = $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                    'result wrap class does not exist '.$result_wrap_class, __FUNCTION__);\r
+                return $err;\r
+            }\r
+            $result = new $result_wrap_class($result_resource, $this->fetchmode);\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function getServerVersion($native = false)\r
+\r
+    /**\r
+     * return version information about the server\r
+     *\r
+     * @param   bool    determines if the raw version string should be returned\r
+     *\r
+     * @return  mixed   array with version information or row string\r
+     *\r
+     * @access  public\r
+     */\r
+    function getServerVersion($native = false)\r
+    {\r
+        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function setLimit($limit, $offset = null)\r
+\r
+    /**\r
+     * set the range of the next query\r
+     *\r
+     * @param   string  number of rows to select\r
+     * @param   string  first row to select\r
+     *\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function setLimit($limit, $offset = null)\r
+    {\r
+        if (!$this->supports('limit_queries')) {\r
+            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'limit is not supported by this driver', __FUNCTION__);\r
+        }\r
+        $limit = (int)$limit;\r
+        if ($limit < 0) {\r
+            return $this->raiseError(MDB2_ERROR_SYNTAX, null, null,\r
+                'it was not specified a valid selected range row limit', __FUNCTION__);\r
+        }\r
+        $this->limit = $limit;\r
+        if (null !== $offset) {\r
+            $offset = (int)$offset;\r
+            if ($offset < 0) {\r
+                return $this->raiseError(MDB2_ERROR_SYNTAX, null, null,\r
+                    'it was not specified a valid first selected range row', __FUNCTION__);\r
+            }\r
+            $this->offset = $offset;\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function subSelect($query, $type = false)\r
+\r
+    /**\r
+     * simple subselect emulation: leaves the query untouched for all RDBMS\r
+     * that support subselects\r
+     *\r
+     * @param   string  the SQL query for the subselect that may only\r
+     *                      return a column\r
+     * @param   string  determines type of the field\r
+     *\r
+     * @return  string  the query\r
+     *\r
+     * @access  public\r
+     */\r
+    function subSelect($query, $type = false)\r
+    {\r
+        if ($this->supports('sub_selects') === true) {\r
+            return $query;\r
+        }\r
+\r
+        if (!$this->supports('sub_selects')) {\r
+            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'method not implemented', __FUNCTION__);\r
+        }\r
+\r
+        $col = $this->queryCol($query, $type);\r
+        if (PEAR::isError($col)) {\r
+            return $col;\r
+        }\r
+        if (!is_array($col) || count($col) == 0) {\r
+            return 'NULL';\r
+        }\r
+        if ($type) {\r
+            $this->loadModule('Datatype', null, true);\r
+            return $this->datatype->implodeArray($col, $type);\r
+        }\r
+        return implode(', ', $col);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function replace($table, $fields)\r
+\r
+    /**\r
+     * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT\r
+     * query, except that if there is already a row in the table with the same\r
+     * key field values, the old row is deleted before the new row is inserted.\r
+     *\r
+     * The REPLACE type of query does not make part of the SQL standards. Since\r
+     * practically only MySQL and SQLite implement it natively, this type of\r
+     * query isemulated through this method for other DBMS using standard types\r
+     * of queries inside a transaction to assure the atomicity of the operation.\r
+     *\r
+     * @param   string  name of the table on which the REPLACE query will\r
+     *       be executed.\r
+     * @param   array   associative array   that describes the fields and the\r
+     *       values that will be inserted or updated in the specified table. The\r
+     *       indexes of the array are the names of all the fields of the table.\r
+     *       The values of the array are also associative arrays that describe\r
+     *       the values and other properties of the table fields.\r
+     *\r
+     *       Here follows a list of field properties that need to be specified:\r
+     *\r
+     *       value\r
+     *           Value to be assigned to the specified field. This value may be\r
+     *           of specified in database independent type format as this\r
+     *           function can perform the necessary datatype conversions.\r
+     *\r
+     *           Default: this property is required unless the Null property is\r
+     *           set to 1.\r
+     *\r
+     *       type\r
+     *           Name of the type of the field. Currently, all types MDB2\r
+     *           are supported except for clob and blob.\r
+     *\r
+     *           Default: no type conversion\r
+     *\r
+     *       null\r
+     *           bool    property that indicates that the value for this field\r
+     *           should be set to null.\r
+     *\r
+     *           The default value for fields missing in INSERT queries may be\r
+     *           specified the definition of a table. Often, the default value\r
+     *           is already null, but since the REPLACE may be emulated using\r
+     *           an UPDATE query, make sure that all fields of the table are\r
+     *           listed in this function argument array.\r
+     *\r
+     *           Default: 0\r
+     *\r
+     *       key\r
+     *           bool    property that indicates that this field should be\r
+     *           handled as a primary key or at least as part of the compound\r
+     *           unique index of the table that will determine the row that will\r
+     *           updated if it exists or inserted a new row otherwise.\r
+     *\r
+     *           This function will fail if no key field is specified or if the\r
+     *           value of a key field is set to null because fields that are\r
+     *           part of unique index they may not be null.\r
+     *\r
+     *           Default: 0\r
+     *\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function replace($table, $fields)\r
+    {\r
+        if (!$this->supports('replace')) {\r
+            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'replace query is not supported', __FUNCTION__);\r
+        }\r
+        $count = count($fields);\r
+        $condition = $values = array();\r
+        for ($colnum = 0, reset($fields); $colnum < $count; next($fields), $colnum++) {\r
+            $name = key($fields);\r
+            if (isset($fields[$name]['null']) && $fields[$name]['null']) {\r
+                $value = 'NULL';\r
+            } else {\r
+                $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;\r
+                $value = $this->quote($fields[$name]['value'], $type);\r
+            }\r
+            $values[$name] = $value;\r
+            if (isset($fields[$name]['key']) && $fields[$name]['key']) {\r
+                if ($value === 'NULL') {\r
+                    return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,\r
+                        'key value '.$name.' may not be NULL', __FUNCTION__);\r
+                }\r
+                $condition[] = $this->quoteIdentifier($name, true) . '=' . $value;\r
+            }\r
+        }\r
+        if (empty($condition)) {\r
+            return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,\r
+                'not specified which fields are keys', __FUNCTION__);\r
+        }\r
+\r
+        $result = null;\r
+        $in_transaction = $this->in_transaction;\r
+        if (!$in_transaction && PEAR::isError($result = $this->beginTransaction())) {\r
+            return $result;\r
+        }\r
+\r
+        $connection = $this->getConnection();\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+\r
+        $condition = ' WHERE '.implode(' AND ', $condition);\r
+        $query = 'DELETE FROM ' . $this->quoteIdentifier($table, true) . $condition;\r
+        $result = $this->_doQuery($query, true, $connection);\r
+        if (!PEAR::isError($result)) {\r
+            $affected_rows = $this->_affectedRows($connection, $result);\r
+            $insert = '';\r
+            foreach ($values as $key => $value) {\r
+                $insert .= ($insert?', ':'') . $this->quoteIdentifier($key, true);\r
+            }\r
+            $values = implode(', ', $values);\r
+            $query = 'INSERT INTO '. $this->quoteIdentifier($table, true) . "($insert) VALUES ($values)";\r
+            $result = $this->_doQuery($query, true, $connection);\r
+            if (!PEAR::isError($result)) {\r
+                $affected_rows += $this->_affectedRows($connection, $result);;\r
+            }\r
+        }\r
+\r
+        if (!$in_transaction) {\r
+            if (PEAR::isError($result)) {\r
+                $this->rollback();\r
+            } else {\r
+                $result = $this->commit();\r
+            }\r
+        }\r
+\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+\r
+        return $affected_rows;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function &prepare($query, $types = null, $result_types = null, $lobs = array())\r
+\r
+    /**\r
+     * Prepares a query for multiple execution with execute().\r
+     * With some database backends, this is emulated.\r
+     * prepare() requires a generic query as string like\r
+     * 'INSERT INTO numbers VALUES(?,?)' or\r
+     * 'INSERT INTO numbers VALUES(:foo,:bar)'.\r
+     * The ? and :name and are placeholders which can be set using\r
+     * bindParam() and the query can be sent off using the execute() method.\r
+     * The allowed format for :name can be set with the 'bindname_format' option.\r
+     *\r
+     * @param   string  the query to prepare\r
+     * @param   mixed   array that contains the types of the placeholders\r
+     * @param   mixed   array that contains the types of the columns in\r
+     *                        the result set or MDB2_PREPARE_RESULT, if set to\r
+     *                        MDB2_PREPARE_MANIP the query is handled as a manipulation query\r
+     * @param   mixed   key (field) value (parameter) pair for all lob placeholders\r
+     *\r
+     * @return  mixed   resource handle for the prepared query on success, \r
+     *                  a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     * @see     bindParam, execute\r
+     */\r
+    function prepare($query, $types = null, $result_types = null, $lobs = array())\r
+    {\r
+        $is_manip = ($result_types === MDB2_PREPARE_MANIP);\r
+        $offset = $this->offset;\r
+        $limit = $this->limit;\r
+        $this->offset = $this->limit = 0;\r
+        $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));\r
+        if ($result) {\r
+            if (PEAR::isError($result)) {\r
+                return $result;\r
+            }\r
+            $query = $result;\r
+        }\r
+        $placeholder_type_guess = $placeholder_type = null;\r
+        $question  = '?';\r
+        $colon     = ':';\r
+        $positions = array();\r
+        $position  = 0;\r
+        while ($position < strlen($query)) {\r
+            $q_position = strpos($query, $question, $position);\r
+            $c_position = strpos($query, $colon, $position);\r
+            if ($q_position && $c_position) {\r
+                $p_position = min($q_position, $c_position);\r
+            } elseif ($q_position) {\r
+                $p_position = $q_position;\r
+            } elseif ($c_position) {\r
+                $p_position = $c_position;\r
+            } else {\r
+                break;\r
+            }\r
+            if (null === $placeholder_type) {\r
+                $placeholder_type_guess = $query[$p_position];\r
+            }\r
+\r
+            $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);\r
+            if (PEAR::isError($new_pos)) {\r
+                return $new_pos;\r
+            }\r
+            if ($new_pos != $position) {\r
+                $position = $new_pos;\r
+                continue; //evaluate again starting from the new position\r
+            }\r
+\r
+            if ($query[$position] == $placeholder_type_guess) {\r
+                if (null === $placeholder_type) {\r
+                    $placeholder_type = $query[$p_position];\r
+                    $question = $colon = $placeholder_type;\r
+                    if (!empty($types) && is_array($types)) {\r
+                        if ($placeholder_type == ':') {\r
+                            if (is_int(key($types))) {\r
+                                $types_tmp = $types;\r
+                                $types = array();\r
+                                $count = -1;\r
+                            }\r
+                        } else {\r
+                            $types = array_values($types);\r
+                        }\r
+                    }\r
+                }\r
+                if ($placeholder_type == ':') {\r
+                    $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';\r
+                    $parameter = preg_replace($regexp, '\\1', $query);\r
+                    if ($parameter === '') {\r
+                        $err = $this->raiseError(MDB2_ERROR_SYNTAX, null, null,\r
+                            'named parameter name must match "bindname_format" option', __FUNCTION__);\r
+                        return $err;\r
+                    }\r
+                    $positions[$p_position] = $parameter;\r
+                    $query = substr_replace($query, '?', $position, strlen($parameter)+1);\r
+                    // use parameter name in type array\r
+                    if (isset($count) && isset($types_tmp[++$count])) {\r
+                        $types[$parameter] = $types_tmp[$count];\r
+                    }\r
+                } else {\r
+                    $positions[$p_position] = count($positions);\r
+                }\r
+                $position = $p_position + 1;\r
+            } else {\r
+                $position = $p_position;\r
+            }\r
+        }\r
+        $class_name = 'MDB2_Statement_'.$this->phptype;\r
+        $statement = null;\r
+        $obj = new $class_name($this, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);\r
+        $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));\r
+        return $obj;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function _skipDelimitedStrings($query, $position, $p_position)\r
+    \r
+    /**\r
+     * Utility method, used by prepare() to avoid replacing placeholders within delimited strings.\r
+     * Check if the placeholder is contained within a delimited string.\r
+     * If so, skip it and advance the position, otherwise return the current position,\r
+     * which is valid\r
+     *\r
+     * @param string $query\r
+     * @param integer $position current string cursor position\r
+     * @param integer $p_position placeholder position\r
+     *\r
+     * @return mixed integer $new_position on success\r
+     *               MDB2_Error on failure\r
+     *\r
+     * @access  protected\r
+     */\r
+    function _skipDelimitedStrings($query, $position, $p_position)\r
+    {\r
+        $ignores = array();\r
+        $ignores[] = $this->string_quoting;\r
+        $ignores[] = $this->identifier_quoting;\r
+        $ignores = array_merge($ignores, $this->sql_comments);\r
+        \r
+        foreach ($ignores as $ignore) {\r
+            if (!empty($ignore['start'])) {\r
+                if (is_int($start_quote = strpos($query, $ignore['start'], $position)) && $start_quote < $p_position) {\r
+                    $end_quote = $start_quote;\r
+                    do {\r
+                        if (!is_int($end_quote = strpos($query, $ignore['end'], $end_quote + 1))) {\r
+                            if ($ignore['end'] === "\n") {\r
+                                $end_quote = strlen($query) - 1;\r
+                            } else {\r
+                                $err = $this->raiseError(MDB2_ERROR_SYNTAX, null, null,\r
+                                    'query with an unterminated text string specified', __FUNCTION__);\r
+                                return $err;\r
+                            }\r
+                        }\r
+                    } while ($ignore['escape']\r
+                        && $end_quote-1 != $start_quote\r
+                        && $query[($end_quote - 1)] == $ignore['escape']\r
+                        && (   $ignore['escape_pattern'] !== $ignore['escape']\r
+                            || $query[($end_quote - 2)] != $ignore['escape'])\r
+                    );\r
+\r
+                    $position = $end_quote + 1;\r
+                    return $position;\r
+                }\r
+            }\r
+        }\r
+        return $position;\r
+    }\r
+    \r
+    // }}}\r
+    // {{{ function quote($value, $type = null, $quote = true)\r
+\r
+    /**\r
+     * Convert a text value into a DBMS specific format that is suitable to\r
+     * compose query statements.\r
+     *\r
+     * @param   string  text string value that is intended to be converted.\r
+     * @param   string  type to which the value should be converted to\r
+     * @param   bool    quote\r
+     * @param   bool    escape wildcards\r
+     *\r
+     * @return  string  text string that represents the given argument value in\r
+     *       a DBMS specific format.\r
+     *\r
+     * @access  public\r
+     */\r
+    function quote($value, $type = null, $quote = true, $escape_wildcards = false)\r
+    {\r
+        $result = $this->loadModule('Datatype', null, true);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+\r
+        return $this->datatype->quote($value, $type, $quote, $escape_wildcards);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function getDeclaration($type, $name, $field)\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare\r
+     * of the given type\r
+     *\r
+     * @param   string  type to which the value should be converted to\r
+     * @param   string  name the field to be declared.\r
+     * @param   string  definition of the field\r
+     *\r
+     * @return  string  DBMS specific SQL code portion that should be used to\r
+     *                 declare the specified field.\r
+     *\r
+     * @access  public\r
+     */\r
+    function getDeclaration($type, $name, $field)\r
+    {\r
+        $result = $this->loadModule('Datatype', null, true);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        return $this->datatype->getDeclaration($type, $name, $field);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function compareDefinition($current, $previous)\r
+\r
+    /**\r
+     * Obtain an array of changes that may need to applied\r
+     *\r
+     * @param   array   new definition\r
+     * @param   array   old definition\r
+     *\r
+     * @return  array   containing all changes that will need to be applied\r
+     *\r
+     * @access  public\r
+     */\r
+    function compareDefinition($current, $previous)\r
+    {\r
+        $result = $this->loadModule('Datatype', null, true);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        return $this->datatype->compareDefinition($current, $previous);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function supports($feature)\r
+\r
+    /**\r
+     * Tell whether a DB implementation or its backend extension\r
+     * supports a given feature.\r
+     *\r
+     * @param   string  name of the feature (see the MDB2 class doc)\r
+     *\r
+     * @return  bool|string if this DB implementation supports a given feature\r
+     *                      false means no, true means native,\r
+     *                      'emulated' means emulated\r
+     *\r
+     * @access  public\r
+     */\r
+    function supports($feature)\r
+    {\r
+        if (array_key_exists($feature, $this->supported)) {\r
+            return $this->supported[$feature];\r
+        }\r
+        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            "unknown support feature $feature", __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function getSequenceName($sqn)\r
+\r
+    /**\r
+     * adds sequence name formatting to a sequence name\r
+     *\r
+     * @param   string  name of the sequence\r
+     *\r
+     * @return  string  formatted sequence name\r
+     *\r
+     * @access  public\r
+     */\r
+    function getSequenceName($sqn)\r
+    {\r
+        return sprintf($this->options['seqname_format'],\r
+            preg_replace('/[^a-z0-9_\-\$.]/i', '_', $sqn));\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function getIndexName($idx)\r
+\r
+    /**\r
+     * adds index name formatting to a index name\r
+     *\r
+     * @param   string  name of the index\r
+     *\r
+     * @return  string  formatted index name\r
+     *\r
+     * @access  public\r
+     */\r
+    function getIndexName($idx)\r
+    {\r
+        return sprintf($this->options['idxname_format'],\r
+            preg_replace('/[^a-z0-9_\-\$.]/i', '_', $idx));\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function nextID($seq_name, $ondemand = true)\r
+\r
+    /**\r
+     * Returns the next free id of a sequence\r
+     *\r
+     * @param   string  name of the sequence\r
+     * @param   bool    when true missing sequences are automatic created\r
+     *\r
+     * @return  mixed   MDB2 Error Object or id\r
+     *\r
+     * @access  public\r
+     */\r
+    function nextID($seq_name, $ondemand = true)\r
+    {\r
+        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function lastInsertID($table = null, $field = null)\r
+\r
+    /**\r
+     * Returns the autoincrement ID if supported or $id or fetches the current\r
+     * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)\r
+     *\r
+     * @param   string  name of the table into which a new row was inserted\r
+     * @param   string  name of the field into which a new row was inserted\r
+     *\r
+     * @return  mixed   MDB2 Error Object or id\r
+     *\r
+     * @access  public\r
+     */\r
+    function lastInsertID($table = null, $field = null)\r
+    {\r
+        return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function currID($seq_name)\r
+\r
+    /**\r
+     * Returns the current id of a sequence\r
+     *\r
+     * @param   string  name of the sequence\r
+     *\r
+     * @return  mixed   MDB2 Error Object or id\r
+     *\r
+     * @access  public\r
+     */\r
+    function currID($seq_name)\r
+    {\r
+        $this->warnings[] = 'database does not support getting current\r
+            sequence value, the sequence value was incremented';\r
+        return $this->nextID($seq_name);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function queryOne($query, $type = null, $colnum = 0)\r
+\r
+    /**\r
+     * Execute the specified query, fetch the value from the first column of\r
+     * the first row of the result set and then frees\r
+     * the result set.\r
+     *\r
+     * @param string $query  the SELECT query statement to be executed.\r
+     * @param string $type   optional argument that specifies the expected\r
+     *                       datatype of the result set field, so that an eventual\r
+     *                       conversion may be performed. The default datatype is\r
+     *                       text, meaning that no conversion is performed\r
+     * @param mixed  $colnum the column number (or name) to fetch\r
+     *\r
+     * @return  mixed   MDB2_OK or field value on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function queryOne($query, $type = null, $colnum = 0)\r
+    {\r
+        $result = $this->query($query, $type);\r
+        if (!MDB2::isResultCommon($result)) {\r
+            return $result;\r
+        }\r
+\r
+        $one = $result->fetchOne($colnum);\r
+        $result->free();\r
+        return $one;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)\r
+\r
+    /**\r
+     * Execute the specified query, fetch the values from the first\r
+     * row of the result set into an array and then frees\r
+     * the result set.\r
+     *\r
+     * @param   string  the SELECT query statement to be executed.\r
+     * @param   array   optional array argument that specifies a list of\r
+     *       expected datatypes of the result set columns, so that the eventual\r
+     *       conversions may be performed. The default list of datatypes is\r
+     *       empty, meaning that no conversion is performed.\r
+     * @param   int     how the array data should be indexed\r
+     *\r
+     * @return  mixed   MDB2_OK or data array on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)\r
+    {\r
+        $result = $this->query($query, $types);\r
+        if (!MDB2::isResultCommon($result)) {\r
+            return $result;\r
+        }\r
+\r
+        $row = $result->fetchRow($fetchmode);\r
+        $result->free();\r
+        return $row;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function queryCol($query, $type = null, $colnum = 0)\r
+\r
+    /**\r
+     * Execute the specified query, fetch the value from the first column of\r
+     * each row of the result set into an array and then frees the result set.\r
+     *\r
+     * @param string $query  the SELECT query statement to be executed.\r
+     * @param string $type   optional argument that specifies the expected\r
+     *                       datatype of the result set field, so that an eventual\r
+     *                       conversion may be performed. The default datatype is text,\r
+     *                       meaning that no conversion is performed\r
+     * @param mixed  $colnum the column number (or name) to fetch\r
+     *\r
+     * @return  mixed   MDB2_OK or data array on success, a MDB2 error on failure\r
+     * @access  public\r
+     */\r
+    function queryCol($query, $type = null, $colnum = 0)\r
+    {\r
+        $result = $this->query($query, $type);\r
+        if (!MDB2::isResultCommon($result)) {\r
+            return $result;\r
+        }\r
+\r
+        $col = $result->fetchCol($colnum);\r
+        $result->free();\r
+        return $col;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)\r
+\r
+    /**\r
+     * Execute the specified query, fetch all the rows of the result set into\r
+     * a two dimensional array and then frees the result set.\r
+     *\r
+     * @param   string  the SELECT query statement to be executed.\r
+     * @param   array   optional array argument that specifies a list of\r
+     *       expected datatypes of the result set columns, so that the eventual\r
+     *       conversions may be performed. The default list of datatypes is\r
+     *       empty, meaning that no conversion is performed.\r
+     * @param   int     how the array data should be indexed\r
+     * @param   bool    if set to true, the $all will have the first\r
+     *       column as its first dimension\r
+     * @param   bool    used only when the query returns exactly\r
+     *       two columns. If true, the values of the returned array will be\r
+     *       one-element arrays instead of scalars.\r
+     * @param   bool    if true, the values of the returned array is\r
+     *       wrapped in another array.  If the same key value (in the first\r
+     *       column) repeats itself, the values will be appended to this array\r
+     *       instead of overwriting the existing values.\r
+     *\r
+     * @return  mixed   MDB2_OK or data array on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT,\r
+        $rekey = false, $force_array = false, $group = false)\r
+    {\r
+        $result = $this->query($query, $types);\r
+        if (!MDB2::isResultCommon($result)) {\r
+            return $result;\r
+        }\r
+\r
+        $all = $result->fetchAll($fetchmode, $rekey, $force_array, $group);\r
+        $result->free();\r
+        return $all;\r
+    }\r
+\r
+    // }}}\r
+}\r
+\r
+// }}}\r
+// {{{ class MDB2_Result\r
+\r
+/**\r
+ * The dummy class that all user space result classes should extend from\r
+ *\r
+ * @package     MDB2\r
+ * @category    Database\r
+ * @author      Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Result\r
+{\r
+}\r
+\r
+// }}}\r
+// {{{ class MDB2_Result_Common extends MDB2_Result\r
+\r
+/**\r
+ * The common result class for MDB2 result objects\r
+ *\r
+ * @package     MDB2\r
+ * @category    Database\r
+ * @author      Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Result_Common extends MDB2_Result\r
+{\r
+    // {{{ Variables (Properties)\r
+\r
+    var $db;\r
+    var $result;\r
+    var $rownum = -1;\r
+    var $types = array();\r
+    var $values = array();\r
+    var $offset;\r
+    var $offset_count = 0;\r
+    var $limit;\r
+    var $column_names;\r
+\r
+    // }}}\r
+    // {{{ constructor: function __construct($db, &$result, $limit = 0, $offset = 0)\r
+\r
+    /**\r
+     * Constructor\r
+     */\r
+    function __construct($db, &$result, $limit = 0, $offset = 0)\r
+    {\r
+        $this->db = $db;\r
+        $this->result = $result;\r
+        $this->offset = $offset;\r
+        $this->limit = max(0, $limit - 1);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function setResultTypes($types)\r
+\r
+    /**\r
+     * Define the list of types to be associated with the columns of a given\r
+     * result set.\r
+     *\r
+     * This function may be called before invoking fetchRow(), fetchOne(),\r
+     * fetchCol() and fetchAll() so that the necessary data type\r
+     * conversions are performed on the data to be retrieved by them. If this\r
+     * function is not called, the type of all result set columns is assumed\r
+     * to be text, thus leading to not perform any conversions.\r
+     *\r
+     * @param   array   variable that lists the\r
+     *       data types to be expected in the result set columns. If this array\r
+     *       contains less types than the number of columns that are returned\r
+     *       in the result set, the remaining columns are assumed to be of the\r
+     *       type text. Currently, the types clob and blob are not fully\r
+     *       supported.\r
+     *\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function setResultTypes($types)\r
+    {\r
+        $load = $this->db->loadModule('Datatype', null, true);\r
+        if (PEAR::isError($load)) {\r
+            return $load;\r
+        }\r
+        $types = $this->db->datatype->checkResultTypes($types);\r
+        if (PEAR::isError($types)) {\r
+            return $types;\r
+        }\r
+        $this->types = $types;\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function seek($rownum = 0)\r
+\r
+    /**\r
+     * Seek to a specific row in a result set\r
+     *\r
+     * @param   int     number of the row where the data can be found\r
+     *\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function seek($rownum = 0)\r
+    {\r
+        $target_rownum = $rownum - 1;\r
+        if ($this->rownum > $target_rownum) {\r
+            return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'seeking to previous rows not implemented', __FUNCTION__);\r
+        }\r
+        while ($this->rownum < $target_rownum) {\r
+            $this->fetchRow();\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)\r
+\r
+    /**\r
+     * Fetch and return a row of data\r
+     *\r
+     * @param   int     how the array data should be indexed\r
+     * @param   int     number of the row where the data can be found\r
+     *\r
+     * @return  int     data array on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)\r
+    {\r
+        $err = $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+        return $err;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function fetchOne($colnum = 0)\r
+\r
+    /**\r
+     * fetch single column from the next row from a result set\r
+     *\r
+     * @param int|string the column number (or name) to fetch\r
+     * @param int        number of the row where the data can be found\r
+     *\r
+     * @return string data on success, a MDB2 error on failure\r
+     * @access  public\r
+     */\r
+    function fetchOne($colnum = 0, $rownum = null)\r
+    {\r
+        $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;\r
+        $row = $this->fetchRow($fetchmode, $rownum);\r
+        if (!is_array($row) || PEAR::isError($row)) {\r
+            return $row;\r
+        }\r
+        if (!array_key_exists($colnum, $row)) {\r
+            return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,\r
+                'column is not defined in the result set: '.$colnum, __FUNCTION__);\r
+        }\r
+        return $row[$colnum];\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function fetchCol($colnum = 0)\r
+\r
+    /**\r
+     * Fetch and return a column from the current row pointer position\r
+     *\r
+     * @param int|string the column number (or name) to fetch\r
+     *\r
+     * @return  mixed data array on success, a MDB2 error on failure\r
+     * @access  public\r
+     */\r
+    function fetchCol($colnum = 0)\r
+    {\r
+        $column = array();\r
+        $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;\r
+        $row = $this->fetchRow($fetchmode);\r
+        if (is_array($row)) {\r
+            if (!array_key_exists($colnum, $row)) {\r
+                return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,\r
+                    'column is not defined in the result set: '.$colnum, __FUNCTION__);\r
+            }\r
+            do {\r
+                $column[] = $row[$colnum];\r
+            } while (is_array($row = $this->fetchRow($fetchmode)));\r
+        }\r
+        if (PEAR::isError($row)) {\r
+            return $row;\r
+        }\r
+        return $column;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)\r
+\r
+    /**\r
+     * Fetch and return all rows from the current row pointer position\r
+     *\r
+     * @param   int     $fetchmode  the fetch mode to use:\r
+     *                            + MDB2_FETCHMODE_ORDERED\r
+     *                            + MDB2_FETCHMODE_ASSOC\r
+     *                            + MDB2_FETCHMODE_ORDERED | MDB2_FETCHMODE_FLIPPED\r
+     *                            + MDB2_FETCHMODE_ASSOC | MDB2_FETCHMODE_FLIPPED\r
+     * @param   bool    if set to true, the $all will have the first\r
+     *       column as its first dimension\r
+     * @param   bool    used only when the query returns exactly\r
+     *       two columns. If true, the values of the returned array will be\r
+     *       one-element arrays instead of scalars.\r
+     * @param   bool    if true, the values of the returned array is\r
+     *       wrapped in another array.  If the same key value (in the first\r
+     *       column) repeats itself, the values will be appended to this array\r
+     *       instead of overwriting the existing values.\r
+     *\r
+     * @return  mixed   data array on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     * @see     getAssoc()\r
+     */\r
+    function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false,\r
+        $force_array = false, $group = false)\r
+    {\r
+        $all = array();\r
+        $row = $this->fetchRow($fetchmode);\r
+        if (PEAR::isError($row)) {\r
+            return $row;\r
+        } elseif (!$row) {\r
+            return $all;\r
+        }\r
+\r
+        $shift_array = $rekey ? false : null;\r
+        if (null !== $shift_array) {\r
+            if (is_object($row)) {\r
+                $colnum = count(get_object_vars($row));\r
+            } else {\r
+                $colnum = count($row);\r
+            }\r
+            if ($colnum < 2) {\r
+                return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,\r
+                    'rekey feature requires atleast 2 column', __FUNCTION__);\r
+            }\r
+            $shift_array = (!$force_array && $colnum == 2);\r
+        }\r
+\r
+        if ($rekey) {\r
+            do {\r
+                if (is_object($row)) {\r
+                    $arr = get_object_vars($row);\r
+                    $key = reset($arr);\r
+                    unset($row->{$key});\r
+                } else {\r
+                    if ($fetchmode & MDB2_FETCHMODE_ASSOC) {\r
+                        $key = reset($row);\r
+                        unset($row[key($row)]);\r
+                    } else {\r
+                        $key = array_shift($row);\r
+                    }\r
+                    if ($shift_array) {\r
+                        $row = array_shift($row);\r
+                    }\r
+                }\r
+                if ($group) {\r
+                    $all[$key][] = $row;\r
+                } else {\r
+                    $all[$key] = $row;\r
+                }\r
+            } while (($row = $this->fetchRow($fetchmode)));\r
+        } elseif ($fetchmode & MDB2_FETCHMODE_FLIPPED) {\r
+            do {\r
+                foreach ($row as $key => $val) {\r
+                    $all[$key][] = $val;\r
+                }\r
+            } while (($row = $this->fetchRow($fetchmode)));\r
+        } else {\r
+            do {\r
+                $all[] = $row;\r
+            } while (($row = $this->fetchRow($fetchmode)));\r
+        }\r
+\r
+        return $all;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function rowCount()\r
+    /**\r
+     * Returns the actual row number that was last fetched (count from 0)\r
+     * @return  int\r
+     *\r
+     * @access  public\r
+     */\r
+    function rowCount()\r
+    {\r
+        return $this->rownum + 1;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function numRows()\r
+\r
+    /**\r
+     * Returns the number of rows in a result object\r
+     *\r
+     * @return  mixed   MDB2 Error Object or the number of rows\r
+     *\r
+     * @access  public\r
+     */\r
+    function numRows()\r
+    {\r
+        return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function nextResult()\r
+\r
+    /**\r
+     * Move the internal result pointer to the next available result\r
+     *\r
+     * @return  true on success, false if there is no more result set or an error object on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function nextResult()\r
+    {\r
+        return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function getColumnNames()\r
+\r
+    /**\r
+     * Retrieve the names of columns returned by the DBMS in a query result or\r
+     * from the cache.\r
+     *\r
+     * @param   bool    If set to true the values are the column names,\r
+     *                  otherwise the names of the columns are the keys.\r
+     * @return  mixed   Array variable that holds the names of columns or an\r
+     *                  MDB2 error on failure.\r
+     *                  Some DBMS may not return any columns when the result set\r
+     *                  does not contain any rows.\r
+     *\r
+     * @access  public\r
+     */\r
+    function getColumnNames($flip = false)\r
+    {\r
+        if (!isset($this->column_names)) {\r
+            $result = $this->_getColumnNames();\r
+            if (PEAR::isError($result)) {\r
+                return $result;\r
+            }\r
+            $this->column_names = $result;\r
+        }\r
+        if ($flip) {\r
+            return array_flip($this->column_names);\r
+        }\r
+        return $this->column_names;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function _getColumnNames()\r
+\r
+    /**\r
+     * Retrieve the names of columns returned by the DBMS in a query result.\r
+     *\r
+     * @return  mixed   Array variable that holds the names of columns as keys\r
+     *                  or an MDB2 error on failure.\r
+     *                  Some DBMS may not return any columns when the result set\r
+     *                  does not contain any rows.\r
+     *\r
+     * @access  private\r
+     */\r
+    function _getColumnNames()\r
+    {\r
+        return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function numCols()\r
+\r
+    /**\r
+     * Count the number of columns returned by the DBMS in a query result.\r
+     *\r
+     * @return  mixed   integer value with the number of columns, a MDB2 error\r
+     *       on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function numCols()\r
+    {\r
+        return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function getResource()\r
+\r
+    /**\r
+     * return the resource associated with the result object\r
+     *\r
+     * @return  resource\r
+     *\r
+     * @access  public\r
+     */\r
+    function getResource()\r
+    {\r
+        return $this->result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function bindColumn($column, &$value, $type = null)\r
+\r
+    /**\r
+     * Set bind variable to a column.\r
+     *\r
+     * @param   int     column number or name\r
+     * @param   mixed   variable reference\r
+     * @param   string  specifies the type of the field\r
+     *\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function bindColumn($column, &$value, $type = null)\r
+    {\r
+        if (!is_numeric($column)) {\r
+            $column_names = $this->getColumnNames();\r
+            if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+                if ($this->db->options['field_case'] == CASE_LOWER) {\r
+                    $column = strtolower($column);\r
+                } else {\r
+                    $column = strtoupper($column);\r
+                }\r
+            }\r
+            $column = $column_names[$column];\r
+        }\r
+        $this->values[$column] =& $value;\r
+        if (null !== $type) {\r
+            $this->types[$column] = $type;\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function _assignBindColumns($row)\r
+\r
+    /**\r
+     * Bind a variable to a value in the result row.\r
+     *\r
+     * @param   array   row data\r
+     *\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  private\r
+     */\r
+    function _assignBindColumns($row)\r
+    {\r
+        $row = array_values($row);\r
+        foreach ($row as $column => $value) {\r
+            if (array_key_exists($column, $this->values)) {\r
+                $this->values[$column] = $value;\r
+            }\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function free()\r
+\r
+    /**\r
+     * Free the internal resources associated with result.\r
+     *\r
+     * @return  bool    true on success, false if result is invalid\r
+     *\r
+     * @access  public\r
+     */\r
+    function free()\r
+    {\r
+        $this->result = false;\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+}\r
+\r
+// }}}\r
+// {{{ class MDB2_Row\r
+\r
+/**\r
+ * The simple class that accepts row data as an array\r
+ *\r
+ * @package     MDB2\r
+ * @category    Database\r
+ * @author      Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Row\r
+{\r
+    // {{{ constructor: function __construct(&$row)\r
+\r
+    /**\r
+     * constructor\r
+     *\r
+     * @param   resource    row data as array\r
+     */\r
+    function __construct(&$row)\r
+    {\r
+        foreach ($row as $key => $value) {\r
+            $this->$key = &$row[$key];\r
+        }\r
+    }\r
+\r
+    // }}}\r
+}\r
+\r
+// }}}\r
+// {{{ class MDB2_Statement_Common\r
+\r
+/**\r
+ * The common statement class for MDB2 statement objects\r
+ *\r
+ * @package     MDB2\r
+ * @category    Database\r
+ * @author      Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Statement_Common\r
+{\r
+    // {{{ Variables (Properties)\r
+\r
+    var $db;\r
+    var $statement;\r
+    var $query;\r
+    var $result_types;\r
+    var $types;\r
+    var $values = array();\r
+    var $limit;\r
+    var $offset;\r
+    var $is_manip;\r
+\r
+    // }}}\r
+    // {{{ constructor: function __construct($db, $statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)\r
+\r
+    /**\r
+     * Constructor\r
+     */\r
+    function __construct($db, $statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)\r
+    {\r
+        $this->db = $db;\r
+        $this->statement = $statement;\r
+        $this->positions = $positions;\r
+        $this->query = $query;\r
+        $this->types = (array)$types;\r
+        $this->result_types = (array)$result_types;\r
+        $this->limit = $limit;\r
+        $this->is_manip = $is_manip;\r
+        $this->offset = $offset;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function bindValue($parameter, &$value, $type = null)\r
+\r
+    /**\r
+     * Set the value of a parameter of a prepared query.\r
+     *\r
+     * @param   int     the order number of the parameter in the query\r
+     *       statement. The order number of the first parameter is 1.\r
+     * @param   mixed   value that is meant to be assigned to specified\r
+     *       parameter. The type of the value depends on the $type argument.\r
+     * @param   string  specifies the type of the field\r
+     *\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function bindValue($parameter, $value, $type = null)\r
+    {\r
+        if (!is_numeric($parameter)) {\r
+            $parameter = preg_replace('/^:(.*)$/', '\\1', $parameter);\r
+        }\r
+        if (!in_array($parameter, $this->positions)) {\r
+            return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);\r
+        }\r
+        $this->values[$parameter] = $value;\r
+        if (null !== $type) {\r
+            $this->types[$parameter] = $type;\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function bindValueArray($values, $types = null)\r
+\r
+    /**\r
+     * Set the values of multiple a parameter of a prepared query in bulk.\r
+     *\r
+     * @param   array   specifies all necessary information\r
+     *       for bindValue() the array elements must use keys corresponding to\r
+     *       the number of the position of the parameter.\r
+     * @param   array   specifies the types of the fields\r
+     *\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     * @see     bindParam()\r
+     */\r
+    function bindValueArray($values, $types = null)\r
+    {\r
+        $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);\r
+        $parameters = array_keys($values);\r
+        foreach ($parameters as $key => $parameter) {\r
+            $this->db->pushErrorHandling(PEAR_ERROR_RETURN);\r
+            $this->db->expectError(MDB2_ERROR_NOT_FOUND);\r
+            $err = $this->bindValue($parameter, $values[$parameter], $types[$key]);\r
+            $this->db->popExpect();\r
+            $this->db->popErrorHandling();\r
+            if (PEAR::isError($err)) {\r
+                if ($err->getCode() == MDB2_ERROR_NOT_FOUND) {\r
+                    //ignore (extra value for missing placeholder)\r
+                    continue;\r
+                }\r
+                return $err;\r
+            }\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function bindParam($parameter, &$value, $type = null)\r
+\r
+    /**\r
+     * Bind a variable to a parameter of a prepared query.\r
+     *\r
+     * @param   int     the order number of the parameter in the query\r
+     *       statement. The order number of the first parameter is 1.\r
+     * @param   mixed   variable that is meant to be bound to specified\r
+     *       parameter. The type of the value depends on the $type argument.\r
+     * @param   string  specifies the type of the field\r
+     *\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function bindParam($parameter, &$value, $type = null)\r
+    {\r
+        if (!is_numeric($parameter)) {\r
+            $parameter = preg_replace('/^:(.*)$/', '\\1', $parameter);\r
+        }\r
+        if (!in_array($parameter, $this->positions)) {\r
+            return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);\r
+        }\r
+        $this->values[$parameter] =& $value;\r
+        if (null !== $type) {\r
+            $this->types[$parameter] = $type;\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function bindParamArray(&$values, $types = null)\r
+\r
+    /**\r
+     * Bind the variables of multiple a parameter of a prepared query in bulk.\r
+     *\r
+     * @param   array   specifies all necessary information\r
+     *       for bindParam() the array elements must use keys corresponding to\r
+     *       the number of the position of the parameter.\r
+     * @param   array   specifies the types of the fields\r
+     *\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     * @see     bindParam()\r
+     */\r
+    function bindParamArray(&$values, $types = null)\r
+    {\r
+        $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);\r
+        $parameters = array_keys($values);\r
+        foreach ($parameters as $key => $parameter) {\r
+            $err = $this->bindParam($parameter, $values[$parameter], $types[$key]);\r
+            if (PEAR::isError($err)) {\r
+                return $err;\r
+            }\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function &execute($values = null, $result_class = true, $result_wrap_class = false)\r
+\r
+    /**\r
+     * Execute a prepared query statement.\r
+     *\r
+     * @param array specifies all necessary information\r
+     *              for bindParam() the array elements must use keys corresponding\r
+     *              to the number of the position of the parameter.\r
+     * @param mixed specifies which result class to use\r
+     * @param mixed specifies which class to wrap results in\r
+     *\r
+     * @return mixed MDB2_Result or integer (affected rows) on success,\r
+     *               a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function execute($values = null, $result_class = true, $result_wrap_class = false)\r
+    {\r
+        if (null === $this->positions) {\r
+            return $this->db->raiseError(MDB2_ERROR, null, null,\r
+                'Prepared statement has already been freed', __FUNCTION__);\r
+        }\r
+\r
+        $values = (array)$values;\r
+        if (!empty($values)) {\r
+            $err = $this->bindValueArray($values);\r
+            if (PEAR::isError($err)) {\r
+                return $this->db->raiseError(MDB2_ERROR, null, null,\r
+                                            'Binding Values failed with message: ' . $err->getMessage(), __FUNCTION__);\r
+            }\r
+        }\r
+        $result = $this->_execute($result_class, $result_wrap_class);\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function _execute($result_class = true, $result_wrap_class = false)\r
+\r
+    /**\r
+     * Execute a prepared query statement helper method.\r
+     *\r
+     * @param   mixed   specifies which result class to use\r
+     * @param   mixed   specifies which class to wrap results in\r
+     *\r
+     * @return mixed MDB2_Result or integer (affected rows) on success,\r
+     *               a MDB2 error on failure\r
+     * @access  private\r
+     */\r
+    function _execute($result_class = true, $result_wrap_class = false)\r
+    {\r
+        $this->last_query = $this->query;\r
+        $query = '';\r
+        $last_position = 0;\r
+        foreach ($this->positions as $current_position => $parameter) {\r
+            if (!array_key_exists($parameter, $this->values)) {\r
+                return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                    'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);\r
+            }\r
+            $value = $this->values[$parameter];\r
+            $query.= substr($this->query, $last_position, $current_position - $last_position);\r
+            if (!isset($value)) {\r
+                $value_quoted = 'NULL';\r
+            } else {\r
+                $type = !empty($this->types[$parameter]) ? $this->types[$parameter] : null;\r
+                $value_quoted = $this->db->quote($value, $type);\r
+                if (PEAR::isError($value_quoted)) {\r
+                    return $value_quoted;\r
+                }\r
+            }\r
+            $query.= $value_quoted;\r
+            $last_position = $current_position + 1;\r
+        }\r
+        $query.= substr($this->query, $last_position);\r
+\r
+        $this->db->offset = $this->offset;\r
+        $this->db->limit = $this->limit;\r
+        if ($this->is_manip) {\r
+            $result = $this->db->exec($query);\r
+        } else {\r
+            $result = $this->db->query($query, $this->result_types, $result_class, $result_wrap_class);\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function free()\r
+\r
+    /**\r
+     * Release resources allocated for the specified prepared query.\r
+     *\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function free()\r
+    {\r
+        if (null === $this->positions) {\r
+            return $this->db->raiseError(MDB2_ERROR, null, null,\r
+                'Prepared statement has already been freed', __FUNCTION__);\r
+        }\r
+\r
+        $this->statement = null;\r
+        $this->positions = null;\r
+        $this->query = null;\r
+        $this->types = null;\r
+        $this->result_types = null;\r
+        $this->limit = null;\r
+        $this->is_manip = null;\r
+        $this->offset = null;\r
+        $this->values = null;\r
+\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+}\r
+\r
+// }}}\r
+// {{{ class MDB2_Module_Common\r
+\r
+/**\r
+ * The common modules class for MDB2 module objects\r
+ *\r
+ * @package     MDB2\r
+ * @category    Database\r
+ * @author      Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Module_Common\r
+{\r
+    // {{{ Variables (Properties)\r
+\r
+    /**\r
+     * contains the key to the global MDB2 instance array of the associated\r
+     * MDB2 instance\r
+     *\r
+     * @var     int\r
+     * @access  protected\r
+     */\r
+    var $db_index;\r
+\r
+    // }}}\r
+    // {{{ constructor: function __construct($db_index)\r
+\r
+    /**\r
+     * Constructor\r
+     */\r
+    function __construct($db_index)\r
+    {\r
+        $this->db_index = $db_index;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function getDBInstance()\r
+\r
+    /**\r
+     * Get the instance of MDB2 associated with the module instance\r
+     *\r
+     * @return  object  MDB2 instance or a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function getDBInstance()\r
+    {\r
+        if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {\r
+            $result = $GLOBALS['_MDB2_databases'][$this->db_index];\r
+        } else {\r
+            $result = MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                'could not find MDB2 instance');\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+}\r
+\r
+// }}}\r
+// {{{ function MDB2_closeOpenTransactions()\r
+\r
+/**\r
+ * Close any open transactions form persistent connections\r
+ *\r
+ * @return  void\r
+ *\r
+ * @access  public\r
+ */\r
+\r
+function MDB2_closeOpenTransactions()\r
+{\r
+    reset($GLOBALS['_MDB2_databases']);\r
+    while (next($GLOBALS['_MDB2_databases'])) {\r
+        $key = key($GLOBALS['_MDB2_databases']);\r
+        if ($GLOBALS['_MDB2_databases'][$key]->opened_persistent\r
+            && $GLOBALS['_MDB2_databases'][$key]->in_transaction\r
+        ) {\r
+            $GLOBALS['_MDB2_databases'][$key]->rollback();\r
+        }\r
+    }\r
+}\r
+\r
+// }}}\r
+// {{{ function MDB2_defaultDebugOutput(&$db, $scope, $message, $is_manip = null)\r
+\r
+/**\r
+ * default debug output handler\r
+ *\r
+ * @param   object  reference to an MDB2 database object\r
+ * @param   string  usually the method name that triggered the debug call:\r
+ *                  for example 'query', 'prepare', 'execute', 'parameters',\r
+ *                  'beginTransaction', 'commit', 'rollback'\r
+ * @param   string  message that should be appended to the debug variable\r
+ * @param   array   contains context information about the debug() call\r
+ *                  common keys are: is_manip, time, result etc.\r
+ *\r
+ * @return  void|string optionally return a modified message, this allows\r
+ *                      rewriting a query before being issued or prepared\r
+ *\r
+ * @access  public\r
+ */\r
+function MDB2_defaultDebugOutput(&$db, $scope, $message, $context = array())\r
+{\r
+    $db->debug_output.= $scope.'('.$db->db_index.'): ';\r
+    $db->debug_output.= $message.$db->getOption('log_line_break');\r
+    return $message;\r
+}\r
+\r
+// }}}\r
+?>
\ No newline at end of file
index ce846543a50e8383fe1fa2140ec8903c8a48daf2..d874531150f75a43c3763d380b74ae670a53ea48 100644 (file)
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: Date.php,v 1.10 2006/03/01 12:15:32 lsmith Exp $
-//
-
-/**
- * @package  MDB2
- * @category Database
- * @author   Lukas Smith <smith@pooteeweet.org>
- */
-
-/**
- * Several methods to convert the MDB2 native timestamp format (ISO based)
- * to and from data structures that are convenient to worth with in side of php.
- * For more complex date arithmetic please take a look at the Date package in PEAR
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Date
-{
-    // {{{ mdbNow()
-
-    /**
-     * return the current datetime
-     *
-     * @return string current datetime in the MDB2 format
-     * @access public
-     */
-    function mdbNow()
-    {
-        return date('Y-m-d H:i:s');
-    }
-    // }}}
-
-    // {{{ mdbToday()
-
-    /**
-     * return the current date
-     *
-     * @return string current date in the MDB2 format
-     * @access public
-     */
-    function mdbToday()
-    {
-        return date('Y-m-d');
-    }
-    // }}}
-
-    // {{{ mdbTime()
-
-    /**
-     * return the current time
-     *
-     * @return string current time in the MDB2 format
-     * @access public
-     */
-    function mdbTime()
-    {
-        return date('H:i:s');
-    }
-    // }}}
-
-    // {{{ date2Mdbstamp()
-
-    /**
-     * convert a date into a MDB2 timestamp
-     *
-     * @param int hour of the date
-     * @param int minute of the date
-     * @param int second of the date
-     * @param int month of the date
-     * @param int day of the date
-     * @param int year of the date
-     *
-     * @return string a valid MDB2 timestamp
-     * @access public
-     */
-    function date2Mdbstamp($hour = null, $minute = null, $second = null,
-        $month = null, $day = null, $year = null)
-    {
-        return MDB2_Date::unix2Mdbstamp(mktime($hour, $minute, $second, $month, $day, $year, -1));
-    }
-    // }}}
-
-    // {{{ unix2Mdbstamp()
-
-    /**
-     * convert a unix timestamp into a MDB2 timestamp
-     *
-     * @param int a valid unix timestamp
-     *
-     * @return string a valid MDB2 timestamp
-     * @access public
-     */
-    function unix2Mdbstamp($unix_timestamp)
-    {
-        return date('Y-m-d H:i:s', $unix_timestamp);
-    }
-    // }}}
-
-    // {{{ mdbstamp2Unix()
-
-    /**
-     * convert a MDB2 timestamp into a unix timestamp
-     *
-     * @param int a valid MDB2 timestamp
-     * @return string unix timestamp with the time stored in the MDB2 format
-     *
-     * @access public
-     */
-    function mdbstamp2Unix($mdb_timestamp)
-    {
-        $arr = MDB2_Date::mdbstamp2Date($mdb_timestamp);
-
-        return mktime($arr['hour'], $arr['minute'], $arr['second'], $arr['month'], $arr['day'], $arr['year'], -1);
-    }
-    // }}}
-
-    // {{{ mdbstamp2Date()
-
-    /**
-     * convert a MDB2 timestamp into an array containing all
-     * values necessary to pass to php's date() function
-     *
-     * @param int a valid MDB2 timestamp
-     *
-     * @return array with the time split
-     * @access public
-     */
-    function mdbstamp2Date($mdb_timestamp)
-    {
-        list($arr['year'], $arr['month'], $arr['day'], $arr['hour'], $arr['minute'], $arr['second']) =
-            sscanf($mdb_timestamp, "%04u-%02u-%02u %02u:%02u:%02u");
-        return $arr;
-    }
-    // }}}
-}
-
-?>
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: Date.php 208329 2006-03-01 12:15:38Z lsmith $\r
+//\r
+\r
+/**\r
+ * @package  MDB2\r
+ * @category Database\r
+ * @author   Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+\r
+/**\r
+ * Several methods to convert the MDB2 native timestamp format (ISO based)\r
+ * to and from data structures that are convenient to worth with in side of php.\r
+ * For more complex date arithmetic please take a look at the Date package in PEAR\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Date\r
+{\r
+    // {{{ mdbNow()\r
+\r
+    /**\r
+     * return the current datetime\r
+     *\r
+     * @return string current datetime in the MDB2 format\r
+     * @access public\r
+     */\r
+    function mdbNow()\r
+    {\r
+        return date('Y-m-d H:i:s');\r
+    }\r
+    // }}}\r
+\r
+    // {{{ mdbToday()\r
+\r
+    /**\r
+     * return the current date\r
+     *\r
+     * @return string current date in the MDB2 format\r
+     * @access public\r
+     */\r
+    function mdbToday()\r
+    {\r
+        return date('Y-m-d');\r
+    }\r
+    // }}}\r
+\r
+    // {{{ mdbTime()\r
+\r
+    /**\r
+     * return the current time\r
+     *\r
+     * @return string current time in the MDB2 format\r
+     * @access public\r
+     */\r
+    function mdbTime()\r
+    {\r
+        return date('H:i:s');\r
+    }\r
+    // }}}\r
+\r
+    // {{{ date2Mdbstamp()\r
+\r
+    /**\r
+     * convert a date into a MDB2 timestamp\r
+     *\r
+     * @param int hour of the date\r
+     * @param int minute of the date\r
+     * @param int second of the date\r
+     * @param int month of the date\r
+     * @param int day of the date\r
+     * @param int year of the date\r
+     *\r
+     * @return string a valid MDB2 timestamp\r
+     * @access public\r
+     */\r
+    function date2Mdbstamp($hour = null, $minute = null, $second = null,\r
+        $month = null, $day = null, $year = null)\r
+    {\r
+        return MDB2_Date::unix2Mdbstamp(mktime($hour, $minute, $second, $month, $day, $year, -1));\r
+    }\r
+    // }}}\r
+\r
+    // {{{ unix2Mdbstamp()\r
+\r
+    /**\r
+     * convert a unix timestamp into a MDB2 timestamp\r
+     *\r
+     * @param int a valid unix timestamp\r
+     *\r
+     * @return string a valid MDB2 timestamp\r
+     * @access public\r
+     */\r
+    function unix2Mdbstamp($unix_timestamp)\r
+    {\r
+        return date('Y-m-d H:i:s', $unix_timestamp);\r
+    }\r
+    // }}}\r
+\r
+    // {{{ mdbstamp2Unix()\r
+\r
+    /**\r
+     * convert a MDB2 timestamp into a unix timestamp\r
+     *\r
+     * @param int a valid MDB2 timestamp\r
+     * @return string unix timestamp with the time stored in the MDB2 format\r
+     *\r
+     * @access public\r
+     */\r
+    function mdbstamp2Unix($mdb_timestamp)\r
+    {\r
+        $arr = MDB2_Date::mdbstamp2Date($mdb_timestamp);\r
+\r
+        return mktime($arr['hour'], $arr['minute'], $arr['second'], $arr['month'], $arr['day'], $arr['year'], -1);\r
+    }\r
+    // }}}\r
+\r
+    // {{{ mdbstamp2Date()\r
+\r
+    /**\r
+     * convert a MDB2 timestamp into an array containing all\r
+     * values necessary to pass to php's date() function\r
+     *\r
+     * @param int a valid MDB2 timestamp\r
+     *\r
+     * @return array with the time split\r
+     * @access public\r
+     */\r
+    function mdbstamp2Date($mdb_timestamp)\r
+    {\r
+        list($arr['year'], $arr['month'], $arr['day'], $arr['hour'], $arr['minute'], $arr['second']) =\r
+            sscanf($mdb_timestamp, "%04u-%02u-%02u %02u:%02u:%02u");\r
+        return $arr;\r
+    }\r
+    // }}}\r
+}\r
+\r
+?>\r
index 85a74f64fca85f3d06ae56284f248eb27428ecae..db0cb45dd892c023b452c2e4088faf4c394ce8d4 100644 (file)
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: Common.php,v 1.139 2008/12/04 11:50:42 afz Exp $
-
-require_once('MDB2/LOB.php');
-
-/**
- * @package  MDB2
- * @category Database
- * @author   Lukas Smith <smith@pooteeweet.org>
- */
-
-/**
- * MDB2_Driver_Common: Base class that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Datatype');
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Datatype_Common extends MDB2_Module_Common
-{
-    var $valid_default_values = array(
-        'text'      => '',
-        'boolean'   => true,
-        'integer'   => 0,
-        'decimal'   => 0.0,
-        'float'     => 0.0,
-        'timestamp' => '1970-01-01 00:00:00',
-        'time'      => '00:00:00',
-        'date'      => '1970-01-01',
-        'clob'      => '',
-        'blob'      => '',
-    );
-
-    /**
-     * contains all LOB objects created with this MDB2 instance
-     * @var array
-     * @access protected
-     */
-    var $lobs = array();
-
-    // }}}
-    // {{{ getValidTypes()
-
-    /**
-     * Get the list of valid types
-     *
-     * This function returns an array of valid types as keys with the values
-     * being possible default values for all native datatypes and mapped types
-     * for custom datatypes.
-     *
-     * @return mixed array on success, a MDB2 error on failure
-     * @access public
-     */
-    function getValidTypes()
-    {
-        $types = $this->valid_default_values;
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-        if (!empty($db->options['datatype_map'])) {
-            foreach ($db->options['datatype_map'] as $type => $mapped_type) {
-                if (array_key_exists($mapped_type, $types)) {
-                    $types[$type] = $types[$mapped_type];
-                } elseif (!empty($db->options['datatype_map_callback'][$type])) {
-                    $parameter = array('type' => $type, 'mapped_type' => $mapped_type);
-                    $default =  call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
-                    $types[$type] = $default;
-                }
-            }
-        }
-        return $types;
-    }
-
-    // }}}
-    // {{{ checkResultTypes()
-
-    /**
-     * Define the list of types to be associated with the columns of a given
-     * result set.
-     *
-     * This function may be called before invoking fetchRow(), fetchOne()
-     * fetchCole() and fetchAll() so that the necessary data type
-     * conversions are performed on the data to be retrieved by them. If this
-     * function is not called, the type of all result set columns is assumed
-     * to be text, thus leading to not perform any conversions.
-     *
-     * @param array $types array variable that lists the
-     *       data types to be expected in the result set columns. If this array
-     *       contains less types than the number of columns that are returned
-     *       in the result set, the remaining columns are assumed to be of the
-     *       type text. Currently, the types clob and blob are not fully
-     *       supported.
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function checkResultTypes($types)
-    {
-        $types = is_array($types) ? $types : array($types);
-        foreach ($types as $key => $type) {
-            if (!isset($this->valid_default_values[$type])) {
-                $db =$this->getDBInstance();
-                if (PEAR::isError($db)) {
-                    return $db;
-                }
-                if (empty($db->options['datatype_map'][$type])) {
-                    return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                        $type.' for '.$key.' is not a supported column type', __FUNCTION__);
-                }
-            }
-        }
-        return $types;
-    }
-
-    // }}}
-    // {{{ _baseConvertResult()
-
-    /**
-     * General type conversion method
-     *
-     * @param mixed   $value reference to a value to be converted
-     * @param string  $type  specifies which type to convert to
-     * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text
-     * @return object an MDB2 error on failure
-     * @access protected
-     */
-    function _baseConvertResult($value, $type, $rtrim = true)
-    {
-        switch ($type) {
-        case 'text':
-            if ($rtrim) {
-                $value = rtrim($value);
-            }
-            return $value;
-        case 'integer':
-            return intval($value);
-        case 'boolean':
-            return !empty($value);
-        case 'decimal':
-            return $value;
-        case 'float':
-            return doubleval($value);
-        case 'date':
-            return $value;
-        case 'time':
-            return $value;
-        case 'timestamp':
-            return $value;
-        case 'clob':
-        case 'blob':
-            $this->lobs[] = array(
-                'buffer' => null,
-                'position' => 0,
-                'lob_index' => null,
-                'endOfLOB' => false,
-                'resource' => $value,
-                'value' => null,
-                'loaded' => false,
-            );
-            end($this->lobs);
-            $lob_index = key($this->lobs);
-            $this->lobs[$lob_index]['lob_index'] = $lob_index;
-            return fopen('MDB2LOB://'.$lob_index.'@'.$this->db_index, 'r+');
-        }
-
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_INVALID, null, null,
-            'attempt to convert result value to an unknown type :' . $type, __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ convertResult()
-
-    /**
-     * Convert a value to a RDBMS indipendent MDB2 type
-     *
-     * @param mixed   $value value to be converted
-     * @param string  $type  specifies which type to convert to
-     * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text
-     * @return mixed converted value
-     * @access public
-     */
-    function convertResult($value, $type, $rtrim = true)
-    {
-        if (is_null($value)) {
-            return null;
-        }
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-        if (!empty($db->options['datatype_map'][$type])) {
-            $type = $db->options['datatype_map'][$type];
-            if (!empty($db->options['datatype_map_callback'][$type])) {
-                $parameter = array('type' => $type, 'value' => $value, 'rtrim' => $rtrim);
-                return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
-            }
-        }
-        return $this->_baseConvertResult($value, $type, $rtrim);
-    }
-
-    // }}}
-    // {{{ convertResultRow()
-
-    /**
-     * Convert a result row
-     *
-     * @param array   $types
-     * @param array   $row   specifies the types to convert to
-     * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text
-     * @return mixed MDB2_OK on success, an MDB2 error on failure
-     * @access public
-     */
-    function convertResultRow($types, $row, $rtrim = true)
-    {
-        $types = $this->_sortResultFieldTypes(array_keys($row), $types);
-        foreach ($row as $key => $value) {
-            if (empty($types[$key])) {
-                continue;
-            }
-            $value = $this->convertResult($row[$key], $types[$key], $rtrim);
-            if (PEAR::isError($value)) {
-                return $value;
-            }
-            $row[$key] = $value;
-        }
-        return $row;
-    }
-
-    // }}}
-    // {{{ _sortResultFieldTypes()
-
-    /**
-     * convert a result row
-     *
-     * @param array $types
-     * @param array $row specifies the types to convert to
-     * @param bool   $rtrim   if to rtrim text values or not
-     * @return mixed MDB2_OK on success,  a MDB2 error on failure
-     * @access public
-     */
-    function _sortResultFieldTypes($columns, $types)
-    {
-        $n_cols = count($columns);
-        $n_types = count($types);
-        if ($n_cols > $n_types) {
-            for ($i= $n_cols - $n_types; $i >= 0; $i--) {
-                $types[] = null;
-            }
-        }
-        $sorted_types = array();
-        foreach ($columns as $col) {
-            $sorted_types[$col] = null;
-        }
-        foreach ($types as $name => $type) {
-            if (array_key_exists($name, $sorted_types)) {
-                $sorted_types[$name] = $type;
-                unset($types[$name]);
-            }
-        }
-        // if there are left types in the array, fill the null values of the
-        // sorted array with them, in order.
-        if (count($types)) {
-            reset($types);
-            foreach (array_keys($sorted_types) as $k) {
-                if (is_null($sorted_types[$k])) {
-                    $sorted_types[$k] = current($types);
-                    next($types);
-                }
-            }
-        }
-        return $sorted_types;
-    }
-
-    // }}}
-    // {{{ getDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare
-     * of the given type
-     *
-     * @param string $type type to which the value should be converted to
-     * @param string  $name   name the field to be declared.
-     * @param string  $field  definition of the field
-     * @return string  DBMS specific SQL code portion that should be used to
-     *                 declare the specified field.
-     * @access public
-     */
-    function getDeclaration($type, $name, $field)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        if (!empty($db->options['datatype_map'][$type])) {
-            $type = $db->options['datatype_map'][$type];
-            if (!empty($db->options['datatype_map_callback'][$type])) {
-                $parameter = array('type' => $type, 'name' => $name, 'field' => $field);
-                return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
-            }
-            $field['type'] = $type;
-        }
-
-        if (!method_exists($this, "_get{$type}Declaration")) {
-            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                'type not defined: '.$type, __FUNCTION__);
-        }
-        return $this->{"_get{$type}Declaration"}($name, $field);
-    }
-
-    // }}}
-    // {{{ getTypeDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare an text type
-     * field to be used in statements like CREATE TABLE.
-     *
-     * @param array $field  associative array with the name of the properties
-     *      of the field being declared as array indexes. Currently, the types
-     *      of supported field properties are as follows:
-     *
-     *      length
-     *          Integer value that determines the maximum length of the text
-     *          field. If this argument is missing the field should be
-     *          declared to have the longest length allowed by the DBMS.
-     *
-     *      default
-     *          Text value to be used as default for this field.
-     *
-     *      notnull
-     *          Boolean flag that indicates whether this field is constrained
-     *          to not be set to null.
-     * @return string  DBMS specific SQL code portion that should be used to
-     *      declare the specified field.
-     * @access public
-     */
-    function getTypeDeclaration($field)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        switch ($field['type']) {
-        case 'text':
-            $length = !empty($field['length']) ? $field['length'] : $db->options['default_text_field_length'];
-            $fixed = !empty($field['fixed']) ? $field['fixed'] : false;
-            return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')')
-                : ($length ? 'VARCHAR('.$length.')' : 'TEXT');
-        case 'clob':
-            return 'TEXT';
-        case 'blob':
-            return 'TEXT';
-        case 'integer':
-            return 'INT';
-        case 'boolean':
-            return 'INT';
-        case 'date':
-            return 'CHAR ('.strlen('YYYY-MM-DD').')';
-        case 'time':
-            return 'CHAR ('.strlen('HH:MM:SS').')';
-        case 'timestamp':
-            return 'CHAR ('.strlen('YYYY-MM-DD HH:MM:SS').')';
-        case 'float':
-            return 'TEXT';
-        case 'decimal':
-            return 'TEXT';
-        }
-        return '';
-    }
-
-    // }}}
-    // {{{ _getDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare a generic type
-     * field to be used in statements like CREATE TABLE.
-     *
-     * @param string $name   name the field to be declared.
-     * @param array  $field  associative array with the name of the properties
-     *      of the field being declared as array indexes. Currently, the types
-     *      of supported field properties are as follows:
-     *
-     *      length
-     *          Integer value that determines the maximum length of the text
-     *          field. If this argument is missing the field should be
-     *          declared to have the longest length allowed by the DBMS.
-     *
-     *      default
-     *          Text value to be used as default for this field.
-     *
-     *      notnull
-     *          Boolean flag that indicates whether this field is constrained
-     *          to not be set to null.
-     *      charset
-     *          Text value with the default CHARACTER SET for this field.
-     *      collation
-     *          Text value with the default COLLATION for this field.
-     * @return string  DBMS specific SQL code portion that should be used to
-     *      declare the specified field, or a MDB2_Error on failure
-     * @access protected
-     */
-    function _getDeclaration($name, $field)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $name = $db->quoteIdentifier($name, true);
-        $declaration_options = $db->datatype->_getDeclarationOptions($field);
-        if (PEAR::isError($declaration_options)) {
-            return $declaration_options;
-        }
-        return $name.' '.$this->getTypeDeclaration($field).$declaration_options;
-    }
-
-    // }}}
-    // {{{ _getDeclarationOptions()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare a generic type
-     * field to be used in statement like CREATE TABLE, without the field name
-     * and type values (ie. just the character set, default value, if the
-     * field is permitted to be NULL or not, and the collation options).
-     *
-     * @param array  $field  associative array with the name of the properties
-     *      of the field being declared as array indexes. Currently, the types
-     *      of supported field properties are as follows:
-     *
-     *      default
-     *          Text value to be used as default for this field.
-     *      notnull
-     *          Boolean flag that indicates whether this field is constrained
-     *          to not be set to null.
-     *      charset
-     *          Text value with the default CHARACTER SET for this field.
-     *      collation
-     *          Text value with the default COLLATION for this field.
-     * @return string  DBMS specific SQL code portion that should be used to
-     *      declare the specified field's options.
-     * @access protected
-     */
-    function _getDeclarationOptions($field)
-    {
-        $charset = empty($field['charset']) ? '' :
-            ' '.$this->_getCharsetFieldDeclaration($field['charset']);
-
-        $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
-        $default = '';
-        if (array_key_exists('default', $field)) {
-            if ($field['default'] === '') {
-                $db =$this->getDBInstance();
-                if (PEAR::isError($db)) {
-                    return $db;
-                }
-                $valid_default_values = $this->getValidTypes();
-                $field['default'] = $valid_default_values[$field['type']];
-                if ($field['default'] === ''&& ($db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL)) {
-                    $field['default'] = ' ';
-                }
-            }
-            if (!is_null($field['default'])) {
-                $default = ' DEFAULT ' . $this->quote($field['default'], $field['type']);
-            }
-        }
-
-        $collation = empty($field['collation']) ? '' :
-            ' '.$this->_getCollationFieldDeclaration($field['collation']);
-
-        return $charset.$default.$notnull.$collation;
-    }
-
-    // }}}
-    // {{{ _getCharsetFieldDeclaration()
-    
-    /**
-     * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET
-     * of a field declaration to be used in statements like CREATE TABLE.
-     *
-     * @param string $charset   name of the charset
-     * @return string  DBMS specific SQL code portion needed to set the CHARACTER SET
-     *                 of a field declaration.
-     */
-    function _getCharsetFieldDeclaration($charset)
-    {
-        return '';
-    }
-
-    // }}}
-    // {{{ _getCollationFieldDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to set the COLLATION
-     * of a field declaration to be used in statements like CREATE TABLE.
-     *
-     * @param string $collation   name of the collation
-     * @return string  DBMS specific SQL code portion needed to set the COLLATION
-     *                 of a field declaration.
-     */
-    function _getCollationFieldDeclaration($collation)
-    {
-        return '';
-    }
-
-    // }}}
-    // {{{ _getIntegerDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare an integer type
-     * field to be used in statements like CREATE TABLE.
-     *
-     * @param string $name name the field to be declared.
-     * @param array $field associative array with the name of the properties
-     *       of the field being declared as array indexes. Currently, the types
-     *       of supported field properties are as follows:
-     *
-     *       unsigned
-     *           Boolean flag that indicates whether the field should be
-     *           declared as unsigned integer if possible.
-     *
-     *       default
-     *           Integer value to be used as default for this field.
-     *
-     *       notnull
-     *           Boolean flag that indicates whether this field is constrained
-     *           to not be set to null.
-     * @return string DBMS specific SQL code portion that should be used to
-     *       declare the specified field.
-     * @access protected
-     */
-    function _getIntegerDeclaration($name, $field)
-    {
-        if (!empty($field['unsigned'])) {
-            $db =$this->getDBInstance();
-            if (PEAR::isError($db)) {
-                return $db;
-            }
-
-            $db->warnings[] = "unsigned integer field \"$name\" is being declared as signed integer";
-        }
-        return $this->_getDeclaration($name, $field);
-    }
-
-    // }}}
-    // {{{ _getTextDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare an text type
-     * field to be used in statements like CREATE TABLE.
-     *
-     * @param string $name name the field to be declared.
-     * @param array $field associative array with the name of the properties
-     *       of the field being declared as array indexes. Currently, the types
-     *       of supported field properties are as follows:
-     *
-     *       length
-     *           Integer value that determines the maximum length of the text
-     *           field. If this argument is missing the field should be
-     *           declared to have the longest length allowed by the DBMS.
-     *
-     *       default
-     *           Text value to be used as default for this field.
-     *
-     *       notnull
-     *           Boolean flag that indicates whether this field is constrained
-     *           to not be set to null.
-     * @return string DBMS specific SQL code portion that should be used to
-     *       declare the specified field.
-     * @access protected
-     */
-    function _getTextDeclaration($name, $field)
-    {
-        return $this->_getDeclaration($name, $field);
-    }
-
-    // }}}
-    // {{{ _getCLOBDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare an character
-     * large object type field to be used in statements like CREATE TABLE.
-     *
-     * @param string $name name the field to be declared.
-     * @param array $field associative array with the name of the properties
-     *        of the field being declared as array indexes. Currently, the types
-     *        of supported field properties are as follows:
-     *
-     *        length
-     *            Integer value that determines the maximum length of the large
-     *            object field. If this argument is missing the field should be
-     *            declared to have the longest length allowed by the DBMS.
-     *
-     *        notnull
-     *            Boolean flag that indicates whether this field is constrained
-     *            to not be set to null.
-     * @return string DBMS specific SQL code portion that should be used to
-     *        declare the specified field.
-     * @access public
-     */
-    function _getCLOBDeclaration($name, $field)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
-        $name = $db->quoteIdentifier($name, true);
-        return $name.' '.$this->getTypeDeclaration($field).$notnull;
-    }
-
-    // }}}
-    // {{{ _getBLOBDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare an binary large
-     * object type field to be used in statements like CREATE TABLE.
-     *
-     * @param string $name name the field to be declared.
-     * @param array $field associative array with the name of the properties
-     *        of the field being declared as array indexes. Currently, the types
-     *        of supported field properties are as follows:
-     *
-     *        length
-     *            Integer value that determines the maximum length of the large
-     *            object field. If this argument is missing the field should be
-     *            declared to have the longest length allowed by the DBMS.
-     *
-     *        notnull
-     *            Boolean flag that indicates whether this field is constrained
-     *            to not be set to null.
-     * @return string DBMS specific SQL code portion that should be used to
-     *        declare the specified field.
-     * @access protected
-     */
-    function _getBLOBDeclaration($name, $field)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
-        $name = $db->quoteIdentifier($name, true);
-        return $name.' '.$this->getTypeDeclaration($field).$notnull;
-    }
-
-    // }}}
-    // {{{ _getBooleanDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare a boolean type
-     * field to be used in statements like CREATE TABLE.
-     *
-     * @param string $name name the field to be declared.
-     * @param array $field associative array with the name of the properties
-     *       of the field being declared as array indexes. Currently, the types
-     *       of supported field properties are as follows:
-     *
-     *       default
-     *           Boolean value to be used as default for this field.
-     *
-     *       notnullL
-     *           Boolean flag that indicates whether this field is constrained
-     *           to not be set to null.
-     * @return string DBMS specific SQL code portion that should be used to
-     *       declare the specified field.
-     * @access protected
-     */
-    function _getBooleanDeclaration($name, $field)
-    {
-        return $this->_getDeclaration($name, $field);
-    }
-
-    // }}}
-    // {{{ _getDateDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare a date type
-     * field to be used in statements like CREATE TABLE.
-     *
-     * @param string $name name the field to be declared.
-     * @param array $field associative array with the name of the properties
-     *       of the field being declared as array indexes. Currently, the types
-     *       of supported field properties are as follows:
-     *
-     *       default
-     *           Date value to be used as default for this field.
-     *
-     *       notnull
-     *           Boolean flag that indicates whether this field is constrained
-     *           to not be set to null.
-     * @return string DBMS specific SQL code portion that should be used to
-     *       declare the specified field.
-     * @access protected
-     */
-    function _getDateDeclaration($name, $field)
-    {
-        return $this->_getDeclaration($name, $field);
-    }
-
-    // }}}
-    // {{{ _getTimestampDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare a timestamp
-     * field to be used in statements like CREATE TABLE.
-     *
-     * @param string $name name the field to be declared.
-     * @param array $field associative array with the name of the properties
-     *       of the field being declared as array indexes. Currently, the types
-     *       of supported field properties are as follows:
-     *
-     *       default
-     *           Timestamp value to be used as default for this field.
-     *
-     *       notnull
-     *           Boolean flag that indicates whether this field is constrained
-     *           to not be set to null.
-     * @return string DBMS specific SQL code portion that should be used to
-     *       declare the specified field.
-     * @access protected
-     */
-    function _getTimestampDeclaration($name, $field)
-    {
-        return $this->_getDeclaration($name, $field);
-    }
-
-    // }}}
-    // {{{ _getTimeDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare a time
-     * field to be used in statements like CREATE TABLE.
-     *
-     * @param string $name name the field to be declared.
-     * @param array $field associative array with the name of the properties
-     *       of the field being declared as array indexes. Currently, the types
-     *       of supported field properties are as follows:
-     *
-     *       default
-     *           Time value to be used as default for this field.
-     *
-     *       notnull
-     *           Boolean flag that indicates whether this field is constrained
-     *           to not be set to null.
-     * @return string DBMS specific SQL code portion that should be used to
-     *       declare the specified field.
-     * @access protected
-     */
-    function _getTimeDeclaration($name, $field)
-    {
-        return $this->_getDeclaration($name, $field);
-    }
-
-    // }}}
-    // {{{ _getFloatDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare a float type
-     * field to be used in statements like CREATE TABLE.
-     *
-     * @param string $name name the field to be declared.
-     * @param array $field associative array with the name of the properties
-     *       of the field being declared as array indexes. Currently, the types
-     *       of supported field properties are as follows:
-     *
-     *       default
-     *           Float value to be used as default for this field.
-     *
-     *       notnull
-     *           Boolean flag that indicates whether this field is constrained
-     *           to not be set to null.
-     * @return string DBMS specific SQL code portion that should be used to
-     *       declare the specified field.
-     * @access protected
-     */
-    function _getFloatDeclaration($name, $field)
-    {
-        return $this->_getDeclaration($name, $field);
-    }
-
-    // }}}
-    // {{{ _getDecimalDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare a decimal type
-     * field to be used in statements like CREATE TABLE.
-     *
-     * @param string $name name the field to be declared.
-     * @param array $field associative array with the name of the properties
-     *       of the field being declared as array indexes. Currently, the types
-     *       of supported field properties are as follows:
-     *
-     *       default
-     *           Decimal value to be used as default for this field.
-     *
-     *       notnull
-     *           Boolean flag that indicates whether this field is constrained
-     *           to not be set to null.
-     * @return string DBMS specific SQL code portion that should be used to
-     *       declare the specified field.
-     * @access protected
-     */
-    function _getDecimalDeclaration($name, $field)
-    {
-        return $this->_getDeclaration($name, $field);
-    }
-
-    // }}}
-    // {{{ compareDefinition()
-
-    /**
-     * Obtain an array of changes that may need to applied
-     *
-     * @param array $current new definition
-     * @param array  $previous old definition
-     * @return array  containing all changes that will need to be applied
-     * @access public
-     */
-    function compareDefinition($current, $previous)
-    {
-        $type = !empty($current['type']) ? $current['type'] : null;
-
-        if (!method_exists($this, "_compare{$type}Definition")) {
-            $db =$this->getDBInstance();
-            if (PEAR::isError($db)) {
-                return $db;
-            }
-            if (!empty($db->options['datatype_map_callback'][$type])) {
-                $parameter = array('current' => $current, 'previous' => $previous);
-                $change =  call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
-                return $change;
-            }
-            return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'type "'.$current['type'].'" is not yet supported', __FUNCTION__);
-        }
-
-        if (empty($previous['type']) || $previous['type'] != $type) {
-            return $current;
-        }
-
-        $change = $this->{"_compare{$type}Definition"}($current, $previous);
-
-        if ($previous['type'] != $type) {
-            $change['type'] = true;
-        }
-
-        $previous_notnull = !empty($previous['notnull']) ? $previous['notnull'] : false;
-        $notnull = !empty($current['notnull']) ? $current['notnull'] : false;
-        if ($previous_notnull != $notnull) {
-            $change['notnull'] = true;
-        }
-
-        $previous_default = array_key_exists('default', $previous) ? $previous['default'] :
-            ($previous_notnull ? '' : null);
-        $default = array_key_exists('default', $current) ? $current['default'] :
-            ($notnull ? '' : null);
-        if ($previous_default !== $default) {
-            $change['default'] = true;
-        }
-
-        return $change;
-    }
-
-    // }}}
-    // {{{ _compareIntegerDefinition()
-
-    /**
-     * Obtain an array of changes that may need to applied to an integer field
-     *
-     * @param array $current new definition
-     * @param array  $previous old definition
-     * @return array  containing all changes that will need to be applied
-     * @access protected
-     */
-    function _compareIntegerDefinition($current, $previous)
-    {
-        $change = array();
-        $previous_unsigned = !empty($previous['unsigned']) ? $previous['unsigned'] : false;
-        $unsigned = !empty($current['unsigned']) ? $current['unsigned'] : false;
-        if ($previous_unsigned != $unsigned) {
-            $change['unsigned'] = true;
-        }
-        $previous_autoincrement = !empty($previous['autoincrement']) ? $previous['autoincrement'] : false;
-        $autoincrement = !empty($current['autoincrement']) ? $current['autoincrement'] : false;
-        if ($previous_autoincrement != $autoincrement) {
-            $change['autoincrement'] = true;
-        }
-        return $change;
-    }
-
-    // }}}
-    // {{{ _compareTextDefinition()
-
-    /**
-     * Obtain an array of changes that may need to applied to an text field
-     *
-     * @param array $current new definition
-     * @param array  $previous old definition
-     * @return array  containing all changes that will need to be applied
-     * @access protected
-     */
-    function _compareTextDefinition($current, $previous)
-    {
-        $change = array();
-        $previous_length = !empty($previous['length']) ? $previous['length'] : 0;
-        $length = !empty($current['length']) ? $current['length'] : 0;
-        if ($previous_length != $length) {
-            $change['length'] = true;
-        }
-        $previous_fixed = !empty($previous['fixed']) ? $previous['fixed'] : 0;
-        $fixed = !empty($current['fixed']) ? $current['fixed'] : 0;
-        if ($previous_fixed != $fixed) {
-            $change['fixed'] = true;
-        }
-        return $change;
-    }
-
-    // }}}
-    // {{{ _compareCLOBDefinition()
-
-    /**
-     * Obtain an array of changes that may need to applied to an CLOB field
-     *
-     * @param array $current new definition
-     * @param array  $previous old definition
-     * @return array  containing all changes that will need to be applied
-     * @access protected
-     */
-    function _compareCLOBDefinition($current, $previous)
-    {
-        return $this->_compareTextDefinition($current, $previous);
-    }
-
-    // }}}
-    // {{{ _compareBLOBDefinition()
-
-    /**
-     * Obtain an array of changes that may need to applied to an BLOB field
-     *
-     * @param array $current new definition
-     * @param array  $previous old definition
-     * @return array  containing all changes that will need to be applied
-     * @access protected
-     */
-    function _compareBLOBDefinition($current, $previous)
-    {
-        return $this->_compareTextDefinition($current, $previous);
-    }
-
-    // }}}
-    // {{{ _compareDateDefinition()
-
-    /**
-     * Obtain an array of changes that may need to applied to an date field
-     *
-     * @param array $current new definition
-     * @param array  $previous old definition
-     * @return array  containing all changes that will need to be applied
-     * @access protected
-     */
-    function _compareDateDefinition($current, $previous)
-    {
-        return array();
-    }
-
-    // }}}
-    // {{{ _compareTimeDefinition()
-
-    /**
-     * Obtain an array of changes that may need to applied to an time field
-     *
-     * @param array $current new definition
-     * @param array  $previous old definition
-     * @return array  containing all changes that will need to be applied
-     * @access protected
-     */
-    function _compareTimeDefinition($current, $previous)
-    {
-        return array();
-    }
-
-    // }}}
-    // {{{ _compareTimestampDefinition()
-
-    /**
-     * Obtain an array of changes that may need to applied to an timestamp field
-     *
-     * @param array $current new definition
-     * @param array  $previous old definition
-     * @return array  containing all changes that will need to be applied
-     * @access protected
-     */
-    function _compareTimestampDefinition($current, $previous)
-    {
-        return array();
-    }
-
-    // }}}
-    // {{{ _compareBooleanDefinition()
-
-    /**
-     * Obtain an array of changes that may need to applied to an boolean field
-     *
-     * @param array $current new definition
-     * @param array  $previous old definition
-     * @return array  containing all changes that will need to be applied
-     * @access protected
-     */
-    function _compareBooleanDefinition($current, $previous)
-    {
-        return array();
-    }
-
-    // }}}
-    // {{{ _compareFloatDefinition()
-
-    /**
-     * Obtain an array of changes that may need to applied to an float field
-     *
-     * @param array $current new definition
-     * @param array  $previous old definition
-     * @return array  containing all changes that will need to be applied
-     * @access protected
-     */
-    function _compareFloatDefinition($current, $previous)
-    {
-        return array();
-    }
-
-    // }}}
-    // {{{ _compareDecimalDefinition()
-
-    /**
-     * Obtain an array of changes that may need to applied to an decimal field
-     *
-     * @param array $current new definition
-     * @param array  $previous old definition
-     * @return array  containing all changes that will need to be applied
-     * @access protected
-     */
-    function _compareDecimalDefinition($current, $previous)
-    {
-        return array();
-    }
-
-    // }}}
-    // {{{ quote()
-
-    /**
-     * Convert a text value into a DBMS specific format that is suitable to
-     * compose query statements.
-     *
-     * @param string $value text string value that is intended to be converted.
-     * @param string $type type to which the value should be converted to
-     * @param bool $quote determines if the value should be quoted and escaped
-     * @param bool $escape_wildcards if to escape escape wildcards
-     * @return string text string that represents the given argument value in
-     *       a DBMS specific format.
-     * @access public
-     */
-    function quote($value, $type = null, $quote = true, $escape_wildcards = false)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        if (is_null($value)
-            || ($value === '' && $db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL)
-        ) {
-            if (!$quote) {
-                return null;
-            }
-            return 'NULL';
-        }
-
-        if (is_null($type)) {
-            switch (gettype($value)) {
-            case 'integer':
-                $type = 'integer';
-                break;
-            case 'double':
-                // todo: default to decimal as float is quite unusual
-                // $type = 'float';
-                $type = 'decimal';
-                break;
-            case 'boolean':
-                $type = 'boolean';
-                break;
-            case 'array':
-                 $value = serialize($value);
-            case 'object':
-                 $type = 'text';
-                break;
-            default:
-                if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/', $value)) {
-                    $type = 'timestamp';
-                } elseif (preg_match('/^\d{2}:\d{2}$/', $value)) {
-                    $type = 'time';
-                } elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) {
-                    $type = 'date';
-                } else {
-                    $type = 'text';
-                }
-                break;
-            }
-        } elseif (!empty($db->options['datatype_map'][$type])) {
-            $type = $db->options['datatype_map'][$type];
-            if (!empty($db->options['datatype_map_callback'][$type])) {
-                $parameter = array('type' => $type, 'value' => $value, 'quote' => $quote, 'escape_wildcards' => $escape_wildcards);
-                return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
-            }
-        }
-
-        if (!method_exists($this, "_quote{$type}")) {
-            return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'type not defined: '.$type, __FUNCTION__);
-        }
-        $value = $this->{"_quote{$type}"}($value, $quote, $escape_wildcards);
-        if ($quote && $escape_wildcards && $db->string_quoting['escape_pattern']
-            && $db->string_quoting['escape'] !== $db->string_quoting['escape_pattern']
-        ) {
-            $value.= $this->patternEscapeString();
-        }
-        return $value;
-    }
-
-    // }}}
-    // {{{ _quoteInteger()
-
-    /**
-     * Convert a text value into a DBMS specific format that is suitable to
-     * compose query statements.
-     *
-     * @param string $value text string value that is intended to be converted.
-     * @param bool $quote determines if the value should be quoted and escaped
-     * @param bool $escape_wildcards if to escape escape wildcards
-     * @return string text string that represents the given argument value in
-     *       a DBMS specific format.
-     * @access protected
-     */
-    function _quoteInteger($value, $quote, $escape_wildcards)
-    {
-        return (int)$value;
-    }
-
-    // }}}
-    // {{{ _quoteText()
-
-    /**
-     * Convert a text value into a DBMS specific format that is suitable to
-     * compose query statements.
-     *
-     * @param string $value text string value that is intended to be converted.
-     * @param bool $quote determines if the value should be quoted and escaped
-     * @param bool $escape_wildcards if to escape escape wildcards
-     * @return string text string that already contains any DBMS specific
-     *       escaped character sequences.
-     * @access protected
-     */
-    function _quoteText($value, $quote, $escape_wildcards)
-    {
-        if (!$quote) {
-            return $value;
-        }
-
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $value = $db->escape($value, $escape_wildcards);
-        if (PEAR::isError($value)) {
-            return $value;
-        }
-        return "'".$value."'";
-    }
-
-    // }}}
-    // {{{ _readFile()
-
-    /**
-     * Convert a text value into a DBMS specific format that is suitable to
-     * compose query statements.
-     *
-     * @param string $value text string value that is intended to be converted.
-     * @return string text string that represents the given argument value in
-     *       a DBMS specific format.
-     * @access protected
-     */
-    function _readFile($value)
-    {
-        $close = false;
-        if (preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
-            $close = true;
-            if ($match[1] == 'file://') {
-                $value = $match[2];
-            }
-            $value = @fopen($value, 'r');
-        }
-
-        if (is_resource($value)) {
-            $db =$this->getDBInstance();
-            if (PEAR::isError($db)) {
-                return $db;
-            }
-
-            $fp = $value;
-            $value = '';
-            while (!@feof($fp)) {
-                $value.= @fread($fp, $db->options['lob_buffer_length']);
-            }
-            if ($close) {
-                @fclose($fp);
-            }
-        }
-
-        return $value;
-    }
-
-    // }}}
-    // {{{ _quoteLOB()
-
-    /**
-     * Convert a text value into a DBMS specific format that is suitable to
-     * compose query statements.
-     *
-     * @param string $value text string value that is intended to be converted.
-     * @param bool $quote determines if the value should be quoted and escaped
-     * @param bool $escape_wildcards if to escape escape wildcards
-     * @return string text string that represents the given argument value in
-     *       a DBMS specific format.
-     * @access protected
-     */
-    function _quoteLOB($value, $quote, $escape_wildcards)
-    {
-        $value = $this->_readFile($value);
-        if (PEAR::isError($value)) {
-            return $value;
-        }
-        return $this->_quoteText($value, $quote, $escape_wildcards);
-    }
-
-    // }}}
-    // {{{ _quoteCLOB()
-
-    /**
-     * Convert a text value into a DBMS specific format that is suitable to
-     * compose query statements.
-     *
-     * @param string $value text string value that is intended to be converted.
-     * @param bool $quote determines if the value should be quoted and escaped
-     * @param bool $escape_wildcards if to escape escape wildcards
-     * @return string text string that represents the given argument value in
-     *       a DBMS specific format.
-     * @access protected
-     */
-    function _quoteCLOB($value, $quote, $escape_wildcards)
-    {
-        return $this->_quoteLOB($value, $quote, $escape_wildcards);
-    }
-
-    // }}}
-    // {{{ _quoteBLOB()
-
-    /**
-     * Convert a text value into a DBMS specific format that is suitable to
-     * compose query statements.
-     *
-     * @param string $value text string value that is intended to be converted.
-     * @param bool $quote determines if the value should be quoted and escaped
-     * @param bool $escape_wildcards if to escape escape wildcards
-     * @return string text string that represents the given argument value in
-     *       a DBMS specific format.
-     * @access protected
-     */
-    function _quoteBLOB($value, $quote, $escape_wildcards)
-    {
-        return $this->_quoteLOB($value, $quote, $escape_wildcards);
-    }
-
-    // }}}
-    // {{{ _quoteBoolean()
-
-    /**
-     * Convert a text value into a DBMS specific format that is suitable to
-     * compose query statements.
-     *
-     * @param string $value text string value that is intended to be converted.
-     * @param bool $quote determines if the value should be quoted and escaped
-     * @param bool $escape_wildcards if to escape escape wildcards
-     * @return string text string that represents the given argument value in
-     *       a DBMS specific format.
-     * @access protected
-     */
-    function _quoteBoolean($value, $quote, $escape_wildcards)
-    {
-        return ($value ? 1 : 0);
-    }
-
-    // }}}
-    // {{{ _quoteDate()
-
-    /**
-     * Convert a text value into a DBMS specific format that is suitable to
-     * compose query statements.
-     *
-     * @param string $value text string value that is intended to be converted.
-     * @param bool $quote determines if the value should be quoted and escaped
-     * @param bool $escape_wildcards if to escape escape wildcards
-     * @return string text string that represents the given argument value in
-     *       a DBMS specific format.
-     * @access protected
-     */
-    function _quoteDate($value, $quote, $escape_wildcards)
-    {
-        if ($value === 'CURRENT_DATE') {
-            $db =$this->getDBInstance();
-            if (PEAR::isError($db)) {
-                return $db;
-            }
-            if (isset($db->function) && is_a($db->function, 'MDB2_Driver_Function_Common')) {
-                return $db->function->now('date');
-            }
-            return 'CURRENT_DATE';
-        }
-        return $this->_quoteText($value, $quote, $escape_wildcards);
-    }
-
-    // }}}
-    // {{{ _quoteTimestamp()
-
-    /**
-     * Convert a text value into a DBMS specific format that is suitable to
-     * compose query statements.
-     *
-     * @param string $value text string value that is intended to be converted.
-     * @param bool $quote determines if the value should be quoted and escaped
-     * @param bool $escape_wildcards if to escape escape wildcards
-     * @return string text string that represents the given argument value in
-     *       a DBMS specific format.
-     * @access protected
-     */
-    function _quoteTimestamp($value, $quote, $escape_wildcards)
-    {
-        if ($value === 'CURRENT_TIMESTAMP') {
-            $db =$this->getDBInstance();
-            if (PEAR::isError($db)) {
-                return $db;
-            }
-            if (isset($db->function) && is_a($db->function, 'MDB2_Driver_Function_Common')) {
-                return $db->function->now('timestamp');
-            }
-            return 'CURRENT_TIMESTAMP';
-        }
-        return $this->_quoteText($value, $quote, $escape_wildcards);
-    }
-
-    // }}}
-    // {{{ _quoteTime()
-
-    /**
-     * Convert a text value into a DBMS specific format that is suitable to
-     *       compose query statements.
-     *
-     * @param string $value text string value that is intended to be converted.
-     * @param bool $quote determines if the value should be quoted and escaped
-     * @param bool $escape_wildcards if to escape escape wildcards
-     * @return string text string that represents the given argument value in
-     *       a DBMS specific format.
-     * @access protected
-     */
-    function _quoteTime($value, $quote, $escape_wildcards)
-    {
-        if ($value === 'CURRENT_TIME') {
-            $db =$this->getDBInstance();
-            if (PEAR::isError($db)) {
-                return $db;
-            }
-            if (isset($db->function) && is_a($db->function, 'MDB2_Driver_Function_Common')) {
-                return $db->function->now('time');
-            }
-            return 'CURRENT_TIME';
-        }
-        return $this->_quoteText($value, $quote, $escape_wildcards);
-    }
-
-    // }}}
-    // {{{ _quoteFloat()
-
-    /**
-     * Convert a text value into a DBMS specific format that is suitable to
-     * compose query statements.
-     *
-     * @param string $value text string value that is intended to be converted.
-     * @param bool $quote determines if the value should be quoted and escaped
-     * @param bool $escape_wildcards if to escape escape wildcards
-     * @return string text string that represents the given argument value in
-     *       a DBMS specific format.
-     * @access protected
-     */
-    function _quoteFloat($value, $quote, $escape_wildcards)
-    {
-        if (preg_match('/^(.*)e([-+])(\d+)$/i', $value, $matches)) {
-            $decimal = $this->_quoteDecimal($matches[1], $quote, $escape_wildcards);
-            $sign = $matches[2];
-            $exponent = str_pad($matches[3], 2, '0', STR_PAD_LEFT);
-            $value = $decimal.'E'.$sign.$exponent;
-        } else {
-            $value = $this->_quoteDecimal($value, $quote, $escape_wildcards);
-        }
-        return $value;
-    }
-
-    // }}}
-    // {{{ _quoteDecimal()
-
-    /**
-     * Convert a text value into a DBMS specific format that is suitable to
-     * compose query statements.
-     *
-     * @param string $value text string value that is intended to be converted.
-     * @param bool $quote determines if the value should be quoted and escaped
-     * @param bool $escape_wildcards if to escape escape wildcards
-     * @return string text string that represents the given argument value in
-     *       a DBMS specific format.
-     * @access protected
-     */
-    function _quoteDecimal($value, $quote, $escape_wildcards)
-    {
-        $value = (string)$value;
-        $value = preg_replace('/[^\d\.,\-+eE]/', '', $value);
-        if (preg_match('/[^\.\d]/', $value)) {
-            if (strpos($value, ',')) {
-                // 1000,00
-                if (!strpos($value, '.')) {
-                    // convert the last "," to a "."
-                    $value = strrev(str_replace(',', '.', strrev($value)));
-                // 1.000,00
-                } elseif (strpos($value, '.') && strpos($value, '.') < strpos($value, ',')) {
-                    $value = str_replace('.', '', $value);
-                    // convert the last "," to a "."
-                    $value = strrev(str_replace(',', '.', strrev($value)));
-                // 1,000.00
-                } else {
-                    $value = str_replace(',', '', $value);
-                }
-            }
-        }
-        return $value;
-    }
-
-    // }}}
-    // {{{ writeLOBToFile()
-
-    /**
-     * retrieve LOB from the database
-     *
-     * @param resource $lob stream handle
-     * @param string $file name of the file into which the LOb should be fetched
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access protected
-     */
-    function writeLOBToFile($lob, $file)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        if (preg_match('/^(\w+:\/\/)(.*)$/', $file, $match)) {
-            if ($match[1] == 'file://') {
-                $file = $match[2];
-            }
-        }
-
-        $fp = @fopen($file, 'wb');
-        while (!@feof($lob)) {
-            $result = @fread($lob, $db->options['lob_buffer_length']);
-            $read = strlen($result);
-            if (@fwrite($fp, $result, $read) != $read) {
-                @fclose($fp);
-                return $db->raiseError(MDB2_ERROR, null, null,
-                    'could not write to the output file', __FUNCTION__);
-            }
-        }
-        @fclose($fp);
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ _retrieveLOB()
-
-    /**
-     * retrieve LOB from the database
-     *
-     * @param array $lob array
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access protected
-     */
-    function _retrieveLOB(&$lob)
-    {
-        if (is_null($lob['value'])) {
-            $lob['value'] = $lob['resource'];
-        }
-        $lob['loaded'] = true;
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ readLOB()
-
-    /**
-     * Read data from large object input stream.
-     *
-     * @param resource $lob stream handle
-     * @param string $data reference to a variable that will hold data
-     *                          to be read from the large object input stream
-     * @param integer $length    value that indicates the largest ammount ofdata
-     *                          to be read from the large object input stream.
-     * @return mixed the effective number of bytes read from the large object
-     *                      input stream on sucess or an MDB2 error object.
-     * @access public
-     * @see endOfLOB()
-     */
-    function _readLOB($lob, $length)
-    {
-        return substr($lob['value'], $lob['position'], $length);
-    }
-
-    // }}}
-    // {{{ _endOfLOB()
-
-    /**
-     * Determine whether it was reached the end of the large object and
-     * therefore there is no more data to be read for the its input stream.
-     *
-     * @param array $lob array
-     * @return mixed true or false on success, a MDB2 error on failure
-     * @access protected
-     */
-    function _endOfLOB($lob)
-    {
-        return $lob['endOfLOB'];
-    }
-
-    // }}}
-    // {{{ destroyLOB()
-
-    /**
-     * Free any resources allocated during the lifetime of the large object
-     * handler object.
-     *
-     * @param resource $lob stream handle
-     * @access public
-     */
-    function destroyLOB($lob)
-    {
-        $lob_data = stream_get_meta_data($lob);
-        $lob_index = $lob_data['wrapper_data']->lob_index;
-        fclose($lob);
-        if (isset($this->lobs[$lob_index])) {
-            $this->_destroyLOB($this->lobs[$lob_index]);
-            unset($this->lobs[$lob_index]);
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ _destroyLOB()
-
-    /**
-     * Free any resources allocated during the lifetime of the large object
-     * handler object.
-     *
-     * @param array $lob array
-     * @access private
-     */
-    function _destroyLOB(&$lob)
-    {
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ implodeArray()
-
-    /**
-     * apply a type to all values of an array and return as a comma seperated string
-     * useful for generating IN statements
-     *
-     * @access public
-     *
-     * @param array $array data array
-     * @param string $type determines type of the field
-     *
-     * @return string comma seperated values
-     */
-    function implodeArray($array, $type = false)
-    {
-        if (!is_array($array) || empty($array)) {
-            return 'NULL';
-        }
-        if ($type) {
-            foreach ($array as $value) {
-                $return[] = $this->quote($value, $type);
-            }
-        } else {
-            $return = $array;
-        }
-        return implode(', ', $return);
-    }
-
-    // }}}
-    // {{{ matchPattern()
-
-    /**
-     * build a pattern matching string
-     *
-     * @access public
-     *
-     * @param array $pattern even keys are strings, odd are patterns (% and _)
-     * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)
-     * @param string $field optional field name that is being matched against
-     *                  (might be required when emulating ILIKE)
-     *
-     * @return string SQL pattern
-     */
-    function matchPattern($pattern, $operator = null, $field = null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $match = '';
-        if (!is_null($operator)) {
-            $operator = strtoupper($operator);
-            switch ($operator) {
-            // case insensitive
-            case 'ILIKE':
-                if (is_null($field)) {
-                    return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                        'case insensitive LIKE matching requires passing the field name', __FUNCTION__);
-                }
-                $db->loadModule('Function', null, true);
-                $match = $db->function->lower($field).' LIKE ';
-                break;
-            // case sensitive
-            case 'LIKE':
-                $match = is_null($field) ? 'LIKE ' : $field.' LIKE ';
-                break;
-            default:
-                return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                    'not a supported operator type:'. $operator, __FUNCTION__);
-            }
-        }
-        $match.= "'";
-        foreach ($pattern as $key => $value) {
-            if ($key % 2) {
-                $match.= $value;
-            } else {
-                if ($operator === 'ILIKE') {
-                    $value = strtolower($value);
-                }
-                $escaped = $db->escape($value);
-                if (PEAR::isError($escaped)) {
-                    return $escaped;
-                }
-                $match.= $db->escapePattern($escaped);
-            }
-        }
-        $match.= "'";
-        $match.= $this->patternEscapeString();
-        return $match;
-    }
-
-    // }}}
-    // {{{ patternEscapeString()
-
-    /**
-     * build string to define pattern escape character
-     *
-     * @access public
-     *
-     * @return string define pattern escape character
-     */
-    function patternEscapeString()
-    {
-        return '';
-    }
-
-    // }}}
-    // {{{ mapNativeDatatype()
-
-    /**
-     * Maps a native array description of a field to a MDB2 datatype and length
-     *
-     * @param array  $field native field description
-     * @return array containing the various possible types, length, sign, fixed
-     * @access public
-     */
-    function mapNativeDatatype($field)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        // If the user has specified an option to map the native field
-        // type to a custom MDB2 datatype...
-        $db_type = strtok($field['type'], '(), ');
-        if (!empty($db->options['nativetype_map_callback'][$db_type])) {
-            return call_user_func_array($db->options['nativetype_map_callback'][$db_type], array($db, $field));
-        }
-
-        // Otherwise perform the built-in (i.e. normal) MDB2 native type to
-        // MDB2 datatype conversion
-        return $this->_mapNativeDatatype($field);
-    }
-
-    // }}}
-    // {{{ _mapNativeDatatype()
-
-    /**
-     * Maps a native array description of a field to a MDB2 datatype and length
-     *
-     * @param array  $field native field description
-     * @return array containing the various possible types, length, sign, fixed
-     * @access public
-     */
-    function _mapNativeDatatype($field)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ mapPrepareDatatype()
-
-    /**
-     * Maps an mdb2 datatype to mysqli prepare type
-     *
-     * @param string $type
-     * @return string
-     * @access public
-     */
-    function mapPrepareDatatype($type)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        if (!empty($db->options['datatype_map'][$type])) {
-            $type = $db->options['datatype_map'][$type];
-            if (!empty($db->options['datatype_map_callback'][$type])) {
-                $parameter = array('type' => $type);
-                return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
-            }
-        }
-
-        return $type;
-    }
-}
-?>
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: Common.php 300551 2010-06-17 21:54:16Z quipo $\r
+\r
+require_once 'MDB2/LOB.php';\r
+\r
+/**\r
+ * @package  MDB2\r
+ * @category Database\r
+ * @author   Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+\r
+/**\r
+ * MDB2_Driver_Common: Base class that is extended by each MDB2 driver\r
+ *\r
+ * To load this module in the MDB2 object:\r
+ * $mdb->loadModule('Datatype');\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Driver_Datatype_Common extends MDB2_Module_Common\r
+{\r
+    var $valid_default_values = array(\r
+        'text'      => '',\r
+        'boolean'   => true,\r
+        'integer'   => 0,\r
+        'decimal'   => 0.0,\r
+        'float'     => 0.0,\r
+        'timestamp' => '1970-01-01 00:00:00',\r
+        'time'      => '00:00:00',\r
+        'date'      => '1970-01-01',\r
+        'clob'      => '',\r
+        'blob'      => '',\r
+    );\r
+\r
+    /**\r
+     * contains all LOB objects created with this MDB2 instance\r
+     * @var array\r
+     * @access protected\r
+     */\r
+    var $lobs = array();\r
+\r
+    // }}}\r
+    // {{{ getValidTypes()\r
+\r
+    /**\r
+     * Get the list of valid types\r
+     *\r
+     * This function returns an array of valid types as keys with the values\r
+     * being possible default values for all native datatypes and mapped types\r
+     * for custom datatypes.\r
+     *\r
+     * @return mixed array on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function getValidTypes()\r
+    {\r
+        $types = $this->valid_default_values;\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+        if (!empty($db->options['datatype_map'])) {\r
+            foreach ($db->options['datatype_map'] as $type => $mapped_type) {\r
+                if (array_key_exists($mapped_type, $types)) {\r
+                    $types[$type] = $types[$mapped_type];\r
+                } elseif (!empty($db->options['datatype_map_callback'][$type])) {\r
+                    $parameter = array('type' => $type, 'mapped_type' => $mapped_type);\r
+                    $default =  call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));\r
+                    $types[$type] = $default;\r
+                }\r
+            }\r
+        }\r
+        return $types;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ checkResultTypes()\r
+\r
+    /**\r
+     * Define the list of types to be associated with the columns of a given\r
+     * result set.\r
+     *\r
+     * This function may be called before invoking fetchRow(), fetchOne()\r
+     * fetchCole() and fetchAll() so that the necessary data type\r
+     * conversions are performed on the data to be retrieved by them. If this\r
+     * function is not called, the type of all result set columns is assumed\r
+     * to be text, thus leading to not perform any conversions.\r
+     *\r
+     * @param array $types array variable that lists the\r
+     *       data types to be expected in the result set columns. If this array\r
+     *       contains less types than the number of columns that are returned\r
+     *       in the result set, the remaining columns are assumed to be of the\r
+     *       type text. Currently, the types clob and blob are not fully\r
+     *       supported.\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function checkResultTypes($types)\r
+    {\r
+        $types = is_array($types) ? $types : array($types);\r
+        foreach ($types as $key => $type) {\r
+            if (!isset($this->valid_default_values[$type])) {\r
+                $db = $this->getDBInstance();\r
+                if (PEAR::isError($db)) {\r
+                    return $db;\r
+                }\r
+                if (empty($db->options['datatype_map'][$type])) {\r
+                    return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                        $type.' for '.$key.' is not a supported column type', __FUNCTION__);\r
+                }\r
+            }\r
+        }\r
+        return $types;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _baseConvertResult()\r
+\r
+    /**\r
+     * General type conversion method\r
+     *\r
+     * @param mixed   $value reference to a value to be converted\r
+     * @param string  $type  specifies which type to convert to\r
+     * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text\r
+     * @return object an MDB2 error on failure\r
+     * @access protected\r
+     */\r
+    function _baseConvertResult($value, $type, $rtrim = true)\r
+    {\r
+        switch ($type) {\r
+        case 'text':\r
+            if ($rtrim) {\r
+                $value = rtrim($value);\r
+            }\r
+            return $value;\r
+        case 'integer':\r
+            return intval($value);\r
+        case 'boolean':\r
+            return !empty($value);\r
+        case 'decimal':\r
+            return $value;\r
+        case 'float':\r
+            return doubleval($value);\r
+        case 'date':\r
+            return $value;\r
+        case 'time':\r
+            return $value;\r
+        case 'timestamp':\r
+            return $value;\r
+        case 'clob':\r
+        case 'blob':\r
+            $this->lobs[] = array(\r
+                'buffer' => null,\r
+                'position' => 0,\r
+                'lob_index' => null,\r
+                'endOfLOB' => false,\r
+                'resource' => $value,\r
+                'value' => null,\r
+                'loaded' => false,\r
+            );\r
+            end($this->lobs);\r
+            $lob_index = key($this->lobs);\r
+            $this->lobs[$lob_index]['lob_index'] = $lob_index;\r
+            return fopen('MDB2LOB://'.$lob_index.'@'.$this->db_index, 'r+');\r
+        }\r
+\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_INVALID, null, null,\r
+            'attempt to convert result value to an unknown type :' . $type, __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ convertResult()\r
+\r
+    /**\r
+     * Convert a value to a RDBMS indipendent MDB2 type\r
+     *\r
+     * @param mixed   $value value to be converted\r
+     * @param string  $type  specifies which type to convert to\r
+     * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text\r
+     * @return mixed converted value\r
+     * @access public\r
+     */\r
+    function convertResult($value, $type, $rtrim = true)\r
+    {\r
+        if (null === $value) {\r
+            return null;\r
+        }\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+        if (!empty($db->options['datatype_map'][$type])) {\r
+            $type = $db->options['datatype_map'][$type];\r
+            if (!empty($db->options['datatype_map_callback'][$type])) {\r
+                $parameter = array('type' => $type, 'value' => $value, 'rtrim' => $rtrim);\r
+                return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));\r
+            }\r
+        }\r
+        return $this->_baseConvertResult($value, $type, $rtrim);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ convertResultRow()\r
+\r
+    /**\r
+     * Convert a result row\r
+     *\r
+     * @param array   $types\r
+     * @param array   $row   specifies the types to convert to\r
+     * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text\r
+     * @return mixed MDB2_OK on success, an MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function convertResultRow($types, $row, $rtrim = true)\r
+    {\r
+        $types = $this->_sortResultFieldTypes(array_keys($row), $types);\r
+        foreach ($row as $key => $value) {\r
+            if (empty($types[$key])) {\r
+                continue;\r
+            }\r
+            $value = $this->convertResult($row[$key], $types[$key], $rtrim);\r
+            if (PEAR::isError($value)) {\r
+                return $value;\r
+            }\r
+            $row[$key] = $value;\r
+        }\r
+        return $row;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _sortResultFieldTypes()\r
+\r
+    /**\r
+     * convert a result row\r
+     *\r
+     * @param array $types\r
+     * @param array $row specifies the types to convert to\r
+     * @param bool   $rtrim   if to rtrim text values or not\r
+     * @return mixed MDB2_OK on success,  a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function _sortResultFieldTypes($columns, $types)\r
+    {\r
+        $n_cols = count($columns);\r
+        $n_types = count($types);\r
+        if ($n_cols > $n_types) {\r
+            for ($i= $n_cols - $n_types; $i >= 0; $i--) {\r
+                $types[] = null;\r
+            }\r
+        }\r
+        $sorted_types = array();\r
+        foreach ($columns as $col) {\r
+            $sorted_types[$col] = null;\r
+        }\r
+        foreach ($types as $name => $type) {\r
+            if (array_key_exists($name, $sorted_types)) {\r
+                $sorted_types[$name] = $type;\r
+                unset($types[$name]);\r
+            }\r
+        }\r
+        // if there are left types in the array, fill the null values of the\r
+        // sorted array with them, in order.\r
+        if (count($types)) {\r
+            reset($types);\r
+            foreach (array_keys($sorted_types) as $k) {\r
+                if (null === $sorted_types[$k]) {\r
+                    $sorted_types[$k] = current($types);\r
+                    next($types);\r
+                }\r
+            }\r
+        }\r
+        return $sorted_types;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare\r
+     * of the given type\r
+     *\r
+     * @param string $type type to which the value should be converted to\r
+     * @param string  $name   name the field to be declared.\r
+     * @param string  $field  definition of the field\r
+     * @return string  DBMS specific SQL code portion that should be used to\r
+     *                 declare the specified field.\r
+     * @access public\r
+     */\r
+    function getDeclaration($type, $name, $field)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        if (!empty($db->options['datatype_map'][$type])) {\r
+            $type = $db->options['datatype_map'][$type];\r
+            if (!empty($db->options['datatype_map_callback'][$type])) {\r
+                $parameter = array('type' => $type, 'name' => $name, 'field' => $field);\r
+                return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));\r
+            }\r
+            $field['type'] = $type;\r
+        }\r
+\r
+        if (!method_exists($this, "_get{$type}Declaration")) {\r
+            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                'type not defined: '.$type, __FUNCTION__);\r
+        }\r
+        return $this->{"_get{$type}Declaration"}($name, $field);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getTypeDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare an text type\r
+     * field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param array $field  associative array with the name of the properties\r
+     *      of the field being declared as array indexes. Currently, the types\r
+     *      of supported field properties are as follows:\r
+     *\r
+     *      length\r
+     *          Integer value that determines the maximum length of the text\r
+     *          field. If this argument is missing the field should be\r
+     *          declared to have the longest length allowed by the DBMS.\r
+     *\r
+     *      default\r
+     *          Text value to be used as default for this field.\r
+     *\r
+     *      notnull\r
+     *          Boolean flag that indicates whether this field is constrained\r
+     *          to not be set to null.\r
+     * @return string  DBMS specific SQL code portion that should be used to\r
+     *      declare the specified field.\r
+     * @access public\r
+     */\r
+    function getTypeDeclaration($field)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        switch ($field['type']) {\r
+        case 'text':\r
+            $length = !empty($field['length']) ? $field['length'] : $db->options['default_text_field_length'];\r
+            $fixed = !empty($field['fixed']) ? $field['fixed'] : false;\r
+            return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')')\r
+                : ($length ? 'VARCHAR('.$length.')' : 'TEXT');\r
+        case 'clob':\r
+            return 'TEXT';\r
+        case 'blob':\r
+            return 'TEXT';\r
+        case 'integer':\r
+            return 'INT';\r
+        case 'boolean':\r
+            return 'INT';\r
+        case 'date':\r
+            return 'CHAR ('.strlen('YYYY-MM-DD').')';\r
+        case 'time':\r
+            return 'CHAR ('.strlen('HH:MM:SS').')';\r
+        case 'timestamp':\r
+            return 'CHAR ('.strlen('YYYY-MM-DD HH:MM:SS').')';\r
+        case 'float':\r
+            return 'TEXT';\r
+        case 'decimal':\r
+            return 'TEXT';\r
+        }\r
+        return '';\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare a generic type\r
+     * field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string $name   name the field to be declared.\r
+     * @param array  $field  associative array with the name of the properties\r
+     *      of the field being declared as array indexes. Currently, the types\r
+     *      of supported field properties are as follows:\r
+     *\r
+     *      length\r
+     *          Integer value that determines the maximum length of the text\r
+     *          field. If this argument is missing the field should be\r
+     *          declared to have the longest length allowed by the DBMS.\r
+     *\r
+     *      default\r
+     *          Text value to be used as default for this field.\r
+     *\r
+     *      notnull\r
+     *          Boolean flag that indicates whether this field is constrained\r
+     *          to not be set to null.\r
+     *      charset\r
+     *          Text value with the default CHARACTER SET for this field.\r
+     *      collation\r
+     *          Text value with the default COLLATION for this field.\r
+     * @return string  DBMS specific SQL code portion that should be used to\r
+     *      declare the specified field, or a MDB2_Error on failure\r
+     * @access protected\r
+     */\r
+    function _getDeclaration($name, $field)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $name = $db->quoteIdentifier($name, true);\r
+        $declaration_options = $db->datatype->_getDeclarationOptions($field);\r
+        if (PEAR::isError($declaration_options)) {\r
+            return $declaration_options;\r
+        }\r
+        return $name.' '.$this->getTypeDeclaration($field).$declaration_options;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getDeclarationOptions()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare a generic type\r
+     * field to be used in statement like CREATE TABLE, without the field name\r
+     * and type values (ie. just the character set, default value, if the\r
+     * field is permitted to be NULL or not, and the collation options).\r
+     *\r
+     * @param array  $field  associative array with the name of the properties\r
+     *      of the field being declared as array indexes. Currently, the types\r
+     *      of supported field properties are as follows:\r
+     *\r
+     *      default\r
+     *          Text value to be used as default for this field.\r
+     *      notnull\r
+     *          Boolean flag that indicates whether this field is constrained\r
+     *          to not be set to null.\r
+     *      charset\r
+     *          Text value with the default CHARACTER SET for this field.\r
+     *      collation\r
+     *          Text value with the default COLLATION for this field.\r
+     * @return string  DBMS specific SQL code portion that should be used to\r
+     *      declare the specified field's options.\r
+     * @access protected\r
+     */\r
+    function _getDeclarationOptions($field)\r
+    {\r
+        $charset = empty($field['charset']) ? '' :\r
+            ' '.$this->_getCharsetFieldDeclaration($field['charset']);\r
+\r
+        $notnull = empty($field['notnull']) ? '' : ' NOT NULL';\r
+        $default = '';\r
+        if (array_key_exists('default', $field)) {\r
+            if ($field['default'] === '') {\r
+                $db = $this->getDBInstance();\r
+                if (PEAR::isError($db)) {\r
+                    return $db;\r
+                }\r
+                $valid_default_values = $this->getValidTypes();\r
+                $field['default'] = $valid_default_values[$field['type']];\r
+                if ($field['default'] === '' && ($db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL)) {\r
+                    $field['default'] = ' ';\r
+                }\r
+            }\r
+            if (null !== $field['default']) {\r
+                $default = ' DEFAULT ' . $this->quote($field['default'], $field['type']);\r
+            }\r
+        }\r
+        if (empty($default) && empty($notnull)) {\r
+            $default = ' DEFAULT NULL';\r
+        }\r
+\r
+        $collation = empty($field['collation']) ? '' :\r
+            ' '.$this->_getCollationFieldDeclaration($field['collation']);\r
+\r
+        return $charset.$default.$notnull.$collation;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getCharsetFieldDeclaration()\r
+    \r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET\r
+     * of a field declaration to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string $charset   name of the charset\r
+     * @return string  DBMS specific SQL code portion needed to set the CHARACTER SET\r
+     *                 of a field declaration.\r
+     */\r
+    function _getCharsetFieldDeclaration($charset)\r
+    {\r
+        return '';\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getCollationFieldDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to set the COLLATION\r
+     * of a field declaration to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string $collation   name of the collation\r
+     * @return string  DBMS specific SQL code portion needed to set the COLLATION\r
+     *                 of a field declaration.\r
+     */\r
+    function _getCollationFieldDeclaration($collation)\r
+    {\r
+        return '';\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getIntegerDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare an integer type\r
+     * field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string $name name the field to be declared.\r
+     * @param array $field associative array with the name of the properties\r
+     *       of the field being declared as array indexes. Currently, the types\r
+     *       of supported field properties are as follows:\r
+     *\r
+     *       unsigned\r
+     *           Boolean flag that indicates whether the field should be\r
+     *           declared as unsigned integer if possible.\r
+     *\r
+     *       default\r
+     *           Integer value to be used as default for this field.\r
+     *\r
+     *       notnull\r
+     *           Boolean flag that indicates whether this field is constrained\r
+     *           to not be set to null.\r
+     * @return string DBMS specific SQL code portion that should be used to\r
+     *       declare the specified field.\r
+     * @access protected\r
+     */\r
+    function _getIntegerDeclaration($name, $field)\r
+    {\r
+        if (!empty($field['unsigned'])) {\r
+            $db = $this->getDBInstance();\r
+            if (PEAR::isError($db)) {\r
+                return $db;\r
+            }\r
+\r
+            $db->warnings[] = "unsigned integer field \"$name\" is being declared as signed integer";\r
+        }\r
+        return $this->_getDeclaration($name, $field);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getTextDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare an text type\r
+     * field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string $name name the field to be declared.\r
+     * @param array $field associative array with the name of the properties\r
+     *       of the field being declared as array indexes. Currently, the types\r
+     *       of supported field properties are as follows:\r
+     *\r
+     *       length\r
+     *           Integer value that determines the maximum length of the text\r
+     *           field. If this argument is missing the field should be\r
+     *           declared to have the longest length allowed by the DBMS.\r
+     *\r
+     *       default\r
+     *           Text value to be used as default for this field.\r
+     *\r
+     *       notnull\r
+     *           Boolean flag that indicates whether this field is constrained\r
+     *           to not be set to null.\r
+     * @return string DBMS specific SQL code portion that should be used to\r
+     *       declare the specified field.\r
+     * @access protected\r
+     */\r
+    function _getTextDeclaration($name, $field)\r
+    {\r
+        return $this->_getDeclaration($name, $field);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getCLOBDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare an character\r
+     * large object type field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string $name name the field to be declared.\r
+     * @param array $field associative array with the name of the properties\r
+     *        of the field being declared as array indexes. Currently, the types\r
+     *        of supported field properties are as follows:\r
+     *\r
+     *        length\r
+     *            Integer value that determines the maximum length of the large\r
+     *            object field. If this argument is missing the field should be\r
+     *            declared to have the longest length allowed by the DBMS.\r
+     *\r
+     *        notnull\r
+     *            Boolean flag that indicates whether this field is constrained\r
+     *            to not be set to null.\r
+     * @return string DBMS specific SQL code portion that should be used to\r
+     *        declare the specified field.\r
+     * @access public\r
+     */\r
+    function _getCLOBDeclaration($name, $field)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $notnull = empty($field['notnull']) ? '' : ' NOT NULL';\r
+        $name = $db->quoteIdentifier($name, true);\r
+        return $name.' '.$this->getTypeDeclaration($field).$notnull;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getBLOBDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare an binary large\r
+     * object type field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string $name name the field to be declared.\r
+     * @param array $field associative array with the name of the properties\r
+     *        of the field being declared as array indexes. Currently, the types\r
+     *        of supported field properties are as follows:\r
+     *\r
+     *        length\r
+     *            Integer value that determines the maximum length of the large\r
+     *            object field. If this argument is missing the field should be\r
+     *            declared to have the longest length allowed by the DBMS.\r
+     *\r
+     *        notnull\r
+     *            Boolean flag that indicates whether this field is constrained\r
+     *            to not be set to null.\r
+     * @return string DBMS specific SQL code portion that should be used to\r
+     *        declare the specified field.\r
+     * @access protected\r
+     */\r
+    function _getBLOBDeclaration($name, $field)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $notnull = empty($field['notnull']) ? '' : ' NOT NULL';\r
+        $name = $db->quoteIdentifier($name, true);\r
+        return $name.' '.$this->getTypeDeclaration($field).$notnull;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getBooleanDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare a boolean type\r
+     * field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string $name name the field to be declared.\r
+     * @param array $field associative array with the name of the properties\r
+     *       of the field being declared as array indexes. Currently, the types\r
+     *       of supported field properties are as follows:\r
+     *\r
+     *       default\r
+     *           Boolean value to be used as default for this field.\r
+     *\r
+     *       notnullL\r
+     *           Boolean flag that indicates whether this field is constrained\r
+     *           to not be set to null.\r
+     * @return string DBMS specific SQL code portion that should be used to\r
+     *       declare the specified field.\r
+     * @access protected\r
+     */\r
+    function _getBooleanDeclaration($name, $field)\r
+    {\r
+        return $this->_getDeclaration($name, $field);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getDateDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare a date type\r
+     * field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string $name name the field to be declared.\r
+     * @param array $field associative array with the name of the properties\r
+     *       of the field being declared as array indexes. Currently, the types\r
+     *       of supported field properties are as follows:\r
+     *\r
+     *       default\r
+     *           Date value to be used as default for this field.\r
+     *\r
+     *       notnull\r
+     *           Boolean flag that indicates whether this field is constrained\r
+     *           to not be set to null.\r
+     * @return string DBMS specific SQL code portion that should be used to\r
+     *       declare the specified field.\r
+     * @access protected\r
+     */\r
+    function _getDateDeclaration($name, $field)\r
+    {\r
+        return $this->_getDeclaration($name, $field);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getTimestampDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare a timestamp\r
+     * field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string $name name the field to be declared.\r
+     * @param array $field associative array with the name of the properties\r
+     *       of the field being declared as array indexes. Currently, the types\r
+     *       of supported field properties are as follows:\r
+     *\r
+     *       default\r
+     *           Timestamp value to be used as default for this field.\r
+     *\r
+     *       notnull\r
+     *           Boolean flag that indicates whether this field is constrained\r
+     *           to not be set to null.\r
+     * @return string DBMS specific SQL code portion that should be used to\r
+     *       declare the specified field.\r
+     * @access protected\r
+     */\r
+    function _getTimestampDeclaration($name, $field)\r
+    {\r
+        return $this->_getDeclaration($name, $field);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getTimeDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare a time\r
+     * field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string $name name the field to be declared.\r
+     * @param array $field associative array with the name of the properties\r
+     *       of the field being declared as array indexes. Currently, the types\r
+     *       of supported field properties are as follows:\r
+     *\r
+     *       default\r
+     *           Time value to be used as default for this field.\r
+     *\r
+     *       notnull\r
+     *           Boolean flag that indicates whether this field is constrained\r
+     *           to not be set to null.\r
+     * @return string DBMS specific SQL code portion that should be used to\r
+     *       declare the specified field.\r
+     * @access protected\r
+     */\r
+    function _getTimeDeclaration($name, $field)\r
+    {\r
+        return $this->_getDeclaration($name, $field);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getFloatDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare a float type\r
+     * field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string $name name the field to be declared.\r
+     * @param array $field associative array with the name of the properties\r
+     *       of the field being declared as array indexes. Currently, the types\r
+     *       of supported field properties are as follows:\r
+     *\r
+     *       default\r
+     *           Float value to be used as default for this field.\r
+     *\r
+     *       notnull\r
+     *           Boolean flag that indicates whether this field is constrained\r
+     *           to not be set to null.\r
+     * @return string DBMS specific SQL code portion that should be used to\r
+     *       declare the specified field.\r
+     * @access protected\r
+     */\r
+    function _getFloatDeclaration($name, $field)\r
+    {\r
+        return $this->_getDeclaration($name, $field);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getDecimalDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare a decimal type\r
+     * field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string $name name the field to be declared.\r
+     * @param array $field associative array with the name of the properties\r
+     *       of the field being declared as array indexes. Currently, the types\r
+     *       of supported field properties are as follows:\r
+     *\r
+     *       default\r
+     *           Decimal value to be used as default for this field.\r
+     *\r
+     *       notnull\r
+     *           Boolean flag that indicates whether this field is constrained\r
+     *           to not be set to null.\r
+     * @return string DBMS specific SQL code portion that should be used to\r
+     *       declare the specified field.\r
+     * @access protected\r
+     */\r
+    function _getDecimalDeclaration($name, $field)\r
+    {\r
+        return $this->_getDeclaration($name, $field);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ compareDefinition()\r
+\r
+    /**\r
+     * Obtain an array of changes that may need to applied\r
+     *\r
+     * @param array $current new definition\r
+     * @param array  $previous old definition\r
+     * @return array  containing all changes that will need to be applied\r
+     * @access public\r
+     */\r
+    function compareDefinition($current, $previous)\r
+    {\r
+        $type = !empty($current['type']) ? $current['type'] : null;\r
+\r
+        if (!method_exists($this, "_compare{$type}Definition")) {\r
+            $db = $this->getDBInstance();\r
+            if (PEAR::isError($db)) {\r
+                return $db;\r
+            }\r
+            if (!empty($db->options['datatype_map_callback'][$type])) {\r
+                $parameter = array('current' => $current, 'previous' => $previous);\r
+                $change =  call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));\r
+                return $change;\r
+            }\r
+            return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'type "'.$current['type'].'" is not yet supported', __FUNCTION__);\r
+        }\r
+\r
+        if (empty($previous['type']) || $previous['type'] != $type) {\r
+            return $current;\r
+        }\r
+\r
+        $change = $this->{"_compare{$type}Definition"}($current, $previous);\r
+\r
+        if ($previous['type'] != $type) {\r
+            $change['type'] = true;\r
+        }\r
+\r
+        $previous_notnull = !empty($previous['notnull']) ? $previous['notnull'] : false;\r
+        $notnull = !empty($current['notnull']) ? $current['notnull'] : false;\r
+        if ($previous_notnull != $notnull) {\r
+            $change['notnull'] = true;\r
+        }\r
+\r
+        $previous_default = array_key_exists('default', $previous) ? $previous['default'] :\r
+            ($previous_notnull ? '' : null);\r
+        $default = array_key_exists('default', $current) ? $current['default'] :\r
+            ($notnull ? '' : null);\r
+        if ($previous_default !== $default) {\r
+            $change['default'] = true;\r
+        }\r
+\r
+        return $change;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _compareIntegerDefinition()\r
+\r
+    /**\r
+     * Obtain an array of changes that may need to applied to an integer field\r
+     *\r
+     * @param array $current new definition\r
+     * @param array  $previous old definition\r
+     * @return array  containing all changes that will need to be applied\r
+     * @access protected\r
+     */\r
+    function _compareIntegerDefinition($current, $previous)\r
+    {\r
+        $change = array();\r
+        $previous_unsigned = !empty($previous['unsigned']) ? $previous['unsigned'] : false;\r
+        $unsigned = !empty($current['unsigned']) ? $current['unsigned'] : false;\r
+        if ($previous_unsigned != $unsigned) {\r
+            $change['unsigned'] = true;\r
+        }\r
+        $previous_autoincrement = !empty($previous['autoincrement']) ? $previous['autoincrement'] : false;\r
+        $autoincrement = !empty($current['autoincrement']) ? $current['autoincrement'] : false;\r
+        if ($previous_autoincrement != $autoincrement) {\r
+            $change['autoincrement'] = true;\r
+        }\r
+        return $change;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _compareTextDefinition()\r
+\r
+    /**\r
+     * Obtain an array of changes that may need to applied to an text field\r
+     *\r
+     * @param array $current new definition\r
+     * @param array  $previous old definition\r
+     * @return array  containing all changes that will need to be applied\r
+     * @access protected\r
+     */\r
+    function _compareTextDefinition($current, $previous)\r
+    {\r
+        $change = array();\r
+        $previous_length = !empty($previous['length']) ? $previous['length'] : 0;\r
+        $length = !empty($current['length']) ? $current['length'] : 0;\r
+        if ($previous_length != $length) {\r
+            $change['length'] = true;\r
+        }\r
+        $previous_fixed = !empty($previous['fixed']) ? $previous['fixed'] : 0;\r
+        $fixed = !empty($current['fixed']) ? $current['fixed'] : 0;\r
+        if ($previous_fixed != $fixed) {\r
+            $change['fixed'] = true;\r
+        }\r
+        return $change;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _compareCLOBDefinition()\r
+\r
+    /**\r
+     * Obtain an array of changes that may need to applied to an CLOB field\r
+     *\r
+     * @param array $current new definition\r
+     * @param array  $previous old definition\r
+     * @return array  containing all changes that will need to be applied\r
+     * @access protected\r
+     */\r
+    function _compareCLOBDefinition($current, $previous)\r
+    {\r
+        return $this->_compareTextDefinition($current, $previous);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _compareBLOBDefinition()\r
+\r
+    /**\r
+     * Obtain an array of changes that may need to applied to an BLOB field\r
+     *\r
+     * @param array $current new definition\r
+     * @param array  $previous old definition\r
+     * @return array  containing all changes that will need to be applied\r
+     * @access protected\r
+     */\r
+    function _compareBLOBDefinition($current, $previous)\r
+    {\r
+        return $this->_compareTextDefinition($current, $previous);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _compareDateDefinition()\r
+\r
+    /**\r
+     * Obtain an array of changes that may need to applied to an date field\r
+     *\r
+     * @param array $current new definition\r
+     * @param array  $previous old definition\r
+     * @return array  containing all changes that will need to be applied\r
+     * @access protected\r
+     */\r
+    function _compareDateDefinition($current, $previous)\r
+    {\r
+        return array();\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _compareTimeDefinition()\r
+\r
+    /**\r
+     * Obtain an array of changes that may need to applied to an time field\r
+     *\r
+     * @param array $current new definition\r
+     * @param array  $previous old definition\r
+     * @return array  containing all changes that will need to be applied\r
+     * @access protected\r
+     */\r
+    function _compareTimeDefinition($current, $previous)\r
+    {\r
+        return array();\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _compareTimestampDefinition()\r
+\r
+    /**\r
+     * Obtain an array of changes that may need to applied to an timestamp field\r
+     *\r
+     * @param array $current new definition\r
+     * @param array  $previous old definition\r
+     * @return array  containing all changes that will need to be applied\r
+     * @access protected\r
+     */\r
+    function _compareTimestampDefinition($current, $previous)\r
+    {\r
+        return array();\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _compareBooleanDefinition()\r
+\r
+    /**\r
+     * Obtain an array of changes that may need to applied to an boolean field\r
+     *\r
+     * @param array $current new definition\r
+     * @param array  $previous old definition\r
+     * @return array  containing all changes that will need to be applied\r
+     * @access protected\r
+     */\r
+    function _compareBooleanDefinition($current, $previous)\r
+    {\r
+        return array();\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _compareFloatDefinition()\r
+\r
+    /**\r
+     * Obtain an array of changes that may need to applied to an float field\r
+     *\r
+     * @param array $current new definition\r
+     * @param array  $previous old definition\r
+     * @return array  containing all changes that will need to be applied\r
+     * @access protected\r
+     */\r
+    function _compareFloatDefinition($current, $previous)\r
+    {\r
+        return array();\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _compareDecimalDefinition()\r
+\r
+    /**\r
+     * Obtain an array of changes that may need to applied to an decimal field\r
+     *\r
+     * @param array $current new definition\r
+     * @param array  $previous old definition\r
+     * @return array  containing all changes that will need to be applied\r
+     * @access protected\r
+     */\r
+    function _compareDecimalDefinition($current, $previous)\r
+    {\r
+        return array();\r
+    }\r
+\r
+    // }}}\r
+    // {{{ quote()\r
+\r
+    /**\r
+     * Convert a text value into a DBMS specific format that is suitable to\r
+     * compose query statements.\r
+     *\r
+     * @param string $value text string value that is intended to be converted.\r
+     * @param string $type type to which the value should be converted to\r
+     * @param bool $quote determines if the value should be quoted and escaped\r
+     * @param bool $escape_wildcards if to escape escape wildcards\r
+     * @return string text string that represents the given argument value in\r
+     *       a DBMS specific format.\r
+     * @access public\r
+     */\r
+    function quote($value, $type = null, $quote = true, $escape_wildcards = false)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        if ((null === $value)\r
+            || ($value === '' && $db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL)\r
+        ) {\r
+            if (!$quote) {\r
+                return null;\r
+            }\r
+            return 'NULL';\r
+        }\r
+\r
+        if (null === $type) {\r
+            switch (gettype($value)) {\r
+            case 'integer':\r
+                $type = 'integer';\r
+                break;\r
+            case 'double':\r
+                // todo: default to decimal as float is quite unusual\r
+                // $type = 'float';\r
+                $type = 'decimal';\r
+                break;\r
+            case 'boolean':\r
+                $type = 'boolean';\r
+                break;\r
+            case 'array':\r
+                 $value = serialize($value);\r
+            case 'object':\r
+                 $type = 'text';\r
+                break;\r
+            default:\r
+                if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/', $value)) {\r
+                    $type = 'timestamp';\r
+                } elseif (preg_match('/^\d{2}:\d{2}$/', $value)) {\r
+                    $type = 'time';\r
+                } elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) {\r
+                    $type = 'date';\r
+                } else {\r
+                    $type = 'text';\r
+                }\r
+                break;\r
+            }\r
+        } elseif (!empty($db->options['datatype_map'][$type])) {\r
+            $type = $db->options['datatype_map'][$type];\r
+            if (!empty($db->options['datatype_map_callback'][$type])) {\r
+                $parameter = array('type' => $type, 'value' => $value, 'quote' => $quote, 'escape_wildcards' => $escape_wildcards);\r
+                return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));\r
+            }\r
+        }\r
+\r
+        if (!method_exists($this, "_quote{$type}")) {\r
+            return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'type not defined: '.$type, __FUNCTION__);\r
+        }\r
+        $value = $this->{"_quote{$type}"}($value, $quote, $escape_wildcards);\r
+        if ($quote && $escape_wildcards && $db->string_quoting['escape_pattern']\r
+            && $db->string_quoting['escape'] !== $db->string_quoting['escape_pattern']\r
+        ) {\r
+            $value.= $this->patternEscapeString();\r
+        }\r
+        return $value;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _quoteInteger()\r
+\r
+    /**\r
+     * Convert a text value into a DBMS specific format that is suitable to\r
+     * compose query statements.\r
+     *\r
+     * @param string $value text string value that is intended to be converted.\r
+     * @param bool $quote determines if the value should be quoted and escaped\r
+     * @param bool $escape_wildcards if to escape escape wildcards\r
+     * @return string text string that represents the given argument value in\r
+     *       a DBMS specific format.\r
+     * @access protected\r
+     */\r
+    function _quoteInteger($value, $quote, $escape_wildcards)\r
+    {\r
+        return (int)$value;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _quoteText()\r
+\r
+    /**\r
+     * Convert a text value into a DBMS specific format that is suitable to\r
+     * compose query statements.\r
+     *\r
+     * @param string $value text string value that is intended to be converted.\r
+     * @param bool $quote determines if the value should be quoted and escaped\r
+     * @param bool $escape_wildcards if to escape escape wildcards\r
+     * @return string text string that already contains any DBMS specific\r
+     *       escaped character sequences.\r
+     * @access protected\r
+     */\r
+    function _quoteText($value, $quote, $escape_wildcards)\r
+    {\r
+        if (!$quote) {\r
+            return $value;\r
+        }\r
+\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $value = $db->escape($value, $escape_wildcards);\r
+        if (PEAR::isError($value)) {\r
+            return $value;\r
+        }\r
+        return "'".$value."'";\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _readFile()\r
+\r
+    /**\r
+     * Convert a text value into a DBMS specific format that is suitable to\r
+     * compose query statements.\r
+     *\r
+     * @param string $value text string value that is intended to be converted.\r
+     * @return string text string that represents the given argument value in\r
+     *       a DBMS specific format.\r
+     * @access protected\r
+     */\r
+    function _readFile($value)\r
+    {\r
+        $close = false;\r
+        if (preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {\r
+            $close = true;\r
+            if (strtolower($match[1]) == 'file://') {\r
+                $value = $match[2];\r
+            }\r
+            $value = @fopen($value, 'r');\r
+        }\r
+\r
+        if (is_resource($value)) {\r
+            $db = $this->getDBInstance();\r
+            if (PEAR::isError($db)) {\r
+                return $db;\r
+            }\r
+\r
+            $fp = $value;\r
+            $value = '';\r
+            while (!@feof($fp)) {\r
+                $value.= @fread($fp, $db->options['lob_buffer_length']);\r
+            }\r
+            if ($close) {\r
+                @fclose($fp);\r
+            }\r
+        }\r
+\r
+        return $value;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _quoteLOB()\r
+\r
+    /**\r
+     * Convert a text value into a DBMS specific format that is suitable to\r
+     * compose query statements.\r
+     *\r
+     * @param string $value text string value that is intended to be converted.\r
+     * @param bool $quote determines if the value should be quoted and escaped\r
+     * @param bool $escape_wildcards if to escape escape wildcards\r
+     * @return string text string that represents the given argument value in\r
+     *       a DBMS specific format.\r
+     * @access protected\r
+     */\r
+    function _quoteLOB($value, $quote, $escape_wildcards)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+        if ($db->options['lob_allow_url_include']) {\r
+            $value = $this->_readFile($value);\r
+            if (PEAR::isError($value)) {\r
+                return $value;\r
+            }\r
+        }\r
+        return $this->_quoteText($value, $quote, $escape_wildcards);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _quoteCLOB()\r
+\r
+    /**\r
+     * Convert a text value into a DBMS specific format that is suitable to\r
+     * compose query statements.\r
+     *\r
+     * @param string $value text string value that is intended to be converted.\r
+     * @param bool $quote determines if the value should be quoted and escaped\r
+     * @param bool $escape_wildcards if to escape escape wildcards\r
+     * @return string text string that represents the given argument value in\r
+     *       a DBMS specific format.\r
+     * @access protected\r
+     */\r
+    function _quoteCLOB($value, $quote, $escape_wildcards)\r
+    {\r
+        return $this->_quoteLOB($value, $quote, $escape_wildcards);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _quoteBLOB()\r
+\r
+    /**\r
+     * Convert a text value into a DBMS specific format that is suitable to\r
+     * compose query statements.\r
+     *\r
+     * @param string $value text string value that is intended to be converted.\r
+     * @param bool $quote determines if the value should be quoted and escaped\r
+     * @param bool $escape_wildcards if to escape escape wildcards\r
+     * @return string text string that represents the given argument value in\r
+     *       a DBMS specific format.\r
+     * @access protected\r
+     */\r
+    function _quoteBLOB($value, $quote, $escape_wildcards)\r
+    {\r
+        return $this->_quoteLOB($value, $quote, $escape_wildcards);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _quoteBoolean()\r
+\r
+    /**\r
+     * Convert a text value into a DBMS specific format that is suitable to\r
+     * compose query statements.\r
+     *\r
+     * @param string $value text string value that is intended to be converted.\r
+     * @param bool $quote determines if the value should be quoted and escaped\r
+     * @param bool $escape_wildcards if to escape escape wildcards\r
+     * @return string text string that represents the given argument value in\r
+     *       a DBMS specific format.\r
+     * @access protected\r
+     */\r
+    function _quoteBoolean($value, $quote, $escape_wildcards)\r
+    {\r
+        return ($value ? 1 : 0);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _quoteDate()\r
+\r
+    /**\r
+     * Convert a text value into a DBMS specific format that is suitable to\r
+     * compose query statements.\r
+     *\r
+     * @param string $value text string value that is intended to be converted.\r
+     * @param bool $quote determines if the value should be quoted and escaped\r
+     * @param bool $escape_wildcards if to escape escape wildcards\r
+     * @return string text string that represents the given argument value in\r
+     *       a DBMS specific format.\r
+     * @access protected\r
+     */\r
+    function _quoteDate($value, $quote, $escape_wildcards)\r
+    {\r
+        if ($value === 'CURRENT_DATE') {\r
+            $db = $this->getDBInstance();\r
+            if (PEAR::isError($db)) {\r
+                return $db;\r
+            }\r
+            if (isset($db->function) && is_a($db->function, 'MDB2_Driver_Function_Common')) {\r
+                return $db->function->now('date');\r
+            }\r
+            return 'CURRENT_DATE';\r
+        }\r
+        return $this->_quoteText($value, $quote, $escape_wildcards);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _quoteTimestamp()\r
+\r
+    /**\r
+     * Convert a text value into a DBMS specific format that is suitable to\r
+     * compose query statements.\r
+     *\r
+     * @param string $value text string value that is intended to be converted.\r
+     * @param bool $quote determines if the value should be quoted and escaped\r
+     * @param bool $escape_wildcards if to escape escape wildcards\r
+     * @return string text string that represents the given argument value in\r
+     *       a DBMS specific format.\r
+     * @access protected\r
+     */\r
+    function _quoteTimestamp($value, $quote, $escape_wildcards)\r
+    {\r
+        if ($value === 'CURRENT_TIMESTAMP') {\r
+            $db = $this->getDBInstance();\r
+            if (PEAR::isError($db)) {\r
+                return $db;\r
+            }\r
+            if (isset($db->function) && is_a($db->function, 'MDB2_Driver_Function_Common')) {\r
+                return $db->function->now('timestamp');\r
+            }\r
+            return 'CURRENT_TIMESTAMP';\r
+        }\r
+        return $this->_quoteText($value, $quote, $escape_wildcards);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _quoteTime()\r
+\r
+    /**\r
+     * Convert a text value into a DBMS specific format that is suitable to\r
+     *       compose query statements.\r
+     *\r
+     * @param string $value text string value that is intended to be converted.\r
+     * @param bool $quote determines if the value should be quoted and escaped\r
+     * @param bool $escape_wildcards if to escape escape wildcards\r
+     * @return string text string that represents the given argument value in\r
+     *       a DBMS specific format.\r
+     * @access protected\r
+     */\r
+    function _quoteTime($value, $quote, $escape_wildcards)\r
+    {\r
+        if ($value === 'CURRENT_TIME') {\r
+            $db = $this->getDBInstance();\r
+            if (PEAR::isError($db)) {\r
+                return $db;\r
+            }\r
+            if (isset($db->function) && is_a($db->function, 'MDB2_Driver_Function_Common')) {\r
+                return $db->function->now('time');\r
+            }\r
+            return 'CURRENT_TIME';\r
+        }\r
+        return $this->_quoteText($value, $quote, $escape_wildcards);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _quoteFloat()\r
+\r
+    /**\r
+     * Convert a text value into a DBMS specific format that is suitable to\r
+     * compose query statements.\r
+     *\r
+     * @param string $value text string value that is intended to be converted.\r
+     * @param bool $quote determines if the value should be quoted and escaped\r
+     * @param bool $escape_wildcards if to escape escape wildcards\r
+     * @return string text string that represents the given argument value in\r
+     *       a DBMS specific format.\r
+     * @access protected\r
+     */\r
+    function _quoteFloat($value, $quote, $escape_wildcards)\r
+    {\r
+        if (preg_match('/^(.*)e([-+])(\d+)$/i', $value, $matches)) {\r
+            $decimal = $this->_quoteDecimal($matches[1], $quote, $escape_wildcards);\r
+            $sign = $matches[2];\r
+            $exponent = str_pad($matches[3], 2, '0', STR_PAD_LEFT);\r
+            $value = $decimal.'E'.$sign.$exponent;\r
+        } else {\r
+            $value = $this->_quoteDecimal($value, $quote, $escape_wildcards);\r
+        }\r
+        return $value;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _quoteDecimal()\r
+\r
+    /**\r
+     * Convert a text value into a DBMS specific format that is suitable to\r
+     * compose query statements.\r
+     *\r
+     * @param string $value text string value that is intended to be converted.\r
+     * @param bool $quote determines if the value should be quoted and escaped\r
+     * @param bool $escape_wildcards if to escape escape wildcards\r
+     * @return string text string that represents the given argument value in\r
+     *       a DBMS specific format.\r
+     * @access protected\r
+     */\r
+    function _quoteDecimal($value, $quote, $escape_wildcards)\r
+    {\r
+        $value = (string)$value;\r
+        $value = preg_replace('/[^\d\.,\-+eE]/', '', $value);\r
+        if (preg_match('/[^\.\d]/', $value)) {\r
+            if (strpos($value, ',')) {\r
+                // 1000,00\r
+                if (!strpos($value, '.')) {\r
+                    // convert the last "," to a "."\r
+                    $value = strrev(str_replace(',', '.', strrev($value)));\r
+                // 1.000,00\r
+                } elseif (strpos($value, '.') && strpos($value, '.') < strpos($value, ',')) {\r
+                    $value = str_replace('.', '', $value);\r
+                    // convert the last "," to a "."\r
+                    $value = strrev(str_replace(',', '.', strrev($value)));\r
+                // 1,000.00\r
+                } else {\r
+                    $value = str_replace(',', '', $value);\r
+                }\r
+            }\r
+        }\r
+        return $value;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ writeLOBToFile()\r
+\r
+    /**\r
+     * retrieve LOB from the database\r
+     *\r
+     * @param resource $lob stream handle\r
+     * @param string $file name of the file into which the LOb should be fetched\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access protected\r
+     */\r
+    function writeLOBToFile($lob, $file)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        if (preg_match('/^(\w+:\/\/)(.*)$/', $file, $match)) {\r
+            if ($match[1] == 'file://') {\r
+                $file = $match[2];\r
+            }\r
+        }\r
+\r
+        $fp = @fopen($file, 'wb');\r
+        while (!@feof($lob)) {\r
+            $result = @fread($lob, $db->options['lob_buffer_length']);\r
+            $read = strlen($result);\r
+            if (@fwrite($fp, $result, $read) != $read) {\r
+                @fclose($fp);\r
+                return $db->raiseError(MDB2_ERROR, null, null,\r
+                    'could not write to the output file', __FUNCTION__);\r
+            }\r
+        }\r
+        @fclose($fp);\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _retrieveLOB()\r
+\r
+    /**\r
+     * retrieve LOB from the database\r
+     *\r
+     * @param array $lob array\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access protected\r
+     */\r
+    function _retrieveLOB(&$lob)\r
+    {\r
+        if (null === $lob['value']) {\r
+            $lob['value'] = $lob['resource'];\r
+        }\r
+        $lob['loaded'] = true;\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ readLOB()\r
+\r
+    /**\r
+     * Read data from large object input stream.\r
+     *\r
+     * @param resource $lob stream handle\r
+     * @param string $data reference to a variable that will hold data\r
+     *                          to be read from the large object input stream\r
+     * @param integer $length    value that indicates the largest ammount ofdata\r
+     *                          to be read from the large object input stream.\r
+     * @return mixed the effective number of bytes read from the large object\r
+     *                      input stream on sucess or an MDB2 error object.\r
+     * @access public\r
+     * @see endOfLOB()\r
+     */\r
+    function _readLOB($lob, $length)\r
+    {\r
+        return substr($lob['value'], $lob['position'], $length);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _endOfLOB()\r
+\r
+    /**\r
+     * Determine whether it was reached the end of the large object and\r
+     * therefore there is no more data to be read for the its input stream.\r
+     *\r
+     * @param array $lob array\r
+     * @return mixed true or false on success, a MDB2 error on failure\r
+     * @access protected\r
+     */\r
+    function _endOfLOB($lob)\r
+    {\r
+        return $lob['endOfLOB'];\r
+    }\r
+\r
+    // }}}\r
+    // {{{ destroyLOB()\r
+\r
+    /**\r
+     * Free any resources allocated during the lifetime of the large object\r
+     * handler object.\r
+     *\r
+     * @param resource $lob stream handle\r
+     * @access public\r
+     */\r
+    function destroyLOB($lob)\r
+    {\r
+        $lob_data = stream_get_meta_data($lob);\r
+        $lob_index = $lob_data['wrapper_data']->lob_index;\r
+        fclose($lob);\r
+        if (isset($this->lobs[$lob_index])) {\r
+            $this->_destroyLOB($this->lobs[$lob_index]);\r
+            unset($this->lobs[$lob_index]);\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _destroyLOB()\r
+\r
+    /**\r
+     * Free any resources allocated during the lifetime of the large object\r
+     * handler object.\r
+     *\r
+     * @param array $lob array\r
+     * @access private\r
+     */\r
+    function _destroyLOB(&$lob)\r
+    {\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ implodeArray()\r
+\r
+    /**\r
+     * apply a type to all values of an array and return as a comma seperated string\r
+     * useful for generating IN statements\r
+     *\r
+     * @access public\r
+     *\r
+     * @param array $array data array\r
+     * @param string $type determines type of the field\r
+     *\r
+     * @return string comma seperated values\r
+     */\r
+    function implodeArray($array, $type = false)\r
+    {\r
+        if (!is_array($array) || empty($array)) {\r
+            return 'NULL';\r
+        }\r
+        if ($type) {\r
+            foreach ($array as $value) {\r
+                $return[] = $this->quote($value, $type);\r
+            }\r
+        } else {\r
+            $return = $array;\r
+        }\r
+        return implode(', ', $return);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ matchPattern()\r
+\r
+    /**\r
+     * build a pattern matching string\r
+     *\r
+     * @access public\r
+     *\r
+     * @param array $pattern even keys are strings, odd are patterns (% and _)\r
+     * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)\r
+     * @param string $field optional field name that is being matched against\r
+     *                  (might be required when emulating ILIKE)\r
+     *\r
+     * @return string SQL pattern\r
+     */\r
+    function matchPattern($pattern, $operator = null, $field = null)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $match = '';\r
+        if (null !== $operator) {\r
+            $operator = strtoupper($operator);\r
+            switch ($operator) {\r
+            // case insensitive\r
+            case 'ILIKE':\r
+                if (null === $field) {\r
+                    return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                        'case insensitive LIKE matching requires passing the field name', __FUNCTION__);\r
+                }\r
+                $db->loadModule('Function', null, true);\r
+                $match = $db->function->lower($field).' LIKE ';\r
+                break;\r
+            case 'NOT ILIKE':\r
+                if (null === $field) {\r
+                    return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                        'case insensitive NOT ILIKE matching requires passing the field name', __FUNCTION__);\r
+                }\r
+                $db->loadModule('Function', null, true);\r
+                $match = $db->function->lower($field).' NOT LIKE ';\r
+                break;\r
+            // case sensitive\r
+            case 'LIKE':\r
+                $match = (null === $field) ? 'LIKE ' : ($field.' LIKE ');\r
+                break;\r
+            case 'NOT LIKE':\r
+                $match = (null === $field) ? 'NOT LIKE ' : ($field.' NOT LIKE ');\r
+                break;\r
+            default:\r
+                return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                    'not a supported operator type:'. $operator, __FUNCTION__);\r
+            }\r
+        }\r
+        $match.= "'";\r
+        foreach ($pattern as $key => $value) {\r
+            if ($key % 2) {\r
+                $match.= $value;\r
+            } else {\r
+                $escaped = $db->escape($value);\r
+                if (PEAR::isError($escaped)) {\r
+                    return $escaped;\r
+                }\r
+                $match.= $db->escapePattern($escaped);\r
+            }\r
+        }\r
+        $match.= "'";\r
+        $match.= $this->patternEscapeString();\r
+        return $match;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ patternEscapeString()\r
+\r
+    /**\r
+     * build string to define pattern escape character\r
+     *\r
+     * @access public\r
+     *\r
+     * @return string define pattern escape character\r
+     */\r
+    function patternEscapeString()\r
+    {\r
+        return '';\r
+    }\r
+\r
+    // }}}\r
+    // {{{ mapNativeDatatype()\r
+\r
+    /**\r
+     * Maps a native array description of a field to a MDB2 datatype and length\r
+     *\r
+     * @param array  $field native field description\r
+     * @return array containing the various possible types, length, sign, fixed\r
+     * @access public\r
+     */\r
+    function mapNativeDatatype($field)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        // If the user has specified an option to map the native field\r
+        // type to a custom MDB2 datatype...\r
+        $db_type = strtok($field['type'], '(), ');\r
+        if (!empty($db->options['nativetype_map_callback'][$db_type])) {\r
+            return call_user_func_array($db->options['nativetype_map_callback'][$db_type], array($db, $field));\r
+        }\r
+\r
+        // Otherwise perform the built-in (i.e. normal) MDB2 native type to\r
+        // MDB2 datatype conversion\r
+        return $this->_mapNativeDatatype($field);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _mapNativeDatatype()\r
+\r
+    /**\r
+     * Maps a native array description of a field to a MDB2 datatype and length\r
+     *\r
+     * @param array  $field native field description\r
+     * @return array containing the various possible types, length, sign, fixed\r
+     * @access public\r
+     */\r
+    function _mapNativeDatatype($field)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ mapPrepareDatatype()\r
+\r
+    /**\r
+     * Maps an mdb2 datatype to mysqli prepare type\r
+     *\r
+     * @param string $type\r
+     * @return string\r
+     * @access public\r
+     */\r
+    function mapPrepareDatatype($type)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        if (!empty($db->options['datatype_map'][$type])) {\r
+            $type = $db->options['datatype_map'][$type];\r
+            if (!empty($db->options['datatype_map_callback'][$type])) {\r
+                $parameter = array('type' => $type);\r
+                return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));\r
+            }\r
+        }\r
+\r
+        return $type;\r
+    }\r
+}\r
+?>\r
index 93dd40524e6795ac4f2ee1a5a152df0d9fb22f63..299901ae6e713b043c121dfccdb650361a3f7700 100644 (file)
-<?php
-// vim: set et ts=4 sw=4 fdm=marker:
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: mysql.php,v 1.65 2008/02/22 19:23:49 quipo Exp $
-//
-
-require_once('MDB2/Driver/Datatype/Common.php');
-
-/**
- * MDB2 MySQL driver
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Datatype_mysql extends MDB2_Driver_Datatype_Common
-{
-    // {{{ _getCharsetFieldDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET
-     * of a field declaration to be used in statements like CREATE TABLE.
-     *
-     * @param string $charset   name of the charset
-     * @return string  DBMS specific SQL code portion needed to set the CHARACTER SET
-     *                 of a field declaration.
-     */
-    function _getCharsetFieldDeclaration($charset)
-    {
-        return 'CHARACTER SET '.$charset;
-    }
-
-    // }}}
-    // {{{ _getCollationFieldDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to set the COLLATION
-     * of a field declaration to be used in statements like CREATE TABLE.
-     *
-     * @param string $collation   name of the collation
-     * @return string  DBMS specific SQL code portion needed to set the COLLATION
-     *                 of a field declaration.
-     */
-    function _getCollationFieldDeclaration($collation)
-    {
-        return 'COLLATE '.$collation;
-    }
-
-    // }}}
-    // {{{ getTypeDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare an text type
-     * field to be used in statements like CREATE TABLE.
-     *
-     * @param array $field  associative array with the name of the properties
-     *      of the field being declared as array indexes. Currently, the types
-     *      of supported field properties are as follows:
-     *
-     *      length
-     *          Integer value that determines the maximum length of the text
-     *          field. If this argument is missing the field should be
-     *          declared to have the longest length allowed by the DBMS.
-     *
-     *      default
-     *          Text value to be used as default for this field.
-     *
-     *      notnull
-     *          Boolean flag that indicates whether this field is constrained
-     *          to not be set to null.
-     * @return string  DBMS specific SQL code portion that should be used to
-     *      declare the specified field.
-     * @access public
-     */
-    function getTypeDeclaration($field)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        switch ($field['type']) {
-        case 'text':
-            if (empty($field['length']) && array_key_exists('default', $field)) {
-                $field['length'] = $db->varchar_max_length;
-            }
-            $length = !empty($field['length']) ? $field['length'] : false;
-            $fixed = !empty($field['fixed']) ? $field['fixed'] : false;
-            return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR(255)')
-                : ($length ? 'VARCHAR('.$length.')' : 'TEXT');
-        case 'clob':
-            if (!empty($field['length'])) {
-                $length = $field['length'];
-                if ($length <= 255) {
-                    return 'TINYTEXT';
-                } elseif ($length <= 65532) {
-                    return 'TEXT';
-                } elseif ($length <= 16777215) {
-                    return 'MEDIUMTEXT';
-                }
-            }
-            return 'LONGTEXT';
-        case 'blob':
-            if (!empty($field['length'])) {
-                $length = $field['length'];
-                if ($length <= 255) {
-                    return 'TINYBLOB';
-                } elseif ($length <= 65532) {
-                    return 'BLOB';
-                } elseif ($length <= 16777215) {
-                    return 'MEDIUMBLOB';
-                }
-            }
-            return 'LONGBLOB';
-        case 'integer':
-            if (!empty($field['length'])) {
-                $length = $field['length'];
-                if ($length <= 1) {
-                    return 'TINYINT';
-                } elseif ($length == 2) {
-                    return 'SMALLINT';
-                } elseif ($length == 3) {
-                    return 'MEDIUMINT';
-                } elseif ($length == 4) {
-                    return 'INT';
-                } elseif ($length > 4) {
-                    return 'BIGINT';
-                }
-            }
-            return 'INT';
-        case 'boolean':
-            return 'TINYINT(1)';
-        case 'date':
-            return 'DATE';
-        case 'time':
-            return 'TIME';
-        case 'timestamp':
-            return 'DATETIME';
-        case 'float':
-            return 'DOUBLE';
-        case 'decimal':
-            $length = !empty($field['length']) ? $field['length'] : 18;
-            $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places'];
-            return 'DECIMAL('.$length.','.$scale.')';
-        }
-        return '';
-    }
-
-    // }}}
-    // {{{ _getIntegerDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare an integer type
-     * field to be used in statements like CREATE TABLE.
-     *
-     * @param string  $name   name the field to be declared.
-     * @param string  $field  associative array with the name of the properties
-     *                        of the field being declared as array indexes.
-     *                        Currently, the types of supported field
-     *                        properties are as follows:
-     *
-     *                       unsigned
-     *                        Boolean flag that indicates whether the field
-     *                        should be declared as unsigned integer if
-     *                        possible.
-     *
-     *                       default
-     *                        Integer value to be used as default for this
-     *                        field.
-     *
-     *                       notnull
-     *                        Boolean flag that indicates whether this field is
-     *                        constrained to not be set to null.
-     * @return string  DBMS specific SQL code portion that should be used to
-     *                 declare the specified field.
-     * @access protected
-     */
-    function _getIntegerDeclaration($name, $field)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $default = $autoinc = '';
-        if (!empty($field['autoincrement'])) {
-            $autoinc = ' AUTO_INCREMENT PRIMARY KEY';
-        } elseif (array_key_exists('default', $field)) {
-            if ($field['default'] === '') {
-                $field['default'] = empty($field['notnull']) ? null : 0;
-            }
-            $default = ' DEFAULT '.$this->quote($field['default'], 'integer');
-        }
-
-        $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
-        $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED';
-        $name = $db->quoteIdentifier($name, true);
-        return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull.$autoinc;
-    }
-
-    // }}}
-    // {{{ _getFloatDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare an float type
-     * field to be used in statements like CREATE TABLE.
-     *
-     * @param string  $name   name the field to be declared.
-     * @param string  $field  associative array with the name of the properties
-     *                        of the field being declared as array indexes.
-     *                        Currently, the types of supported field
-     *                        properties are as follows:
-     *
-     *                       unsigned
-     *                        Boolean flag that indicates whether the field
-     *                        should be declared as unsigned float if
-     *                        possible.
-     *
-     *                       default
-     *                        float value to be used as default for this
-     *                        field.
-     *
-     *                       notnull
-     *                        Boolean flag that indicates whether this field is
-     *                        constrained to not be set to null.
-     * @return string  DBMS specific SQL code portion that should be used to
-     *                 declare the specified field.
-     * @access protected
-     */
-    function _getFloatDeclaration($name, $field)
-    {
-        // Since AUTO_INCREMENT can be used for integer or floating-point types,
-        // reuse the INTEGER declaration
-        // @see http://bugs.mysql.com/bug.php?id=31032
-        return $this->_getIntegerDeclaration($name, $field);
-    }
-
-    // }}}
-    // {{{ _getDecimalDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare an decimal type
-     * field to be used in statements like CREATE TABLE.
-     *
-     * @param string  $name   name the field to be declared.
-     * @param string  $field  associative array with the name of the properties
-     *                        of the field being declared as array indexes.
-     *                        Currently, the types of supported field
-     *                        properties are as follows:
-     *
-     *                       unsigned
-     *                        Boolean flag that indicates whether the field
-     *                        should be declared as unsigned integer if
-     *                        possible.
-     *
-     *                       default
-     *                        Decimal value to be used as default for this
-     *                        field.
-     *
-     *                       notnull
-     *                        Boolean flag that indicates whether this field is
-     *                        constrained to not be set to null.
-     * @return string  DBMS specific SQL code portion that should be used to
-     *                 declare the specified field.
-     * @access protected
-     */
-    function _getDecimalDeclaration($name, $field)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $default = '';
-        if (array_key_exists('default', $field)) {
-            if ($field['default'] === '') {
-                $field['default'] = empty($field['notnull']) ? null : 0;
-            }
-            $default = ' DEFAULT '.$this->quote($field['default'], 'integer');
-        } elseif (empty($field['notnull'])) {
-            $default = ' DEFAULT NULL';
-        }
-
-        $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
-        $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED';
-        $name = $db->quoteIdentifier($name, true);
-        return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull;
-    }
-
-    // }}}
-    // {{{ matchPattern()
-
-    /**
-     * build a pattern matching string
-     *
-     * @access public
-     *
-     * @param array $pattern even keys are strings, odd are patterns (% and _)
-     * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)
-     * @param string $field optional field name that is being matched against
-     *                  (might be required when emulating ILIKE)
-     *
-     * @return string SQL pattern
-     */
-    function matchPattern($pattern, $operator = null, $field = null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $match = '';
-        if (!is_null($operator)) {
-            $field = is_null($field) ? '' : $field.' ';
-            $operator = strtoupper($operator);
-            switch ($operator) {
-            // case insensitive
-            case 'ILIKE':
-                $match = $field.'LIKE ';
-                break;
-            // case sensitive
-            case 'LIKE':
-                $match = $field.'LIKE BINARY ';
-                break;
-            default:
-                return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                    'not a supported operator type:'. $operator, __FUNCTION__);
-            }
-        }
-        $match.= "'";
-        foreach ($pattern as $key => $value) {
-            if ($key % 2) {
-                $match.= $value;
-            } else {
-                $match.= $db->escapePattern($db->escape($value));
-            }
-        }
-        $match.= "'";
-        $match.= $this->patternEscapeString();
-        return $match;
-    }
-
-    // }}}
-    // {{{ _mapNativeDatatype()
-
-    /**
-     * Maps a native array description of a field to a MDB2 datatype and length
-     *
-     * @param array  $field native field description
-     * @return array containing the various possible types, length, sign, fixed
-     * @access public
-     */
-    function _mapNativeDatatype($field)
-    {
-        $db_type = strtolower($field['type']);
-        $db_type = strtok($db_type, '(), ');
-        if ($db_type == 'national') {
-            $db_type = strtok('(), ');
-        }
-        if (!empty($field['length'])) {
-            $length = strtok($field['length'], ', ');
-            $decimal = strtok(', ');
-        } else {
-            $length = strtok('(), ');
-            $decimal = strtok('(), ');
-        }
-        $type = array();
-        $unsigned = $fixed = null;
-        switch ($db_type) {
-        case 'tinyint':
-            $type[] = 'integer';
-            $type[] = 'boolean';
-            if (preg_match('/^(is|has)/', $field['name'])) {
-                $type = array_reverse($type);
-            }
-            $unsigned = preg_match('/ unsigned/i', $field['type']);
-            $length = 1;
-            break;
-        case 'smallint':
-            $type[] = 'integer';
-            $unsigned = preg_match('/ unsigned/i', $field['type']);
-            $length = 2;
-            break;
-        case 'mediumint':
-            $type[] = 'integer';
-            $unsigned = preg_match('/ unsigned/i', $field['type']);
-            $length = 3;
-            break;
-        case 'int':
-        case 'integer':
-            $type[] = 'integer';
-            $unsigned = preg_match('/ unsigned/i', $field['type']);
-            $length = 4;
-            break;
-        case 'bigint':
-            $type[] = 'integer';
-            $unsigned = preg_match('/ unsigned/i', $field['type']);
-            $length = 8;
-            break;
-        case 'tinytext':
-        case 'mediumtext':
-        case 'longtext':
-        case 'text':
-        case 'varchar':
-            $fixed = false;
-        case 'string':
-        case 'char':
-            $type[] = 'text';
-            if ($length == '1') {
-                $type[] = 'boolean';
-                if (preg_match('/^(is|has)/', $field['name'])) {
-                    $type = array_reverse($type);
-                }
-            } elseif (strstr($db_type, 'text')) {
-                $type[] = 'clob';
-                if ($decimal == 'binary') {
-                    $type[] = 'blob';
-                }
-                $type = array_reverse($type);
-            }
-            if ($fixed !== false) {
-                $fixed = true;
-            }
-            break;
-        case 'enum':
-            $type[] = 'text';
-            preg_match_all('/\'.+\'/U', $field['type'], $matches);
-            $length = 0;
-            $fixed = false;
-            if (is_array($matches)) {
-                foreach ($matches[0] as $value) {
-                    $length = max($length, strlen($value)-2);
-                }
-                if ($length == '1' && count($matches[0]) == 2) {
-                    $type[] = 'boolean';
-                    if (preg_match('/^(is|has)/', $field['name'])) {
-                        $type = array_reverse($type);
-                    }
-                }
-            }
-            $type[] = 'integer';
-        case 'set':
-            $fixed = false;
-            $type[] = 'text';
-            $type[] = 'integer';
-            break;
-        case 'date':
-            $type[] = 'date';
-            $length = null;
-            break;
-        case 'datetime':
-        case 'timestamp':
-            $type[] = 'timestamp';
-            $length = null;
-            break;
-        case 'time':
-            $type[] = 'time';
-            $length = null;
-            break;
-        case 'float':
-        case 'double':
-        case 'real':
-            $type[] = 'float';
-            $unsigned = preg_match('/ unsigned/i', $field['type']);
-            break;
-        case 'unknown':
-        case 'decimal':
-        case 'numeric':
-            $type[] = 'decimal';
-            $unsigned = preg_match('/ unsigned/i', $field['type']);
-            if ($decimal !== false) {
-                $length = $length.','.$decimal;
-            }
-            break;
-        case 'tinyblob':
-        case 'mediumblob':
-        case 'longblob':
-        case 'blob':
-            $type[] = 'blob';
-            $length = null;
-            break;
-        case 'binary':
-        case 'varbinary':
-            $type[] = 'blob';
-            break;
-        case 'year':
-            $type[] = 'integer';
-            $type[] = 'date';
-            $length = null;
-            break;
-        default:
-            $db =$this->getDBInstance();
-            if (PEAR::isError($db)) {
-                return $db;
-            }
-
-            return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'unknown database attribute type: '.$db_type, __FUNCTION__);
-        }
-
-        if ((int)$length <= 0) {
-            $length = null;
-        }
-
-        return array($type, $length, $unsigned, $fixed);
-    }
-
-    // }}}
-}
-
+<?php\r
+// vim: set et ts=4 sw=4 fdm=marker:\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: mysql.php 295587 2010-02-28 17:16:38Z quipo $\r
+//\r
+\r
+require_once 'MDB2/Driver/Datatype/Common.php';\r
+\r
+/**\r
+ * MDB2 MySQL driver\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Driver_Datatype_mysql extends MDB2_Driver_Datatype_Common\r
+{\r
+    // {{{ _getCharsetFieldDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET\r
+     * of a field declaration to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string $charset   name of the charset\r
+     * @return string  DBMS specific SQL code portion needed to set the CHARACTER SET\r
+     *                 of a field declaration.\r
+     */\r
+    function _getCharsetFieldDeclaration($charset)\r
+    {\r
+        return 'CHARACTER SET '.$charset;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getCollationFieldDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to set the COLLATION\r
+     * of a field declaration to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string $collation   name of the collation\r
+     * @return string  DBMS specific SQL code portion needed to set the COLLATION\r
+     *                 of a field declaration.\r
+     */\r
+    function _getCollationFieldDeclaration($collation)\r
+    {\r
+        return 'COLLATE '.$collation;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getTypeDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare an text type\r
+     * field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param array $field  associative array with the name of the properties\r
+     *      of the field being declared as array indexes. Currently, the types\r
+     *      of supported field properties are as follows:\r
+     *\r
+     *      length\r
+     *          Integer value that determines the maximum length of the text\r
+     *          field. If this argument is missing the field should be\r
+     *          declared to have the longest length allowed by the DBMS.\r
+     *\r
+     *      default\r
+     *          Text value to be used as default for this field.\r
+     *\r
+     *      notnull\r
+     *          Boolean flag that indicates whether this field is constrained\r
+     *          to not be set to null.\r
+     * @return string  DBMS specific SQL code portion that should be used to\r
+     *      declare the specified field.\r
+     * @access public\r
+     */\r
+    function getTypeDeclaration($field)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        switch ($field['type']) {\r
+        case 'text':\r
+            if (empty($field['length']) && array_key_exists('default', $field)) {\r
+                $field['length'] = $db->varchar_max_length;\r
+            }\r
+            $length = !empty($field['length']) ? $field['length'] : false;\r
+            $fixed = !empty($field['fixed']) ? $field['fixed'] : false;\r
+            return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR(255)')\r
+                : ($length ? 'VARCHAR('.$length.')' : 'TEXT');\r
+        case 'clob':\r
+            if (!empty($field['length'])) {\r
+                $length = $field['length'];\r
+                if ($length <= 255) {\r
+                    return 'TINYTEXT';\r
+                } elseif ($length <= 65532) {\r
+                    return 'TEXT';\r
+                } elseif ($length <= 16777215) {\r
+                    return 'MEDIUMTEXT';\r
+                }\r
+            }\r
+            return 'LONGTEXT';\r
+        case 'blob':\r
+            if (!empty($field['length'])) {\r
+                $length = $field['length'];\r
+                if ($length <= 255) {\r
+                    return 'TINYBLOB';\r
+                } elseif ($length <= 65532) {\r
+                    return 'BLOB';\r
+                } elseif ($length <= 16777215) {\r
+                    return 'MEDIUMBLOB';\r
+                }\r
+            }\r
+            return 'LONGBLOB';\r
+        case 'integer':\r
+            if (!empty($field['length'])) {\r
+                $length = $field['length'];\r
+                if ($length <= 1) {\r
+                    return 'TINYINT';\r
+                } elseif ($length == 2) {\r
+                    return 'SMALLINT';\r
+                } elseif ($length == 3) {\r
+                    return 'MEDIUMINT';\r
+                } elseif ($length == 4) {\r
+                    return 'INT';\r
+                } elseif ($length > 4) {\r
+                    return 'BIGINT';\r
+                }\r
+            }\r
+            return 'INT';\r
+        case 'boolean':\r
+            return 'TINYINT(1)';\r
+        case 'date':\r
+            return 'DATE';\r
+        case 'time':\r
+            return 'TIME';\r
+        case 'timestamp':\r
+            return 'DATETIME';\r
+        case 'float':\r
+            return 'DOUBLE';\r
+        case 'decimal':\r
+            $length = !empty($field['length']) ? $field['length'] : 18;\r
+            $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places'];\r
+            return 'DECIMAL('.$length.','.$scale.')';\r
+        }\r
+        return '';\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getIntegerDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare an integer type\r
+     * field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string  $name   name the field to be declared.\r
+     * @param string  $field  associative array with the name of the properties\r
+     *                        of the field being declared as array indexes.\r
+     *                        Currently, the types of supported field\r
+     *                        properties are as follows:\r
+     *\r
+     *                       unsigned\r
+     *                        Boolean flag that indicates whether the field\r
+     *                        should be declared as unsigned integer if\r
+     *                        possible.\r
+     *\r
+     *                       default\r
+     *                        Integer value to be used as default for this\r
+     *                        field.\r
+     *\r
+     *                       notnull\r
+     *                        Boolean flag that indicates whether this field is\r
+     *                        constrained to not be set to null.\r
+     * @return string  DBMS specific SQL code portion that should be used to\r
+     *                 declare the specified field.\r
+     * @access protected\r
+     */\r
+    function _getIntegerDeclaration($name, $field)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $default = $autoinc = '';\r
+        if (!empty($field['autoincrement'])) {\r
+            $autoinc = ' AUTO_INCREMENT PRIMARY KEY';\r
+        } elseif (array_key_exists('default', $field)) {\r
+            if ($field['default'] === '') {\r
+                $field['default'] = empty($field['notnull']) ? null : 0;\r
+            }\r
+            $default = ' DEFAULT '.$this->quote($field['default'], 'integer');\r
+        }\r
+\r
+        $notnull = empty($field['notnull']) ? '' : ' NOT NULL';\r
+        $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED';\r
+        if (empty($default) && empty($notnull)) {\r
+            $default = ' DEFAULT NULL';\r
+        }\r
+        $name = $db->quoteIdentifier($name, true);\r
+        return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull.$autoinc;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getFloatDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare an float type\r
+     * field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string  $name   name the field to be declared.\r
+     * @param string  $field  associative array with the name of the properties\r
+     *                        of the field being declared as array indexes.\r
+     *                        Currently, the types of supported field\r
+     *                        properties are as follows:\r
+     *\r
+     *                       unsigned\r
+     *                        Boolean flag that indicates whether the field\r
+     *                        should be declared as unsigned float if\r
+     *                        possible.\r
+     *\r
+     *                       default\r
+     *                        float value to be used as default for this\r
+     *                        field.\r
+     *\r
+     *                       notnull\r
+     *                        Boolean flag that indicates whether this field is\r
+     *                        constrained to not be set to null.\r
+     * @return string  DBMS specific SQL code portion that should be used to\r
+     *                 declare the specified field.\r
+     * @access protected\r
+     */\r
+    function _getFloatDeclaration($name, $field)\r
+    {\r
+        // Since AUTO_INCREMENT can be used for integer or floating-point types,\r
+        // reuse the INTEGER declaration\r
+        // @see http://bugs.mysql.com/bug.php?id=31032\r
+        return $this->_getIntegerDeclaration($name, $field);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getDecimalDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare an decimal type\r
+     * field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string  $name   name the field to be declared.\r
+     * @param string  $field  associative array with the name of the properties\r
+     *                        of the field being declared as array indexes.\r
+     *                        Currently, the types of supported field\r
+     *                        properties are as follows:\r
+     *\r
+     *                       unsigned\r
+     *                        Boolean flag that indicates whether the field\r
+     *                        should be declared as unsigned integer if\r
+     *                        possible.\r
+     *\r
+     *                       default\r
+     *                        Decimal value to be used as default for this\r
+     *                        field.\r
+     *\r
+     *                       notnull\r
+     *                        Boolean flag that indicates whether this field is\r
+     *                        constrained to not be set to null.\r
+     * @return string  DBMS specific SQL code portion that should be used to\r
+     *                 declare the specified field.\r
+     * @access protected\r
+     */\r
+    function _getDecimalDeclaration($name, $field)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $default = '';\r
+        if (array_key_exists('default', $field)) {\r
+            if ($field['default'] === '') {\r
+                $field['default'] = empty($field['notnull']) ? null : 0;\r
+            }\r
+            $default = ' DEFAULT '.$this->quote($field['default'], 'integer');\r
+        } elseif (empty($field['notnull'])) {\r
+            $default = ' DEFAULT NULL';\r
+        }\r
+\r
+        $notnull = empty($field['notnull']) ? '' : ' NOT NULL';\r
+        $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED';\r
+        $name = $db->quoteIdentifier($name, true);\r
+        return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ matchPattern()\r
+\r
+    /**\r
+     * build a pattern matching string\r
+     *\r
+     * @access public\r
+     *\r
+     * @param array $pattern even keys are strings, odd are patterns (% and _)\r
+     * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)\r
+     * @param string $field optional field name that is being matched against\r
+     *                  (might be required when emulating ILIKE)\r
+     *\r
+     * @return string SQL pattern\r
+     */\r
+    function matchPattern($pattern, $operator = null, $field = null)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $match = '';\r
+        if (null !== $operator) {\r
+            $field = (null === $field) ? '' : $field.' ';\r
+            $operator = strtoupper($operator);\r
+            switch ($operator) {\r
+            // case insensitive\r
+            case 'ILIKE':\r
+                $match = $field.'LIKE ';\r
+                break;\r
+            case 'NOT ILIKE':\r
+                $match = $field.'NOT LIKE ';\r
+                break;\r
+            // case sensitive\r
+            case 'LIKE':\r
+                $match = $field.'LIKE BINARY ';\r
+                break;\r
+            case 'NOT LIKE':\r
+                $match = $field.'NOT LIKE BINARY ';\r
+                break;\r
+            default:\r
+                return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                    'not a supported operator type:'. $operator, __FUNCTION__);\r
+            }\r
+        }\r
+        $match.= "'";\r
+        foreach ($pattern as $key => $value) {\r
+            if ($key % 2) {\r
+                $match.= $value;\r
+            } else {\r
+                $match.= $db->escapePattern($db->escape($value));\r
+            }\r
+        }\r
+        $match.= "'";\r
+        $match.= $this->patternEscapeString();\r
+        return $match;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _mapNativeDatatype()\r
+\r
+    /**\r
+     * Maps a native array description of a field to a MDB2 datatype and length\r
+     *\r
+     * @param array  $field native field description\r
+     * @return array containing the various possible types, length, sign, fixed\r
+     * @access public\r
+     */\r
+    function _mapNativeDatatype($field)\r
+    {\r
+        $db_type = strtolower($field['type']);\r
+        $db_type = strtok($db_type, '(), ');\r
+        if ($db_type == 'national') {\r
+            $db_type = strtok('(), ');\r
+        }\r
+        if (!empty($field['length'])) {\r
+            $length = strtok($field['length'], ', ');\r
+            $decimal = strtok(', ');\r
+        } else {\r
+            $length = strtok('(), ');\r
+            $decimal = strtok('(), ');\r
+        }\r
+        $type = array();\r
+        $unsigned = $fixed = null;\r
+        switch ($db_type) {\r
+        case 'tinyint':\r
+            $type[] = 'integer';\r
+            $type[] = 'boolean';\r
+            if (preg_match('/^(is|has)/', $field['name'])) {\r
+                $type = array_reverse($type);\r
+            }\r
+            $unsigned = preg_match('/ unsigned/i', $field['type']);\r
+            $length = 1;\r
+            break;\r
+        case 'smallint':\r
+            $type[] = 'integer';\r
+            $unsigned = preg_match('/ unsigned/i', $field['type']);\r
+            $length = 2;\r
+            break;\r
+        case 'mediumint':\r
+            $type[] = 'integer';\r
+            $unsigned = preg_match('/ unsigned/i', $field['type']);\r
+            $length = 3;\r
+            break;\r
+        case 'int':\r
+        case 'integer':\r
+            $type[] = 'integer';\r
+            $unsigned = preg_match('/ unsigned/i', $field['type']);\r
+            $length = 4;\r
+            break;\r
+        case 'bigint':\r
+            $type[] = 'integer';\r
+            $unsigned = preg_match('/ unsigned/i', $field['type']);\r
+            $length = 8;\r
+            break;\r
+        case 'tinytext':\r
+        case 'mediumtext':\r
+        case 'longtext':\r
+        case 'text':\r
+        case 'varchar':\r
+            $fixed = false;\r
+        case 'string':\r
+        case 'char':\r
+            $type[] = 'text';\r
+            if ($length == '1') {\r
+                $type[] = 'boolean';\r
+                if (preg_match('/^(is|has)/', $field['name'])) {\r
+                    $type = array_reverse($type);\r
+                }\r
+            } elseif (strstr($db_type, 'text')) {\r
+                $type[] = 'clob';\r
+                if ($decimal == 'binary') {\r
+                    $type[] = 'blob';\r
+                }\r
+                $type = array_reverse($type);\r
+            }\r
+            if ($fixed !== false) {\r
+                $fixed = true;\r
+            }\r
+            break;\r
+        case 'enum':\r
+            $type[] = 'text';\r
+            preg_match_all('/\'.+\'/U', $field['type'], $matches);\r
+            $length = 0;\r
+            $fixed = false;\r
+            if (is_array($matches)) {\r
+                foreach ($matches[0] as $value) {\r
+                    $length = max($length, strlen($value)-2);\r
+                }\r
+                if ($length == '1' && count($matches[0]) == 2) {\r
+                    $type[] = 'boolean';\r
+                    if (preg_match('/^(is|has)/', $field['name'])) {\r
+                        $type = array_reverse($type);\r
+                    }\r
+                }\r
+            }\r
+            $type[] = 'integer';\r
+        case 'set':\r
+            $fixed = false;\r
+            $type[] = 'text';\r
+            $type[] = 'integer';\r
+            break;\r
+        case 'date':\r
+            $type[] = 'date';\r
+            $length = null;\r
+            break;\r
+        case 'datetime':\r
+        case 'timestamp':\r
+            $type[] = 'timestamp';\r
+            $length = null;\r
+            break;\r
+        case 'time':\r
+            $type[] = 'time';\r
+            $length = null;\r
+            break;\r
+        case 'float':\r
+        case 'double':\r
+        case 'real':\r
+            $type[] = 'float';\r
+            $unsigned = preg_match('/ unsigned/i', $field['type']);\r
+            break;\r
+        case 'unknown':\r
+        case 'decimal':\r
+        case 'numeric':\r
+            $type[] = 'decimal';\r
+            $unsigned = preg_match('/ unsigned/i', $field['type']);\r
+            if ($decimal !== false) {\r
+                $length = $length.','.$decimal;\r
+            }\r
+            break;\r
+        case 'tinyblob':\r
+        case 'mediumblob':\r
+        case 'longblob':\r
+        case 'blob':\r
+            $type[] = 'blob';\r
+            $length = null;\r
+            break;\r
+        case 'binary':\r
+        case 'varbinary':\r
+            $type[] = 'blob';\r
+            break;\r
+        case 'year':\r
+            $type[] = 'integer';\r
+            $type[] = 'date';\r
+            $length = null;\r
+            break;\r
+        default:\r
+            $db = $this->getDBInstance();\r
+            if (PEAR::isError($db)) {\r
+                return $db;\r
+            }\r
+\r
+            return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'unknown database attribute type: '.$db_type, __FUNCTION__);\r
+        }\r
+\r
+        if ((int)$length <= 0) {\r
+            $length = null;\r
+        }\r
+\r
+        return array($type, $length, $unsigned, $fixed);\r
+    }\r
+\r
+    // }}}\r
+}\r
+\r
 ?>
\ No newline at end of file
index e72aa743b738cc722dab21b2bc3c81d7470ef138..fec2c9799f507e13e4afef546d9c181028e0d785 100644 (file)
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Paul Cooper <pgc@ucecom.com>                                 |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.93 2008/08/28 20:32:57 afz Exp $
-
-require_once('MDB2/Driver/Datatype/Common.php');
-
-/**
- * MDB2 PostGreSQL driver
- *
- * @package MDB2
- * @category Database
- * @author  Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_Driver_Datatype_pgsql extends MDB2_Driver_Datatype_Common
-{
-    // {{{ _baseConvertResult()
-
-    /**
-     * General type conversion method
-     *
-     * @param mixed   $value refernce to a value to be converted
-     * @param string  $type  specifies which type to convert to
-     * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text
-     * @return object a MDB2 error on failure
-     * @access protected
-     */
-    function _baseConvertResult($value, $type, $rtrim = true)
-    {
-        if (is_null($value)) {
-            return null;
-        }
-        switch ($type) {
-        case 'boolean':
-            return $value == 't';
-        case 'float':
-            return doubleval($value);
-        case 'date':
-            return $value;
-        case 'time':
-            return substr($value, 0, strlen('HH:MM:SS'));
-        case 'timestamp':
-            return substr($value, 0, strlen('YYYY-MM-DD HH:MM:SS'));
-        case 'blob':
-            $value = pg_unescape_bytea($value);
-            return parent::_baseConvertResult($value, $type, $rtrim);
-        }
-        return parent::_baseConvertResult($value, $type, $rtrim);
-    }
-
-    // }}}
-    // {{{ getTypeDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare an text type
-     * field to be used in statements like CREATE TABLE.
-     *
-     * @param array $field  associative array with the name of the properties
-     *      of the field being declared as array indexes. Currently, the types
-     *      of supported field properties are as follows:
-     *
-     *      length
-     *          Integer value that determines the maximum length of the text
-     *          field. If this argument is missing the field should be
-     *          declared to have the longest length allowed by the DBMS.
-     *
-     *      default
-     *          Text value to be used as default for this field.
-     *
-     *      notnull
-     *          Boolean flag that indicates whether this field is constrained
-     *          to not be set to null.
-     * @return string  DBMS specific SQL code portion that should be used to
-     *      declare the specified field.
-     * @access public
-     */
-    function getTypeDeclaration($field)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        switch ($field['type']) {
-        case 'text':
-            $length = !empty($field['length']) ? $field['length'] : false;
-            $fixed = !empty($field['fixed']) ? $field['fixed'] : false;
-            return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')')
-                : ($length ? 'VARCHAR('.$length.')' : 'TEXT');
-        case 'clob':
-            return 'TEXT';
-        case 'blob':
-            return 'BYTEA';
-        case 'integer':
-            if (!empty($field['autoincrement'])) {
-                if (!empty($field['length'])) {
-                    $length = $field['length'];
-                    if ($length > 4) {
-                        return 'BIGSERIAL PRIMARY KEY';
-                    }
-                }
-                return 'SERIAL PRIMARY KEY';
-            }
-            if (!empty($field['length'])) {
-                $length = $field['length'];
-                if ($length <= 2) {
-                    return 'SMALLINT';
-                } elseif ($length == 3 || $length == 4) {
-                    return 'INT';
-                } elseif ($length > 4) {
-                    return 'BIGINT';
-                }
-            }
-            return 'INT';
-        case 'boolean':
-            return 'BOOLEAN';
-        case 'date':
-            return 'DATE';
-        case 'time':
-            return 'TIME without time zone';
-        case 'timestamp':
-            return 'TIMESTAMP without time zone';
-        case 'float':
-            return 'FLOAT8';
-        case 'decimal':
-            $length = !empty($field['length']) ? $field['length'] : 18;
-            $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places'];
-            return 'NUMERIC('.$length.','.$scale.')';
-        }
-    }
-
-    // }}}
-    // {{{ _getIntegerDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare an integer type
-     * field to be used in statements like CREATE TABLE.
-     *
-     * @param string $name name the field to be declared.
-     * @param array $field associative array with the name of the properties
-     *       of the field being declared as array indexes. Currently, the types
-     *       of supported field properties are as follows:
-     *
-     *       unsigned
-     *           Boolean flag that indicates whether the field should be
-     *           declared as unsigned integer if possible.
-     *
-     *       default
-     *           Integer value to be used as default for this field.
-     *
-     *       notnull
-     *           Boolean flag that indicates whether this field is constrained
-     *           to not be set to null.
-     * @return string DBMS specific SQL code portion that should be used to
-     *       declare the specified field.
-     * @access protected
-     */
-    function _getIntegerDeclaration($name, $field)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        if (!empty($field['unsigned'])) {
-            $db->warnings[] = "unsigned integer field \"$name\" is being declared as signed integer";
-        }
-        if (!empty($field['autoincrement'])) {
-            $name = $db->quoteIdentifier($name, true);
-            return $name.' '.$this->getTypeDeclaration($field);
-        }
-        $default = '';
-        if (array_key_exists('default', $field)) {
-            if ($field['default'] === '') {
-                $field['default'] = empty($field['notnull']) ? null : 0;
-            }
-            $default = ' DEFAULT '.$this->quote($field['default'], 'integer');
-        }
-
-        $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
-        $name = $db->quoteIdentifier($name, true);
-        return $name.' '.$this->getTypeDeclaration($field).$default.$notnull;
-    }
-
-    // }}}
-    // {{{ _quoteCLOB()
-
-    /**
-     * Convert a text value into a DBMS specific format that is suitable to
-     * compose query statements.
-     *
-     * @param string $value text string value that is intended to be converted.
-     * @param bool $quote determines if the value should be quoted and escaped
-     * @param bool $escape_wildcards if to escape escape wildcards
-     * @return string text string that represents the given argument value in
-     *      a DBMS specific format.
-     * @access protected
-     */
-    function _quoteCLOB($value, $quote, $escape_wildcards)
-    {
-        return $this->_quoteText($value, $quote, $escape_wildcards);
-    }
-
-    // }}}
-    // {{{ _quoteBLOB()
-
-    /**
-     * Convert a text value into a DBMS specific format that is suitable to
-     * compose query statements.
-     *
-     * @param string $value text string value that is intended to be converted.
-     * @param bool $quote determines if the value should be quoted and escaped
-     * @param bool $escape_wildcards if to escape escape wildcards
-     * @return string text string that represents the given argument value in
-     *      a DBMS specific format.
-     * @access protected
-     */
-    function _quoteBLOB($value, $quote, $escape_wildcards)
-    {
-        if (!$quote) {
-            return $value;
-        }
-        if (version_compare(PHP_VERSION, '5.2.0RC6', '>=')) {
-            $db =$this->getDBInstance();
-            if (PEAR::isError($db)) {
-                return $db;
-            }
-            $connection = $db->getConnection();
-            if (PEAR::isError($connection)) {
-                return $connection;
-            }
-            $value = @pg_escape_bytea($connection, $value);
-        } else {
-            $value = @pg_escape_bytea($value);
-        }
-        return "'".$value."'";
-    }
-
-    // }}}
-    // {{{ _quoteBoolean()
-
-    /**
-     * Convert a text value into a DBMS specific format that is suitable to
-     * compose query statements.
-     *
-     * @param string $value text string value that is intended to be converted.
-     * @param bool $quote determines if the value should be quoted and escaped
-     * @param bool $escape_wildcards if to escape escape wildcards
-     * @return string text string that represents the given argument value in
-     *       a DBMS specific format.
-     * @access protected
-     */
-    function _quoteBoolean($value, $quote, $escape_wildcards)
-    {
-        $value = $value ? 't' : 'f';
-        if (!$quote) {
-            return $value;
-        }
-        return "'".$value."'";
-    }
-
-    // }}}
-    // {{{ matchPattern()
-
-    /**
-     * build a pattern matching string
-     *
-     * @access public
-     *
-     * @param array $pattern even keys are strings, odd are patterns (% and _)
-     * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)
-     * @param string $field optional field name that is being matched against
-     *                  (might be required when emulating ILIKE)
-     *
-     * @return string SQL pattern
-     */
-    function matchPattern($pattern, $operator = null, $field = null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $match = '';
-        if (!is_null($operator)) {
-            $field = is_null($field) ? '' : $field.' ';
-            $operator = strtoupper($operator);
-            switch ($operator) {
-            // case insensitive
-            case 'ILIKE':
-                $match = $field.'ILIKE ';
-                break;
-            // case sensitive
-            case 'LIKE':
-                $match = $field.'LIKE ';
-                break;
-            default:
-                return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                    'not a supported operator type:'. $operator, __FUNCTION__);
-            }
-        }
-        $match.= "'";
-        foreach ($pattern as $key => $value) {
-            if ($key % 2) {
-                $match.= $value;
-            } else {
-                $match.= $db->escapePattern($db->escape($value));
-            }
-        }
-        $match.= "'";
-        $match.= $this->patternEscapeString();
-        return $match;
-    }
-
-    // }}}
-    // {{{ patternEscapeString()
-
-    /**
-     * build string to define escape pattern string
-     *
-     * @access public
-     *
-     *
-     * @return string define escape pattern
-     */
-    function patternEscapeString()
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-        return ' ESCAPE '.$this->quote($db->string_quoting['escape_pattern']);
-    }
-
-    // }}}
-    // {{{ _mapNativeDatatype()
-
-    /**
-     * Maps a native array description of a field to a MDB2 datatype and length
-     *
-     * @param array  $field native field description
-     * @return array containing the various possible types, length, sign, fixed
-     * @access public
-     */
-    function _mapNativeDatatype($field)
-    {
-        $db_type = strtolower($field['type']);
-        $length = $field['length'];
-        $type = array();
-        $unsigned = $fixed = null;
-        switch ($db_type) {
-        case 'smallint':
-        case 'int2':
-            $type[] = 'integer';
-            $unsigned = false;
-            $length = 2;
-            if ($length == '2') {
-                $type[] = 'boolean';
-                if (preg_match('/^(is|has)/', $field['name'])) {
-                    $type = array_reverse($type);
-                }
-            }
-            break;
-        case 'int':
-        case 'int4':
-        case 'integer':
-        case 'serial':
-        case 'serial4':
-            $type[] = 'integer';
-            $unsigned = false;
-            $length = 4;
-            break;
-        case 'bigint':
-        case 'int8':
-        case 'bigserial':
-        case 'serial8':
-            $type[] = 'integer';
-            $unsigned = false;
-            $length = 8;
-            break;
-        case 'bool':
-        case 'boolean':
-            $type[] = 'boolean';
-            $length = null;
-            break;
-        case 'text':
-        case 'varchar':
-            $fixed = false;
-        case 'unknown':
-        case 'char':
-        case 'bpchar':
-            $type[] = 'text';
-            if ($length == '1') {
-                $type[] = 'boolean';
-                if (preg_match('/^(is|has)/', $field['name'])) {
-                    $type = array_reverse($type);
-                }
-            } elseif (strstr($db_type, 'text')) {
-                $type[] = 'clob';
-                $type = array_reverse($type);
-            }
-            if ($fixed !== false) {
-                $fixed = true;
-            }
-            break;
-        case 'date':
-            $type[] = 'date';
-            $length = null;
-            break;
-        case 'datetime':
-        case 'timestamp':
-        case 'timestamptz':
-            $type[] = 'timestamp';
-            $length = null;
-            break;
-        case 'time':
-            $type[] = 'time';
-            $length = null;
-            break;
-        case 'float':
-        case 'float4':
-        case 'float8':
-        case 'double':
-        case 'real':
-            $type[] = 'float';
-            break;
-        case 'decimal':
-        case 'money':
-        case 'numeric':
-            $type[] = 'decimal';
-            if (isset($field['scale'])) {
-                $length = $length.','.$field['scale'];
-            }
-            break;
-        case 'tinyblob':
-        case 'mediumblob':
-        case 'longblob':
-        case 'blob':
-        case 'bytea':
-            $type[] = 'blob';
-            $length = null;
-            break;
-        case 'oid':
-            $type[] = 'blob';
-            $type[] = 'clob';
-            $length = null;
-            break;
-        case 'year':
-            $type[] = 'integer';
-            $type[] = 'date';
-            $length = null;
-            break;
-        default:
-            $db =$this->getDBInstance();
-            if (PEAR::isError($db)) {
-                return $db;
-            }
-            return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'unknown database attribute type: '.$db_type, __FUNCTION__);
-        }
-
-        if ((int)$length <= 0) {
-            $length = null;
-        }
-
-        return array($type, $length, $unsigned, $fixed);
-    }
-
-    // }}}
-    // {{{ mapPrepareDatatype()
-
-    /**
-     * Maps an mdb2 datatype to native prepare type
-     *
-     * @param string $type
-     * @return string
-     * @access public
-     */
-    function mapPrepareDatatype($type)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        if (!empty($db->options['datatype_map'][$type])) {
-            $type = $db->options['datatype_map'][$type];
-            if (!empty($db->options['datatype_map_callback'][$type])) {
-                $parameter = array('type' => $type);
-                return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
-            }
-        }
-
-        switch ($type) {
-            case 'integer':
-                return 'int';
-            case 'boolean':
-                return 'bool';
-            case 'decimal':
-            case 'float':
-                return 'numeric';
-            case 'clob':
-                return 'text';
-            case 'blob':
-                return 'bytea';
-            default:
-                break;
-        }
-        return $type;
-    }
-    // }}}
-}
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Paul Cooper <pgc@ucecom.com>                                 |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: pgsql.php 298763 2010-04-29 08:49:41Z afz $\r
+\r
+require_once 'MDB2/Driver/Datatype/Common.php';\r
+\r
+/**\r
+ * MDB2 PostGreSQL driver\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Paul Cooper <pgc@ucecom.com>\r
+ */\r
+class MDB2_Driver_Datatype_pgsql extends MDB2_Driver_Datatype_Common\r
+{\r
+    // {{{ _baseConvertResult()\r
+\r
+    /**\r
+     * General type conversion method\r
+     *\r
+     * @param mixed   $value refernce to a value to be converted\r
+     * @param string  $type  specifies which type to convert to\r
+     * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text\r
+     * @return object a MDB2 error on failure\r
+     * @access protected\r
+     */\r
+    function _baseConvertResult($value, $type, $rtrim = true)\r
+    {\r
+        if (null === $value) {\r
+            return null;\r
+        }\r
+        switch ($type) {\r
+        case 'boolean':\r
+            return $value == 't';\r
+        case 'float':\r
+            return doubleval($value);\r
+        case 'date':\r
+            return $value;\r
+        case 'time':\r
+            return substr($value, 0, strlen('HH:MM:SS'));\r
+        case 'timestamp':\r
+            return substr($value, 0, strlen('YYYY-MM-DD HH:MM:SS'));\r
+        case 'blob':\r
+            $value = pg_unescape_bytea($value);\r
+            return parent::_baseConvertResult($value, $type, $rtrim);\r
+        }\r
+        return parent::_baseConvertResult($value, $type, $rtrim);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getTypeDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare an text type\r
+     * field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param array $field  associative array with the name of the properties\r
+     *      of the field being declared as array indexes. Currently, the types\r
+     *      of supported field properties are as follows:\r
+     *\r
+     *      length\r
+     *          Integer value that determines the maximum length of the text\r
+     *          field. If this argument is missing the field should be\r
+     *          declared to have the longest length allowed by the DBMS.\r
+     *\r
+     *      default\r
+     *          Text value to be used as default for this field.\r
+     *\r
+     *      notnull\r
+     *          Boolean flag that indicates whether this field is constrained\r
+     *          to not be set to null.\r
+     * @return string  DBMS specific SQL code portion that should be used to\r
+     *      declare the specified field.\r
+     * @access public\r
+     */\r
+    function getTypeDeclaration($field)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        switch ($field['type']) {\r
+        case 'text':\r
+            $length = !empty($field['length']) ? $field['length'] : false;\r
+            $fixed = !empty($field['fixed']) ? $field['fixed'] : false;\r
+            return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')')\r
+                : ($length ? 'VARCHAR('.$length.')' : 'TEXT');\r
+        case 'clob':\r
+            return 'TEXT';\r
+        case 'blob':\r
+            return 'BYTEA';\r
+        case 'integer':\r
+            if (!empty($field['autoincrement'])) {\r
+                if (!empty($field['length'])) {\r
+                    $length = $field['length'];\r
+                    if ($length > 4) {\r
+                        return 'BIGSERIAL PRIMARY KEY';\r
+                    }\r
+                }\r
+                return 'SERIAL PRIMARY KEY';\r
+            }\r
+            if (!empty($field['length'])) {\r
+                $length = $field['length'];\r
+                if ($length <= 2) {\r
+                    return 'SMALLINT';\r
+                } elseif ($length == 3 || $length == 4) {\r
+                    return 'INT';\r
+                } elseif ($length > 4) {\r
+                    return 'BIGINT';\r
+                }\r
+            }\r
+            return 'INT';\r
+        case 'boolean':\r
+            return 'BOOLEAN';\r
+        case 'date':\r
+            return 'DATE';\r
+        case 'time':\r
+            return 'TIME without time zone';\r
+        case 'timestamp':\r
+            return 'TIMESTAMP without time zone';\r
+        case 'float':\r
+            return 'FLOAT8';\r
+        case 'decimal':\r
+            $length = !empty($field['length']) ? $field['length'] : 18;\r
+            $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places'];\r
+            return 'NUMERIC('.$length.','.$scale.')';\r
+        }\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getIntegerDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare an integer type\r
+     * field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string $name name the field to be declared.\r
+     * @param array $field associative array with the name of the properties\r
+     *       of the field being declared as array indexes. Currently, the types\r
+     *       of supported field properties are as follows:\r
+     *\r
+     *       unsigned\r
+     *           Boolean flag that indicates whether the field should be\r
+     *           declared as unsigned integer if possible.\r
+     *\r
+     *       default\r
+     *           Integer value to be used as default for this field.\r
+     *\r
+     *       notnull\r
+     *           Boolean flag that indicates whether this field is constrained\r
+     *           to not be set to null.\r
+     * @return string DBMS specific SQL code portion that should be used to\r
+     *       declare the specified field.\r
+     * @access protected\r
+     */\r
+    function _getIntegerDeclaration($name, $field)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        if (!empty($field['unsigned'])) {\r
+            $db->warnings[] = "unsigned integer field \"$name\" is being declared as signed integer";\r
+        }\r
+        if (!empty($field['autoincrement'])) {\r
+            $name = $db->quoteIdentifier($name, true);\r
+            return $name.' '.$this->getTypeDeclaration($field);\r
+        }\r
+        $default = '';\r
+        if (array_key_exists('default', $field)) {\r
+            if ($field['default'] === '') {\r
+                $field['default'] = empty($field['notnull']) ? null : 0;\r
+            }\r
+            $default = ' DEFAULT '.$this->quote($field['default'], 'integer');\r
+        }\r
+\r
+        $notnull = empty($field['notnull']) ? '' : ' NOT NULL';\r
+        if (empty($default) && empty($notnull)) {\r
+            $default = ' DEFAULT NULL';\r
+        }\r
+        $name = $db->quoteIdentifier($name, true);\r
+        return $name.' '.$this->getTypeDeclaration($field).$default.$notnull;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _quoteCLOB()\r
+\r
+    /**\r
+     * Convert a text value into a DBMS specific format that is suitable to\r
+     * compose query statements.\r
+     *\r
+     * @param string $value text string value that is intended to be converted.\r
+     * @param bool $quote determines if the value should be quoted and escaped\r
+     * @param bool $escape_wildcards if to escape escape wildcards\r
+     * @return string text string that represents the given argument value in\r
+     *      a DBMS specific format.\r
+     * @access protected\r
+     */\r
+    function _quoteCLOB($value, $quote, $escape_wildcards)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+        $value = $this->_readFile($value, $db->options['lob_allow_url_include']);\r
+        if (PEAR::isError($value)) {\r
+            return $value;\r
+        }\r
+        return $this->_quoteText($value, $quote, $escape_wildcards);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _quoteBLOB()\r
+\r
+    /**\r
+     * Convert a text value into a DBMS specific format that is suitable to\r
+     * compose query statements.\r
+     *\r
+     * @param string $value text string value that is intended to be converted.\r
+     * @param bool $quote determines if the value should be quoted and escaped\r
+     * @param bool $escape_wildcards if to escape escape wildcards\r
+     * @return string text string that represents the given argument value in\r
+     *      a DBMS specific format.\r
+     * @access protected\r
+     */\r
+    function _quoteBLOB($value, $quote, $escape_wildcards)\r
+    {\r
+        if (!$quote) {\r
+            return $value;\r
+        }\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+        $value = $this->_readFile($value, $db->options['lob_allow_url_include']);\r
+        if (PEAR::isError($value)) {\r
+            return $value;\r
+        }\r
+        if (version_compare(PHP_VERSION, '5.2.0RC6', '>=')) {\r
+            $connection = $db->getConnection();\r
+            if (PEAR::isError($connection)) {\r
+                return $connection;\r
+            }\r
+            $value = @pg_escape_bytea($connection, $value);\r
+        } else {\r
+            $value = @pg_escape_bytea($value);\r
+        }\r
+        return "'".$value."'";\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _quoteBoolean()\r
+\r
+    /**\r
+     * Convert a text value into a DBMS specific format that is suitable to\r
+     * compose query statements.\r
+     *\r
+     * @param string $value text string value that is intended to be converted.\r
+     * @param bool $quote determines if the value should be quoted and escaped\r
+     * @param bool $escape_wildcards if to escape escape wildcards\r
+     * @return string text string that represents the given argument value in\r
+     *       a DBMS specific format.\r
+     * @access protected\r
+     */\r
+    function _quoteBoolean($value, $quote, $escape_wildcards)\r
+    {\r
+        $value = $value ? 't' : 'f';\r
+        if (!$quote) {\r
+            return $value;\r
+        }\r
+        return "'".$value."'";\r
+    }\r
+\r
+    // }}}\r
+    // {{{ matchPattern()\r
+\r
+    /**\r
+     * build a pattern matching string\r
+     *\r
+     * @access public\r
+     *\r
+     * @param array $pattern even keys are strings, odd are patterns (% and _)\r
+     * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)\r
+     * @param string $field optional field name that is being matched against\r
+     *                  (might be required when emulating ILIKE)\r
+     *\r
+     * @return string SQL pattern\r
+     */\r
+    function matchPattern($pattern, $operator = null, $field = null)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $match = '';\r
+        if (null !== $operator) {\r
+            $field = (null === $field) ? '' : $field.' ';\r
+            $operator = strtoupper($operator);\r
+            switch ($operator) {\r
+            // case insensitive\r
+            case 'ILIKE':\r
+                $match = $field.'ILIKE ';\r
+                break;\r
+            case 'NOT ILIKE':\r
+                $match = $field.'NOT ILIKE ';\r
+                break;\r
+            // case sensitive\r
+            case 'LIKE':\r
+                $match = $field.'LIKE ';\r
+                break;\r
+            case 'NOT LIKE':\r
+                $match = $field.'NOT LIKE ';\r
+                break;\r
+            default:\r
+                return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                    'not a supported operator type:'. $operator, __FUNCTION__);\r
+            }\r
+        }\r
+        $match.= "'";\r
+        foreach ($pattern as $key => $value) {\r
+            if ($key % 2) {\r
+                $match.= $value;\r
+            } else {\r
+                $match.= $db->escapePattern($db->escape($value));\r
+            }\r
+        }\r
+        $match.= "'";\r
+        $match.= $this->patternEscapeString();\r
+        return $match;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ patternEscapeString()\r
+\r
+    /**\r
+     * build string to define escape pattern string\r
+     *\r
+     * @access public\r
+     *\r
+     *\r
+     * @return string define escape pattern\r
+     */\r
+    function patternEscapeString()\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+        return ' ESCAPE '.$this->quote($db->string_quoting['escape_pattern']);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _mapNativeDatatype()\r
+\r
+    /**\r
+     * Maps a native array description of a field to a MDB2 datatype and length\r
+     *\r
+     * @param array  $field native field description\r
+     * @return array containing the various possible types, length, sign, fixed\r
+     * @access public\r
+     */\r
+    function _mapNativeDatatype($field)\r
+    {\r
+        $db_type = strtolower($field['type']);\r
+        $length = $field['length'];\r
+        $type = array();\r
+        $unsigned = $fixed = null;\r
+        switch ($db_type) {\r
+        case 'smallint':\r
+        case 'int2':\r
+            $type[] = 'integer';\r
+            $unsigned = false;\r
+            $length = 2;\r
+            if ($length == '2') {\r
+                $type[] = 'boolean';\r
+                if (preg_match('/^(is|has)/', $field['name'])) {\r
+                    $type = array_reverse($type);\r
+                }\r
+            }\r
+            break;\r
+        case 'int':\r
+        case 'int4':\r
+        case 'integer':\r
+        case 'serial':\r
+        case 'serial4':\r
+            $type[] = 'integer';\r
+            $unsigned = false;\r
+            $length = 4;\r
+            break;\r
+        case 'bigint':\r
+        case 'int8':\r
+        case 'bigserial':\r
+        case 'serial8':\r
+            $type[] = 'integer';\r
+            $unsigned = false;\r
+            $length = 8;\r
+            break;\r
+        case 'bool':\r
+        case 'boolean':\r
+            $type[] = 'boolean';\r
+            $length = null;\r
+            break;\r
+        case 'text':\r
+        case 'varchar':\r
+            $fixed = false;\r
+        case 'unknown':\r
+        case 'char':\r
+        case 'bpchar':\r
+            $type[] = 'text';\r
+            if ($length == '1') {\r
+                $type[] = 'boolean';\r
+                if (preg_match('/^(is|has)/', $field['name'])) {\r
+                    $type = array_reverse($type);\r
+                }\r
+            } elseif (strstr($db_type, 'text')) {\r
+                $type[] = 'clob';\r
+                $type = array_reverse($type);\r
+            }\r
+            if ($fixed !== false) {\r
+                $fixed = true;\r
+            }\r
+            break;\r
+        case 'date':\r
+            $type[] = 'date';\r
+            $length = null;\r
+            break;\r
+        case 'datetime':\r
+        case 'timestamp':\r
+        case 'timestamptz':\r
+            $type[] = 'timestamp';\r
+            $length = null;\r
+            break;\r
+        case 'time':\r
+            $type[] = 'time';\r
+            $length = null;\r
+            break;\r
+        case 'float':\r
+        case 'float4':\r
+        case 'float8':\r
+        case 'double':\r
+        case 'real':\r
+            $type[] = 'float';\r
+            break;\r
+        case 'decimal':\r
+        case 'money':\r
+        case 'numeric':\r
+            $type[] = 'decimal';\r
+            if (isset($field['scale'])) {\r
+                $length = $length.','.$field['scale'];\r
+            }\r
+            break;\r
+        case 'tinyblob':\r
+        case 'mediumblob':\r
+        case 'longblob':\r
+        case 'blob':\r
+        case 'bytea':\r
+            $type[] = 'blob';\r
+            $length = null;\r
+            break;\r
+        case 'oid':\r
+            $type[] = 'blob';\r
+            $type[] = 'clob';\r
+            $length = null;\r
+            break;\r
+        case 'year':\r
+            $type[] = 'integer';\r
+            $type[] = 'date';\r
+            $length = null;\r
+            break;\r
+        default:\r
+            $db = $this->getDBInstance();\r
+            if (PEAR::isError($db)) {\r
+                return $db;\r
+            }\r
+            return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'unknown database attribute type: '.$db_type, __FUNCTION__);\r
+        }\r
+\r
+        if ((int)$length <= 0) {\r
+            $length = null;\r
+        }\r
+\r
+        return array($type, $length, $unsigned, $fixed);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ mapPrepareDatatype()\r
+\r
+    /**\r
+     * Maps an mdb2 datatype to native prepare type\r
+     *\r
+     * @param string $type\r
+     * @return string\r
+     * @access public\r
+     */\r
+    function mapPrepareDatatype($type)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        if (!empty($db->options['datatype_map'][$type])) {\r
+            $type = $db->options['datatype_map'][$type];\r
+            if (!empty($db->options['datatype_map_callback'][$type])) {\r
+                $parameter = array('type' => $type);\r
+                return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));\r
+            }\r
+        }\r
+\r
+        switch ($type) {\r
+            case 'integer':\r
+                return 'int';\r
+            case 'boolean':\r
+                return 'bool';\r
+            case 'decimal':\r
+            case 'float':\r
+                return 'numeric';\r
+            case 'clob':\r
+                return 'text';\r
+            case 'blob':\r
+                return 'bytea';\r
+            default:\r
+                break;\r
+        }\r
+        return $type;\r
+    }\r
+    // }}}\r
+}\r
 ?>
\ No newline at end of file
index 9e57e7e56783eb99714274209e0d26f7e41203ed..e4711e46b32d4214de0301de80bcc8e71519d3b9 100644 (file)
-<?php
-// vim: set et ts=4 sw=4 fdm=marker:
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: sqlite.php,v 1.67 2008/02/22 19:58:06 quipo Exp $
-//
-
-require_once('MDB2/Driver/Datatype/Common.php');
-
-/**
- * MDB2 SQLite driver
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Datatype_sqlite extends MDB2_Driver_Datatype_Common
-{
-    // {{{ _getCollationFieldDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to set the COLLATION
-     * of a field declaration to be used in statements like CREATE TABLE.
-     *
-     * @param string $collation name of the collation
-     *
-     * @return string DBMS specific SQL code portion needed to set the COLLATION
-     *                of a field declaration.
-     */
-    function _getCollationFieldDeclaration($collation)
-    {
-        return 'COLLATE '.$collation;
-    }
-
-    // }}}
-    // {{{ getTypeDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare an text type
-     * field to be used in statements like CREATE TABLE.
-     *
-     * @param array $field  associative array with the name of the properties
-     *      of the field being declared as array indexes. Currently, the types
-     *      of supported field properties are as follows:
-     *
-     *      length
-     *          Integer value that determines the maximum length of the text
-     *          field. If this argument is missing the field should be
-     *          declared to have the longest length allowed by the DBMS.
-     *
-     *      default
-     *          Text value to be used as default for this field.
-     *
-     *      notnull
-     *          Boolean flag that indicates whether this field is constrained
-     *          to not be set to null.
-     * @return string  DBMS specific SQL code portion that should be used to
-     *      declare the specified field.
-     * @access public
-     */
-    function getTypeDeclaration($field)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        switch ($field['type']) {
-        case 'text':
-            $length = !empty($field['length'])
-                ? $field['length'] : false;
-            $fixed = !empty($field['fixed']) ? $field['fixed'] : false;
-            return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')')
-                : ($length ? 'VARCHAR('.$length.')' : 'TEXT');
-        case 'clob':
-            if (!empty($field['length'])) {
-                $length = $field['length'];
-                if ($length <= 255) {
-                    return 'TINYTEXT';
-                } elseif ($length <= 65532) {
-                    return 'TEXT';
-                } elseif ($length <= 16777215) {
-                    return 'MEDIUMTEXT';
-                }
-            }
-            return 'LONGTEXT';
-        case 'blob':
-            if (!empty($field['length'])) {
-                $length = $field['length'];
-                if ($length <= 255) {
-                    return 'TINYBLOB';
-                } elseif ($length <= 65532) {
-                    return 'BLOB';
-                } elseif ($length <= 16777215) {
-                    return 'MEDIUMBLOB';
-                }
-            }
-            return 'LONGBLOB';
-        case 'integer':
-            if (!empty($field['length'])) {
-                $length = $field['length'];
-                if ($length <= 2) {
-                    return 'SMALLINT';
-                } elseif ($length == 3 || $length == 4) {
-                    return 'INTEGER';
-                } elseif ($length > 4) {
-                    return 'BIGINT';
-                }
-            }
-            return 'INTEGER';
-        case 'boolean':
-            return 'BOOLEAN';
-        case 'date':
-            return 'DATE';
-        case 'time':
-            return 'TIME';
-        case 'timestamp':
-            return 'DATETIME';
-        case 'float':
-            return 'DOUBLE'.($db->options['fixed_float'] ? '('.
-                ($db->options['fixed_float']+2).','.$db->options['fixed_float'].')' : '');
-        case 'decimal':
-            $length = !empty($field['length']) ? $field['length'] : 18;
-            $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places'];
-            return 'DECIMAL('.$length.','.$scale.')';
-        }
-        return '';
-    }
-
-    // }}}
-    // {{{ _getIntegerDeclaration()
-
-    /**
-     * Obtain DBMS specific SQL code portion needed to declare an integer type
-     * field to be used in statements like CREATE TABLE.
-     *
-     * @param string  $name   name the field to be declared.
-     * @param string  $field  associative array with the name of the properties
-     *                        of the field being declared as array indexes.
-     *                        Currently, the types of supported field
-     *                        properties are as follows:
-     *
-     *                       unsigned
-     *                        Boolean flag that indicates whether the field
-     *                        should be declared as unsigned integer if
-     *                        possible.
-     *
-     *                       default
-     *                        Integer value to be used as default for this
-     *                        field.
-     *
-     *                       notnull
-     *                        Boolean flag that indicates whether this field is
-     *                        constrained to not be set to null.
-     * @return string  DBMS specific SQL code portion that should be used to
-     *                 declare the specified field.
-     * @access protected
-     */
-    function _getIntegerDeclaration($name, $field)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $default = $autoinc = '';
-        if (!empty($field['autoincrement'])) {
-            $autoinc = ' PRIMARY KEY';
-        } elseif (array_key_exists('default', $field)) {
-            if ($field['default'] === '') {
-                $field['default'] = empty($field['notnull']) ? null : 0;
-            }
-            $default = ' DEFAULT '.$this->quote($field['default'], 'integer');
-        }
-
-        $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
-        $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED';
-        $name = $db->quoteIdentifier($name, true);
-        return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull.$autoinc;
-    }
-
-    // }}}
-    // {{{ matchPattern()
-
-    /**
-     * build a pattern matching string
-     *
-     * @access public
-     *
-     * @param array $pattern even keys are strings, odd are patterns (% and _)
-     * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)
-     * @param string $field optional field name that is being matched against
-     *                  (might be required when emulating ILIKE)
-     *
-     * @return string SQL pattern
-     */
-    function matchPattern($pattern, $operator = null, $field = null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $match = '';
-        if (!is_null($operator)) {
-            $field = is_null($field) ? '' : $field.' ';
-            $operator = strtoupper($operator);
-            switch ($operator) {
-            // case insensitive
-            case 'ILIKE':
-                $match = $field.'LIKE ';
-                break;
-            // case sensitive
-            case 'LIKE':
-                $match = $field.'LIKE ';
-                break;
-            default:
-                return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                    'not a supported operator type:'. $operator, __FUNCTION__);
-            }
-        }
-        $match.= "'";
-        foreach ($pattern as $key => $value) {
-            if ($key % 2) {
-                $match.= $value;
-            } else {
-                $match.= $db->escapePattern($db->escape($value));
-            }
-        }
-        $match.= "'";
-        $match.= $this->patternEscapeString();
-        return $match;
-    }
-
-    // }}}
-    // {{{ _mapNativeDatatype()
-
-    /**
-     * Maps a native array description of a field to a MDB2 datatype and length
-     *
-     * @param array  $field native field description
-     * @return array containing the various possible types, length, sign, fixed
-     * @access public
-     */
-    function _mapNativeDatatype($field)
-    {
-        $db_type = strtolower($field['type']);
-        $length = !empty($field['length']) ? $field['length'] : null;
-        $unsigned = !empty($field['unsigned']) ? $field['unsigned'] : null;
-        $fixed = null;
-        $type = array();
-        switch ($db_type) {
-        case 'boolean':
-            $type[] = 'boolean';
-            break;
-        case 'tinyint':
-            $type[] = 'integer';
-            $type[] = 'boolean';
-            if (preg_match('/^(is|has)/', $field['name'])) {
-                $type = array_reverse($type);
-            }
-            $unsigned = preg_match('/ unsigned/i', $field['type']);
-            $length = 1;
-            break;
-        case 'smallint':
-            $type[] = 'integer';
-            $unsigned = preg_match('/ unsigned/i', $field['type']);
-            $length = 2;
-            break;
-        case 'mediumint':
-            $type[] = 'integer';
-            $unsigned = preg_match('/ unsigned/i', $field['type']);
-            $length = 3;
-            break;
-        case 'int':
-        case 'integer':
-        case 'serial':
-            $type[] = 'integer';
-            $unsigned = preg_match('/ unsigned/i', $field['type']);
-            $length = 4;
-            break;
-        case 'bigint':
-        case 'bigserial':
-            $type[] = 'integer';
-            $unsigned = preg_match('/ unsigned/i', $field['type']);
-            $length = 8;
-            break;
-        case 'clob':
-            $type[] = 'clob';
-            $fixed  = false;
-            break;
-        case 'tinytext':
-        case 'mediumtext':
-        case 'longtext':
-        case 'text':
-        case 'varchar':
-        case 'varchar2':
-            $fixed = false;
-        case 'char':
-            $type[] = 'text';
-            if ($length == '1') {
-                $type[] = 'boolean';
-                if (preg_match('/^(is|has)/', $field['name'])) {
-                    $type = array_reverse($type);
-                }
-            } elseif (strstr($db_type, 'text')) {
-                $type[] = 'clob';
-                $type = array_reverse($type);
-            }
-            if ($fixed !== false) {
-                $fixed = true;
-            }
-            break;
-        case 'date':
-            $type[] = 'date';
-            $length = null;
-            break;
-        case 'datetime':
-        case 'timestamp':
-            $type[] = 'timestamp';
-            $length = null;
-            break;
-        case 'time':
-            $type[] = 'time';
-            $length = null;
-            break;
-        case 'float':
-        case 'double':
-        case 'real':
-            $type[] = 'float';
-            break;
-        case 'decimal':
-        case 'numeric':
-            $type[] = 'decimal';
-            $length = $length.','.$field['decimal'];
-            break;
-        case 'tinyblob':
-        case 'mediumblob':
-        case 'longblob':
-        case 'blob':
-            $type[] = 'blob';
-            $length = null;
-            break;
-        case 'year':
-            $type[] = 'integer';
-            $type[] = 'date';
-            $length = null;
-            break;
-        default:
-            $db =$this->getDBInstance();
-            if (PEAR::isError($db)) {
-                return $db;
-            }
-            return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'unknown database attribute type: '.$db_type, __FUNCTION__);
-        }
-
-        if ((int)$length <= 0) {
-            $length = null;
-        }
-
-        return array($type, $length, $unsigned, $fixed);
-    }
-
-    // }}}
-}
-
+<?php\r
+// vim: set et ts=4 sw=4 fdm=marker:\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: sqlite.php 295587 2010-02-28 17:16:38Z quipo $\r
+//\r
+\r
+require_once 'MDB2/Driver/Datatype/Common.php';\r
+\r
+/**\r
+ * MDB2 SQLite driver\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Driver_Datatype_sqlite extends MDB2_Driver_Datatype_Common\r
+{\r
+    // {{{ _getCollationFieldDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to set the COLLATION\r
+     * of a field declaration to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string $collation name of the collation\r
+     *\r
+     * @return string DBMS specific SQL code portion needed to set the COLLATION\r
+     *                of a field declaration.\r
+     */\r
+    function _getCollationFieldDeclaration($collation)\r
+    {\r
+        return 'COLLATE '.$collation;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getTypeDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare an text type\r
+     * field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param array $field  associative array with the name of the properties\r
+     *      of the field being declared as array indexes. Currently, the types\r
+     *      of supported field properties are as follows:\r
+     *\r
+     *      length\r
+     *          Integer value that determines the maximum length of the text\r
+     *          field. If this argument is missing the field should be\r
+     *          declared to have the longest length allowed by the DBMS.\r
+     *\r
+     *      default\r
+     *          Text value to be used as default for this field.\r
+     *\r
+     *      notnull\r
+     *          Boolean flag that indicates whether this field is constrained\r
+     *          to not be set to null.\r
+     * @return string  DBMS specific SQL code portion that should be used to\r
+     *      declare the specified field.\r
+     * @access public\r
+     */\r
+    function getTypeDeclaration($field)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        switch ($field['type']) {\r
+        case 'text':\r
+            $length = !empty($field['length'])\r
+                ? $field['length'] : false;\r
+            $fixed = !empty($field['fixed']) ? $field['fixed'] : false;\r
+            return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')')\r
+                : ($length ? 'VARCHAR('.$length.')' : 'TEXT');\r
+        case 'clob':\r
+            if (!empty($field['length'])) {\r
+                $length = $field['length'];\r
+                if ($length <= 255) {\r
+                    return 'TINYTEXT';\r
+                } elseif ($length <= 65532) {\r
+                    return 'TEXT';\r
+                } elseif ($length <= 16777215) {\r
+                    return 'MEDIUMTEXT';\r
+                }\r
+            }\r
+            return 'LONGTEXT';\r
+        case 'blob':\r
+            if (!empty($field['length'])) {\r
+                $length = $field['length'];\r
+                if ($length <= 255) {\r
+                    return 'TINYBLOB';\r
+                } elseif ($length <= 65532) {\r
+                    return 'BLOB';\r
+                } elseif ($length <= 16777215) {\r
+                    return 'MEDIUMBLOB';\r
+                }\r
+            }\r
+            return 'LONGBLOB';\r
+        case 'integer':\r
+            if (!empty($field['length'])) {\r
+                $length = $field['length'];\r
+                if ($length <= 2) {\r
+                    return 'SMALLINT';\r
+                } elseif ($length == 3 || $length == 4) {\r
+                    return 'INTEGER';\r
+                } elseif ($length > 4) {\r
+                    return 'BIGINT';\r
+                }\r
+            }\r
+            return 'INTEGER';\r
+        case 'boolean':\r
+            return 'BOOLEAN';\r
+        case 'date':\r
+            return 'DATE';\r
+        case 'time':\r
+            return 'TIME';\r
+        case 'timestamp':\r
+            return 'DATETIME';\r
+        case 'float':\r
+            return 'DOUBLE'.($db->options['fixed_float'] ? '('.\r
+                ($db->options['fixed_float']+2).','.$db->options['fixed_float'].')' : '');\r
+        case 'decimal':\r
+            $length = !empty($field['length']) ? $field['length'] : 18;\r
+            $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places'];\r
+            return 'DECIMAL('.$length.','.$scale.')';\r
+        }\r
+        return '';\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getIntegerDeclaration()\r
+\r
+    /**\r
+     * Obtain DBMS specific SQL code portion needed to declare an integer type\r
+     * field to be used in statements like CREATE TABLE.\r
+     *\r
+     * @param string  $name   name the field to be declared.\r
+     * @param string  $field  associative array with the name of the properties\r
+     *                        of the field being declared as array indexes.\r
+     *                        Currently, the types of supported field\r
+     *                        properties are as follows:\r
+     *\r
+     *                       unsigned\r
+     *                        Boolean flag that indicates whether the field\r
+     *                        should be declared as unsigned integer if\r
+     *                        possible.\r
+     *\r
+     *                       default\r
+     *                        Integer value to be used as default for this\r
+     *                        field.\r
+     *\r
+     *                       notnull\r
+     *                        Boolean flag that indicates whether this field is\r
+     *                        constrained to not be set to null.\r
+     * @return string  DBMS specific SQL code portion that should be used to\r
+     *                 declare the specified field.\r
+     * @access protected\r
+     */\r
+    function _getIntegerDeclaration($name, $field)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $default = $autoinc = '';\r
+        if (!empty($field['autoincrement'])) {\r
+            $autoinc = ' PRIMARY KEY';\r
+        } elseif (array_key_exists('default', $field)) {\r
+            if ($field['default'] === '') {\r
+                $field['default'] = empty($field['notnull']) ? null : 0;\r
+            }\r
+            $default = ' DEFAULT '.$this->quote($field['default'], 'integer');\r
+        }\r
+\r
+        $notnull = empty($field['notnull']) ? '' : ' NOT NULL';\r
+        $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED';\r
+        if (empty($default) && empty($notnull)) {\r
+            $default = ' DEFAULT NULL';\r
+        }\r
+        $name = $db->quoteIdentifier($name, true);\r
+        return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull.$autoinc;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ matchPattern()\r
+\r
+    /**\r
+     * build a pattern matching string\r
+     *\r
+     * @access public\r
+     *\r
+     * @param array $pattern even keys are strings, odd are patterns (% and _)\r
+     * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)\r
+     * @param string $field optional field name that is being matched against\r
+     *                  (might be required when emulating ILIKE)\r
+     *\r
+     * @return string SQL pattern\r
+     */\r
+    function matchPattern($pattern, $operator = null, $field = null)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $match = '';\r
+        if (null !== $operator) {\r
+            $field = (null === $field) ? '' : $field.' ';\r
+            $operator = strtoupper($operator);\r
+            switch ($operator) {\r
+            // case insensitive\r
+            case 'ILIKE':\r
+                $match = $field.'LIKE ';\r
+                break;\r
+            case 'NOT ILIKE':\r
+                $match = $field.'NOT LIKE ';\r
+                break;\r
+            // case sensitive\r
+            case 'LIKE':\r
+                $match = $field.'LIKE ';\r
+                break;\r
+            case 'NOT LIKE':\r
+                $match = $field.'NOT LIKE ';\r
+                break;\r
+            default:\r
+                return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                    'not a supported operator type:'. $operator, __FUNCTION__);\r
+            }\r
+        }\r
+        $match.= "'";\r
+        foreach ($pattern as $key => $value) {\r
+            if ($key % 2) {\r
+                $match.= $value;\r
+            } else {\r
+                $match.= $db->escapePattern($db->escape($value));\r
+            }\r
+        }\r
+        $match.= "'";\r
+        $match.= $this->patternEscapeString();\r
+        return $match;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _mapNativeDatatype()\r
+\r
+    /**\r
+     * Maps a native array description of a field to a MDB2 datatype and length\r
+     *\r
+     * @param array  $field native field description\r
+     * @return array containing the various possible types, length, sign, fixed\r
+     * @access public\r
+     */\r
+    function _mapNativeDatatype($field)\r
+    {\r
+        $db_type = strtolower($field['type']);\r
+        $length = !empty($field['length']) ? $field['length'] : null;\r
+        $unsigned = !empty($field['unsigned']) ? $field['unsigned'] : null;\r
+        $fixed = null;\r
+        $type = array();\r
+        switch ($db_type) {\r
+        case 'boolean':\r
+            $type[] = 'boolean';\r
+            break;\r
+        case 'tinyint':\r
+            $type[] = 'integer';\r
+            $type[] = 'boolean';\r
+            if (preg_match('/^(is|has)/', $field['name'])) {\r
+                $type = array_reverse($type);\r
+            }\r
+            $unsigned = preg_match('/ unsigned/i', $field['type']);\r
+            $length = 1;\r
+            break;\r
+        case 'smallint':\r
+            $type[] = 'integer';\r
+            $unsigned = preg_match('/ unsigned/i', $field['type']);\r
+            $length = 2;\r
+            break;\r
+        case 'mediumint':\r
+            $type[] = 'integer';\r
+            $unsigned = preg_match('/ unsigned/i', $field['type']);\r
+            $length = 3;\r
+            break;\r
+        case 'int':\r
+        case 'integer':\r
+        case 'serial':\r
+            $type[] = 'integer';\r
+            $unsigned = preg_match('/ unsigned/i', $field['type']);\r
+            $length = 4;\r
+            break;\r
+        case 'bigint':\r
+        case 'bigserial':\r
+            $type[] = 'integer';\r
+            $unsigned = preg_match('/ unsigned/i', $field['type']);\r
+            $length = 8;\r
+            break;\r
+        case 'clob':\r
+            $type[] = 'clob';\r
+            $fixed  = false;\r
+            break;\r
+        case 'tinytext':\r
+        case 'mediumtext':\r
+        case 'longtext':\r
+        case 'text':\r
+        case 'varchar':\r
+        case 'varchar2':\r
+            $fixed = false;\r
+        case 'char':\r
+            $type[] = 'text';\r
+            if ($length == '1') {\r
+                $type[] = 'boolean';\r
+                if (preg_match('/^(is|has)/', $field['name'])) {\r
+                    $type = array_reverse($type);\r
+                }\r
+            } elseif (strstr($db_type, 'text')) {\r
+                $type[] = 'clob';\r
+                $type = array_reverse($type);\r
+            }\r
+            if ($fixed !== false) {\r
+                $fixed = true;\r
+            }\r
+            break;\r
+        case 'date':\r
+            $type[] = 'date';\r
+            $length = null;\r
+            break;\r
+        case 'datetime':\r
+        case 'timestamp':\r
+            $type[] = 'timestamp';\r
+            $length = null;\r
+            break;\r
+        case 'time':\r
+            $type[] = 'time';\r
+            $length = null;\r
+            break;\r
+        case 'float':\r
+        case 'double':\r
+        case 'real':\r
+            $type[] = 'float';\r
+            break;\r
+        case 'decimal':\r
+        case 'numeric':\r
+            $type[] = 'decimal';\r
+            $length = $length.','.$field['decimal'];\r
+            break;\r
+        case 'tinyblob':\r
+        case 'mediumblob':\r
+        case 'longblob':\r
+        case 'blob':\r
+            $type[] = 'blob';\r
+            $length = null;\r
+            break;\r
+        case 'year':\r
+            $type[] = 'integer';\r
+            $type[] = 'date';\r
+            $length = null;\r
+            break;\r
+        default:\r
+            $db = $this->getDBInstance();\r
+            if (PEAR::isError($db)) {\r
+                return $db;\r
+            }\r
+            return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'unknown database attribute type: '.$db_type, __FUNCTION__);\r
+        }\r
+\r
+        if ((int)$length <= 0) {\r
+            $length = null;\r
+        }\r
+\r
+        return array($type, $length, $unsigned, $fixed);\r
+    }\r
+\r
+    // }}}\r
+}\r
+\r
 ?>
\ No newline at end of file
index 731f06882ce52a603f1a7bd7ecef5b7c8c23a6f4..5d247bec3599ea09e9095c5c38e7b1e4f194f38f 100644 (file)
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: Common.php,v 1.21 2008/02/17 18:51:39 quipo Exp $
-//
-
-/**
- * @package  MDB2
- * @category Database
- * @author   Lukas Smith <smith@pooteeweet.org>
- */
-
-/**
- * Base class for the function modules that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Function');
- *
- * @package  MDB2
- * @category Database
- * @author   Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Function_Common extends MDB2_Module_Common
-{
-    // {{{ executeStoredProc()
-
-    /**
-     * Execute a stored procedure and return any results
-     *
-     * @param string $name string that identifies the function to execute
-     * @param mixed  $params  array that contains the paramaters to pass the stored proc
-     * @param mixed   $types  array that contains the types of the columns in
-     *                        the result set
-     * @param mixed $result_class string which specifies which result class to use
-     * @param mixed $result_wrap_class string which specifies which class to wrap results in
-     *
-     * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function &executeStoredProc($name, $params = null, $types = null, $result_class = true, $result_wrap_class = false)
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $error =& $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-        return $error;
-    }
-
-    // }}}
-    // {{{ functionTable()
-
-    /**
-     * return string for internal table used when calling only a function
-     *
-     * @return string for internal table used when calling only a function
-     * @access public
-     */
-    function functionTable()
-    {
-        return '';
-    }
-
-    // }}}
-    // {{{ now()
-
-    /**
-     * Return string to call a variable with the current timestamp inside an SQL statement
-     * There are three special variables for current date and time:
-     * - CURRENT_TIMESTAMP (date and time, TIMESTAMP type)
-     * - CURRENT_DATE (date, DATE type)
-     * - CURRENT_TIME (time, TIME type)
-     *
-     * @param string $type 'timestamp' | 'time' | 'date'
-     *
-     * @return string to call a variable with the current timestamp
-     * @access public
-     */
-    function now($type = 'timestamp')
-    {
-        switch ($type) {
-        case 'time':
-            return 'CURRENT_TIME';
-        case 'date':
-            return 'CURRENT_DATE';
-        case 'timestamp':
-        default:
-            return 'CURRENT_TIMESTAMP';
-        }
-    }
-
-    // }}}
-    // {{{ unixtimestamp()
-
-    /**
-     * return string to call a function to get the unix timestamp from a iso timestamp
-     *
-     * @param string $expression
-     *
-     * @return string to call a variable with the timestamp
-     * @access public
-     */
-    function unixtimestamp($expression)
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $error =& $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-        return $error;
-    }
-
-    // }}}
-    // {{{ substring()
-
-    /**
-     * return string to call a function to get a substring inside an SQL statement
-     *
-     * @return string to call a function to get a substring
-     * @access public
-     */
-    function substring($value, $position = 1, $length = null)
-    {
-        if (!is_null($length)) {
-            return "SUBSTRING($value FROM $position FOR $length)";
-        }
-        return "SUBSTRING($value FROM $position)";
-    }
-
-    // }}}
-    // {{{ replace()
-
-    /**
-     * return string to call a function to get replace inside an SQL statement.
-     *
-     * @return string to call a function to get a replace
-     * @access public
-     */
-    function replace($str, $from_str, $to_str)
-    {
-        return "REPLACE($str, $from_str , $to_str)";
-    }
-
-    // }}}
-    // {{{ concat()
-
-    /**
-     * Returns string to concatenate two or more string parameters
-     *
-     * @param string $value1
-     * @param string $value2
-     * @param string $values...
-     *
-     * @return string to concatenate two strings
-     * @access public
-     */
-    function concat($value1, $value2)
-    {
-        $args = func_get_args();
-        return "(".implode(' || ', $args).")";
-    }
-
-    // }}}
-    // {{{ random()
-
-    /**
-     * return string to call a function to get random value inside an SQL statement
-     *
-     * @return return string to generate float between 0 and 1
-     * @access public
-     */
-    function random()
-    {
-        return 'RAND()';
-    }
-
-    // }}}
-    // {{{ lower()
-
-    /**
-     * return string to call a function to lower the case of an expression
-     *
-     * @param string $expression
-     *
-     * @return return string to lower case of an expression
-     * @access public
-     */
-    function lower($expression)
-    {
-        return "LOWER($expression)";
-    }
-
-    // }}}
-    // {{{ upper()
-
-    /**
-     * return string to call a function to upper the case of an expression
-     *
-     * @param string $expression
-     *
-     * @return return string to upper case of an expression
-     * @access public
-     */
-    function upper($expression)
-    {
-        return "UPPER($expression)";
-    }
-
-    // }}}
-    // {{{ length()
-
-    /**
-     * return string to call a function to get the length of a string expression
-     *
-     * @param string $expression
-     *
-     * @return return string to get the string expression length
-     * @access public
-     */
-    function length($expression)
-    {
-        return "LENGTH($expression)";
-    }
-
-    // }}}
-    // {{{ guid()
-
-    /**
-     * Returns global unique identifier
-     *
-     * @return string to get global unique identifier
-     * @access public
-     */
-    function guid()
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $error =& $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-        return $error;
-    }
-
-    // }}}
-}
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: Common.php 295587 2010-02-28 17:16:38Z quipo $\r
+//\r
+\r
+/**\r
+ * @package  MDB2\r
+ * @category Database\r
+ * @author   Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+\r
+/**\r
+ * Base class for the function modules that is extended by each MDB2 driver\r
+ *\r
+ * To load this module in the MDB2 object:\r
+ * $mdb->loadModule('Function');\r
+ *\r
+ * @package  MDB2\r
+ * @category Database\r
+ * @author   Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Driver_Function_Common extends MDB2_Module_Common\r
+{\r
+    // {{{ executeStoredProc()\r
+\r
+    /**\r
+     * Execute a stored procedure and return any results\r
+     *\r
+     * @param string $name string that identifies the function to execute\r
+     * @param mixed  $params  array that contains the paramaters to pass the stored proc\r
+     * @param mixed   $types  array that contains the types of the columns in\r
+     *                        the result set\r
+     * @param mixed $result_class string which specifies which result class to use\r
+     * @param mixed $result_wrap_class string which specifies which class to wrap results in\r
+     *\r
+     * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function executeStoredProc($name, $params = null, $types = null, $result_class = true, $result_wrap_class = false)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $error = $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+        return $error;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ functionTable()\r
+\r
+    /**\r
+     * return string for internal table used when calling only a function\r
+     *\r
+     * @return string for internal table used when calling only a function\r
+     * @access public\r
+     */\r
+    function functionTable()\r
+    {\r
+        return '';\r
+    }\r
+\r
+    // }}}\r
+    // {{{ now()\r
+\r
+    /**\r
+     * Return string to call a variable with the current timestamp inside an SQL statement\r
+     * There are three special variables for current date and time:\r
+     * - CURRENT_TIMESTAMP (date and time, TIMESTAMP type)\r
+     * - CURRENT_DATE (date, DATE type)\r
+     * - CURRENT_TIME (time, TIME type)\r
+     *\r
+     * @param string $type 'timestamp' | 'time' | 'date'\r
+     *\r
+     * @return string to call a variable with the current timestamp\r
+     * @access public\r
+     */\r
+    function now($type = 'timestamp')\r
+    {\r
+        switch ($type) {\r
+        case 'time':\r
+            return 'CURRENT_TIME';\r
+        case 'date':\r
+            return 'CURRENT_DATE';\r
+        case 'timestamp':\r
+        default:\r
+            return 'CURRENT_TIMESTAMP';\r
+        }\r
+    }\r
+\r
+    // }}}\r
+    // {{{ unixtimestamp()\r
+\r
+    /**\r
+     * return string to call a function to get the unix timestamp from a iso timestamp\r
+     *\r
+     * @param string $expression\r
+     *\r
+     * @return string to call a variable with the timestamp\r
+     * @access public\r
+     */\r
+    function unixtimestamp($expression)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $error = $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+        return $error;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ substring()\r
+\r
+    /**\r
+     * return string to call a function to get a substring inside an SQL statement\r
+     *\r
+     * @return string to call a function to get a substring\r
+     * @access public\r
+     */\r
+    function substring($value, $position = 1, $length = null)\r
+    {\r
+        if (null !== $length) {\r
+            return "SUBSTRING($value FROM $position FOR $length)";\r
+        }\r
+        return "SUBSTRING($value FROM $position)";\r
+    }\r
+\r
+    // }}}\r
+    // {{{ replace()\r
+\r
+    /**\r
+     * return string to call a function to get replace inside an SQL statement.\r
+     *\r
+     * @return string to call a function to get a replace\r
+     * @access public\r
+     */\r
+    function replace($str, $from_str, $to_str)\r
+    {\r
+        return "REPLACE($str, $from_str , $to_str)";\r
+    }\r
+\r
+    // }}}\r
+    // {{{ concat()\r
+\r
+    /**\r
+     * Returns string to concatenate two or more string parameters\r
+     *\r
+     * @param string $value1\r
+     * @param string $value2\r
+     * @param string $values...\r
+     *\r
+     * @return string to concatenate two strings\r
+     * @access public\r
+     */\r
+    function concat($value1, $value2)\r
+    {\r
+        $args = func_get_args();\r
+        return "(".implode(' || ', $args).")";\r
+    }\r
+\r
+    // }}}\r
+    // {{{ random()\r
+\r
+    /**\r
+     * return string to call a function to get random value inside an SQL statement\r
+     *\r
+     * @return return string to generate float between 0 and 1\r
+     * @access public\r
+     */\r
+    function random()\r
+    {\r
+        return 'RAND()';\r
+    }\r
+\r
+    // }}}\r
+    // {{{ lower()\r
+\r
+    /**\r
+     * return string to call a function to lower the case of an expression\r
+     *\r
+     * @param string $expression\r
+     *\r
+     * @return return string to lower case of an expression\r
+     * @access public\r
+     */\r
+    function lower($expression)\r
+    {\r
+        return "LOWER($expression)";\r
+    }\r
+\r
+    // }}}\r
+    // {{{ upper()\r
+\r
+    /**\r
+     * return string to call a function to upper the case of an expression\r
+     *\r
+     * @param string $expression\r
+     *\r
+     * @return return string to upper case of an expression\r
+     * @access public\r
+     */\r
+    function upper($expression)\r
+    {\r
+        return "UPPER($expression)";\r
+    }\r
+\r
+    // }}}\r
+    // {{{ length()\r
+\r
+    /**\r
+     * return string to call a function to get the length of a string expression\r
+     *\r
+     * @param string $expression\r
+     *\r
+     * @return return string to get the string expression length\r
+     * @access public\r
+     */\r
+    function length($expression)\r
+    {\r
+        return "LENGTH($expression)";\r
+    }\r
+\r
+    // }}}\r
+    // {{{ guid()\r
+\r
+    /**\r
+     * Returns global unique identifier\r
+     *\r
+     * @return string to get global unique identifier\r
+     * @access public\r
+     */\r
+    function guid()\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $error = $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+        return $error;\r
+    }\r
+\r
+    // }}}\r
+}\r
 ?>
\ No newline at end of file
index 44183c3aa0674baf7f7b50f2f246cb571335bb3f..bf91536e1f39a1289b739d56c23bc26cbc4be4de 100644 (file)
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: mysql.php,v 1.12 2008/02/17 18:54:08 quipo Exp $
-//
-
-require_once('MDB2/Driver/Function/Common.php');
-
-/**
- * MDB2 MySQL driver for the function modules
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Function_mysql extends MDB2_Driver_Function_Common
-{
-     // }}}
-    // {{{ executeStoredProc()
-
-    /**
-     * Execute a stored procedure and return any results
-     *
-     * @param string $name string that identifies the function to execute
-     * @param mixed  $params  array that contains the paramaters to pass the stored proc
-     * @param mixed   $types  array that contains the types of the columns in
-     *                        the result set
-     * @param mixed $result_class string which specifies which result class to use
-     * @param mixed $result_wrap_class string which specifies which class to wrap results in
-     * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function &executeStoredProc($name, $params = null, $types = null, $result_class = true, $result_wrap_class = false)
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = 'CALL '.$name;
-        $query .= $params ? '('.implode(', ', $params).')' : '()';
-        return $db->query($query, $types, $result_class, $result_wrap_class);
-    }
-
-    // }}}
-    // {{{ unixtimestamp()
-
-    /**
-     * return string to call a function to get the unix timestamp from a iso timestamp
-     *
-     * @param string $expression
-     *
-     * @return string to call a variable with the timestamp
-     * @access public
-     */
-    function unixtimestamp($expression)
-    {
-        return 'UNIX_TIMESTAMP('. $expression.')';
-    }
-
-    // }}}
-    // {{{ concat()
-
-    /**
-     * Returns string to concatenate two or more string parameters
-     *
-     * @param string $value1
-     * @param string $value2
-     * @param string $values...
-     * @return string to concatenate two strings
-     * @access public
-     **/
-    function concat($value1, $value2)
-    {
-        $args = func_get_args();
-        return "CONCAT(".implode(', ', $args).")";
-    }
-
-    // }}}
-    // {{{ guid()
-
-    /**
-     * Returns global unique identifier
-     *
-     * @return string to get global unique identifier
-     * @access public
-     */
-    function guid()
-    {
-        return 'UUID()';
-    }
-
-    // }}}
-}
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: mysql.php 295587 2010-02-28 17:16:38Z quipo $\r
+//\r
+\r
+require_once 'MDB2/Driver/Function/Common.php';\r
+\r
+/**\r
+ * MDB2 MySQL driver for the function modules\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Driver_Function_mysql extends MDB2_Driver_Function_Common\r
+{\r
+     // }}}\r
+    // {{{ executeStoredProc()\r
+\r
+    /**\r
+     * Execute a stored procedure and return any results\r
+     *\r
+     * @param string $name string that identifies the function to execute\r
+     * @param mixed  $params  array that contains the paramaters to pass the stored proc\r
+     * @param mixed   $types  array that contains the types of the columns in\r
+     *                        the result set\r
+     * @param mixed $result_class string which specifies which result class to use\r
+     * @param mixed $result_wrap_class string which specifies which class to wrap results in\r
+     * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function executeStoredProc($name, $params = null, $types = null, $result_class = true, $result_wrap_class = false)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = 'CALL '.$name;\r
+        $query .= $params ? '('.implode(', ', $params).')' : '()';\r
+        return $db->query($query, $types, $result_class, $result_wrap_class);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ unixtimestamp()\r
+\r
+    /**\r
+     * return string to call a function to get the unix timestamp from a iso timestamp\r
+     *\r
+     * @param string $expression\r
+     *\r
+     * @return string to call a variable with the timestamp\r
+     * @access public\r
+     */\r
+    function unixtimestamp($expression)\r
+    {\r
+        return 'UNIX_TIMESTAMP('. $expression.')';\r
+    }\r
+\r
+    // }}}\r
+    // {{{ concat()\r
+\r
+    /**\r
+     * Returns string to concatenate two or more string parameters\r
+     *\r
+     * @param string $value1\r
+     * @param string $value2\r
+     * @param string $values...\r
+     * @return string to concatenate two strings\r
+     * @access public\r
+     **/\r
+    function concat($value1, $value2)\r
+    {\r
+        $args = func_get_args();\r
+        return "CONCAT(".implode(', ', $args).")";\r
+    }\r
+\r
+    // }}}\r
+    // {{{ guid()\r
+\r
+    /**\r
+     * Returns global unique identifier\r
+     *\r
+     * @return string to get global unique identifier\r
+     * @access public\r
+     */\r
+    function guid()\r
+    {\r
+        return 'UUID()';\r
+    }\r
+\r
+    // }}}\r
+}\r
 ?>
\ No newline at end of file
index 173bfc9149473d57b3641d1ea134b5bc0f4eda68..e232e4feec15108e9f45187f2299b77c2223573c 100644 (file)
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Paul Cooper <pgc@ucecom.com>                                 |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.11 2008/11/09 19:46:50 quipo Exp $
-
-require_once('MDB2/Driver/Function/Common.php');
-
-/**
- * MDB2 MySQL driver for the function modules
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Function_pgsql extends MDB2_Driver_Function_Common
-{
-    // {{{ executeStoredProc()
-
-    /**
-     * Execute a stored procedure and return any results
-     *
-     * @param string $name string that identifies the function to execute
-     * @param mixed  $params  array that contains the paramaters to pass the stored proc
-     * @param mixed   $types  array that contains the types of the columns in
-     *                        the result set
-     * @param mixed $result_class string which specifies which result class to use
-     * @param mixed $result_wrap_class string which specifies which class to wrap results in
-     * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function &executeStoredProc($name, $params = null, $types = null, $result_class = true, $result_wrap_class = false)
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = 'SELECT * FROM '.$name;
-        $query .= $params ? '('.implode(', ', $params).')' : '()';
-        return $db->query($query, $types, $result_class, $result_wrap_class);
-    }
-    // }}}
-    // {{{ unixtimestamp()
-
-    /**
-     * return string to call a function to get the unix timestamp from a iso timestamp
-     *
-     * @param string $expression
-     *
-     * @return string to call a variable with the timestamp
-     * @access public
-     */
-    function unixtimestamp($expression)
-    {
-        return 'EXTRACT(EPOCH FROM DATE_TRUNC(\'seconds\', CAST ((' . $expression . ') AS TIMESTAMP)))';
-    }
-
-    // }}}
-    // {{{ random()
-
-    /**
-     * return string to call a function to get random value inside an SQL statement
-     *
-     * @return return string to generate float between 0 and 1
-     * @access public
-     */
-    function random()
-    {
-        return 'RANDOM()';
-    }
-
-    // }}}
-}
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Paul Cooper <pgc@ucecom.com>                                 |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: pgsql.php 296139 2010-03-13 04:15:22Z afz $\r
+\r
+require_once 'MDB2/Driver/Function/Common.php';\r
+\r
+/**\r
+ * MDB2 MySQL driver for the function modules\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Driver_Function_pgsql extends MDB2_Driver_Function_Common\r
+{\r
+    // {{{ executeStoredProc()\r
+\r
+    /**\r
+     * Execute a stored procedure and return any results\r
+     *\r
+     * @param string $name string that identifies the function to execute\r
+     * @param mixed  $params  array that contains the paramaters to pass the stored proc\r
+     * @param mixed   $types  array that contains the types of the columns in\r
+     *                        the result set\r
+     * @param mixed $result_class string which specifies which result class to use\r
+     * @param mixed $result_wrap_class string which specifies which class to wrap results in\r
+     * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function executeStoredProc($name, $params = null, $types = null, $result_class = true, $result_wrap_class = false)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = 'SELECT * FROM '.$name;\r
+        $query .= $params ? '('.implode(', ', $params).')' : '()';\r
+        return $db->query($query, $types, $result_class, $result_wrap_class);\r
+    }\r
+    // }}}\r
+    // {{{ unixtimestamp()\r
+\r
+    /**\r
+     * return string to call a function to get the unix timestamp from a iso timestamp\r
+     *\r
+     * @param string $expression\r
+     *\r
+     * @return string to call a variable with the timestamp\r
+     * @access public\r
+     */\r
+    function unixtimestamp($expression)\r
+    {\r
+        return 'EXTRACT(EPOCH FROM DATE_TRUNC(\'seconds\', CAST ((' . $expression . ') AS TIMESTAMP)))';\r
+    }\r
+\r
+    // }}}\r
+    // {{{ substring()\r
+\r
+    /**\r
+     * return string to call a function to get a substring inside an SQL statement\r
+     *\r
+     * @return string to call a function to get a substring\r
+     * @access public\r
+     */\r
+    function substring($value, $position = 1, $length = null)\r
+    {\r
+        if (null !== $length) {\r
+            return "SUBSTRING(CAST($value AS VARCHAR) FROM $position FOR $length)";\r
+        }\r
+        return "SUBSTRING(CAST($value AS VARCHAR) FROM $position)";\r
+    }\r
+\r
+    // }}}\r
+    // {{{ random()\r
+\r
+    /**\r
+     * return string to call a function to get random value inside an SQL statement\r
+     *\r
+     * @return return string to generate float between 0 and 1\r
+     * @access public\r
+     */\r
+    function random()\r
+    {\r
+        return 'RANDOM()';\r
+    }\r
+\r
+    // }}}\r
+}\r
 ?>
\ No newline at end of file
index 8a5b7ec8fad628c4cfc9cdbe61e57c9dd309c871..0a46a4f06a5233228c8a9c3d7de957952c2c476f 100644 (file)
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: sqlite.php,v 1.10 2008/02/17 18:54:08 quipo Exp $
-//
-
-require_once('MDB2/Driver/Function/Common.php');
-
-/**
- * MDB2 SQLite driver for the function modules
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Function_sqlite extends MDB2_Driver_Function_Common
-{
-    // {{{ constructor
-
-    /**
-     * Constructor
-     */
-    function __construct($db_index)
-    {
-        parent::__construct($db_index);
-        // create all sorts of UDFs
-    }
-
-    // {{{ now()
-
-    /**
-     * Return string to call a variable with the current timestamp inside an SQL statement
-     * There are three special variables for current date and time.
-     *
-     * @return string to call a variable with the current timestamp
-     * @access public
-     */
-    function now($type = 'timestamp')
-    {
-        switch ($type) {
-        case 'time':
-            return 'time(\'now\')';
-        case 'date':
-            return 'date(\'now\')';
-        case 'timestamp':
-        default:
-            return 'datetime(\'now\')';
-        }
-    }
-
-    // }}}
-    // {{{ unixtimestamp()
-
-    /**
-     * return string to call a function to get the unix timestamp from a iso timestamp
-     *
-     * @param string $expression
-     *
-     * @return string to call a variable with the timestamp
-     * @access public
-     */
-    function unixtimestamp($expression)
-    {
-        return 'strftime("%s",'. $expression.', "utc")';
-    }
-
-    // }}}
-    // {{{ substring()
-
-    /**
-     * return string to call a function to get a substring inside an SQL statement
-     *
-     * @return string to call a function to get a substring
-     * @access public
-     */
-    function substring($value, $position = 1, $length = null)
-    {
-        if (!is_null($length)) {
-            return "substr($value,$position,$length)";
-        }
-        return "substr($value,$position,length($value))";
-    }
-
-    // }}}
-    // {{{ random()
-
-    /**
-     * return string to call a function to get random value inside an SQL statement
-     *
-     * @return return string to generate float between 0 and 1
-     * @access public
-     */
-    function random()
-    {
-        return '((RANDOM()+2147483648)/4294967296)';
-    }
-
-    // }}}
-    // {{{ replace()
-
-    /**
-     * return string to call a function to get a replacement inside an SQL statement.
-     *
-     * @return string to call a function to get a replace
-     * @access public
-     */
-    function replace($str, $from_str, $to_str)
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $error =& $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-        return $error;
-    }
-
-    // }}}
-}
-?>
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: sqlite.php 295587 2010-02-28 17:16:38Z quipo $\r
+//\r
+\r
+require_once 'MDB2/Driver/Function/Common.php';\r
+\r
+/**\r
+ * MDB2 SQLite driver for the function modules\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Driver_Function_sqlite extends MDB2_Driver_Function_Common\r
+{\r
+    // {{{ constructor\r
+\r
+    /**\r
+     * Constructor\r
+     */\r
+    function __construct($db_index)\r
+    {\r
+        parent::__construct($db_index);\r
+        // create all sorts of UDFs\r
+    }\r
+\r
+    // {{{ now()\r
+\r
+    /**\r
+     * Return string to call a variable with the current timestamp inside an SQL statement\r
+     * There are three special variables for current date and time.\r
+     *\r
+     * @return string to call a variable with the current timestamp\r
+     * @access public\r
+     */\r
+    function now($type = 'timestamp')\r
+    {\r
+        switch ($type) {\r
+        case 'time':\r
+            return 'time(\'now\')';\r
+        case 'date':\r
+            return 'date(\'now\')';\r
+        case 'timestamp':\r
+        default:\r
+            return 'datetime(\'now\')';\r
+        }\r
+    }\r
+\r
+    // }}}\r
+    // {{{ unixtimestamp()\r
+\r
+    /**\r
+     * return string to call a function to get the unix timestamp from a iso timestamp\r
+     *\r
+     * @param string $expression\r
+     *\r
+     * @return string to call a variable with the timestamp\r
+     * @access public\r
+     */\r
+    function unixtimestamp($expression)\r
+    {\r
+        return 'strftime("%s",'. $expression.', "utc")';\r
+    }\r
+\r
+    // }}}\r
+    // {{{ substring()\r
+\r
+    /**\r
+     * return string to call a function to get a substring inside an SQL statement\r
+     *\r
+     * @return string to call a function to get a substring\r
+     * @access public\r
+     */\r
+    function substring($value, $position = 1, $length = null)\r
+    {\r
+        if (null !== $length) {\r
+            return "substr($value, $position, $length)";\r
+        }\r
+        return "substr($value, $position, length($value))";\r
+    }\r
+\r
+    // }}}\r
+    // {{{ random()\r
+\r
+    /**\r
+     * return string to call a function to get random value inside an SQL statement\r
+     *\r
+     * @return return string to generate float between 0 and 1\r
+     * @access public\r
+     */\r
+    function random()\r
+    {\r
+        return '((RANDOM()+2147483648)/4294967296)';\r
+    }\r
+\r
+    // }}}\r
+    // {{{ replace()\r
+\r
+    /**\r
+     * return string to call a function to get a replacement inside an SQL statement.\r
+     *\r
+     * @return string to call a function to get a replace\r
+     * @access public\r
+     */\r
+    function replace($str, $from_str, $to_str)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $error = $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+        return $error;\r
+    }\r
+\r
+    // }}}\r
+}\r
+?>\r
index 9e16749bffc49b12d2c7ec296f40da06562b7bad..fadd72934d626a170704645b0c50e4182614cedf 100644 (file)
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Authors: Lukas Smith <smith@pooteeweet.org>                          |
-// |          Lorenzo Alberton <l.alberton@quipo.it>                      |
-// +----------------------------------------------------------------------+
-//
-// $Id: Common.php,v 1.72 2009/01/14 15:00:40 quipo Exp $
-//
-
-/**
- * @package  MDB2
- * @category Database
- * @author   Lukas Smith <smith@pooteeweet.org>
- * @author   Lorenzo Alberton <l.alberton@quipo.it>
- */
-
-/**
- * Base class for the management modules that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Manager');
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Manager_Common extends MDB2_Module_Common
-{
-    // {{{ splitTableSchema()
-
-    /**
-     * Split the "[owner|schema].table" notation into an array
-     *
-     * @param string $table [schema and] table name
-     *
-     * @return array array(schema, table)
-     * @access private
-     */
-    function splitTableSchema($table)
-    {
-        $ret = array();
-        if (strpos($table, '.') !== false) {
-            return explode('.', $table);
-        }
-        return array(null, $table);
-    }
-
-    // }}}
-    // {{{ getFieldDeclarationList()
-
-    /**
-     * Get declaration of a number of field in bulk
-     *
-     * @param array $fields  a multidimensional associative array.
-     *      The first dimension determines the field name, while the second
-     *      dimension is keyed with the name of the properties
-     *      of the field being declared as array indexes. Currently, the types
-     *      of supported field properties are as follows:
-     *
-     *      default
-     *          Boolean value to be used as default for this field.
-     *
-     *      notnull
-     *          Boolean flag that indicates whether this field is constrained
-     *          to not be set to null.
-     *
-     * @return mixed string on success, a MDB2 error on failure
-     * @access public
-     */
-    function getFieldDeclarationList($fields)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        if (!is_array($fields) || empty($fields)) {
-            return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                'missing any fields', __FUNCTION__);
-        }
-        foreach ($fields as $field_name => $field) {
-            $query = $db->getDeclaration($field['type'], $field_name, $field);
-            if (PEAR::isError($query)) {
-                return $query;
-            }
-            $query_fields[] = $query;
-        }
-        return implode(', ', $query_fields);
-    }
-
-    // }}}
-    // {{{ _fixSequenceName()
-
-    /**
-     * Removes any formatting in an sequence name using the 'seqname_format' option
-     *
-     * @param string $sqn string that containts name of a potential sequence
-     * @param bool $check if only formatted sequences should be returned
-     * @return string name of the sequence with possible formatting removed
-     * @access protected
-     */
-    function _fixSequenceName($sqn, $check = false)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $seq_pattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $db->options['seqname_format']).'$/i';
-        $seq_name = preg_replace($seq_pattern, '\\1', $sqn);
-        if ($seq_name && !strcasecmp($sqn, $db->getSequenceName($seq_name))) {
-            return $seq_name;
-        }
-        if ($check) {
-            return false;
-        }
-        return $sqn;
-    }
-
-    // }}}
-    // {{{ _fixIndexName()
-
-    /**
-     * Removes any formatting in an index name using the 'idxname_format' option
-     *
-     * @param string $idx string that containts name of anl index
-     * @return string name of the index with eventual formatting removed
-     * @access protected
-     */
-    function _fixIndexName($idx)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $idx_pattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $db->options['idxname_format']).'$/i';
-        $idx_name = preg_replace($idx_pattern, '\\1', $idx);
-        if ($idx_name && !strcasecmp($idx, $db->getIndexName($idx_name))) {
-            return $idx_name;
-        }
-        return $idx;
-    }
-
-    // }}}
-    // {{{ createDatabase()
-
-    /**
-     * create a new database
-     *
-     * @param string $name    name of the database that should be created
-     * @param array  $options array with charset, collation info
-     *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function createDatabase($database, $options = array())
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ alterDatabase()
-
-    /**
-     * alter an existing database
-     *
-     * @param string $name    name of the database that should be created
-     * @param array  $options array with charset, collation info
-     *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function alterDatabase($database, $options = array())
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ dropDatabase()
-
-    /**
-     * drop an existing database
-     *
-     * @param string $name name of the database that should be dropped
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function dropDatabase($database)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ _getCreateTableQuery()
-
-    /**
-     * Create a basic SQL query for a new table creation
-     *
-     * @param string $name    Name of the database that should be created
-     * @param array  $fields  Associative array that contains the definition of each field of the new table
-     * @param array  $options An associative array of table options
-     *
-     * @return mixed string (the SQL query) on success, a MDB2 error on failure
-     * @see createTable()
-     */
-    function _getCreateTableQuery($name, $fields, $options = array())
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        if (!$name) {
-            return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
-                'no valid table name specified', __FUNCTION__);
-        }
-        if (empty($fields)) {
-            return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
-                'no fields specified for table "'.$name.'"', __FUNCTION__);
-        }
-        $query_fields = $this->getFieldDeclarationList($fields);
-        if (PEAR::isError($query_fields)) {
-            return $query_fields;
-        }
-        if (!empty($options['primary'])) {
-            $query_fields.= ', PRIMARY KEY ('.implode(', ', array_keys($options['primary'])).')';
-        }
-
-        $name = $db->quoteIdentifier($name, true);
-        $result = 'CREATE ';
-        if (!empty($options['temporary'])) {
-            $result .= $this->_getTemporaryTableQuery();
-        }
-        $result .= " TABLE $name ($query_fields)";
-        return $result;
-    }
-
-    // }}}
-    // {{{ _getTemporaryTableQuery()
-
-    /**
-     * A method to return the required SQL string that fits between CREATE ... TABLE
-     * to create the table as a temporary table.
-     *
-     * Should be overridden in driver classes to return the correct string for the
-     * specific database type.
-     *
-     * The default is to return the string "TEMPORARY" - this will result in a
-     * SQL error for any database that does not support temporary tables, or that
-     * requires a different SQL command from "CREATE TEMPORARY TABLE".
-     *
-     * @return string The string required to be placed between "CREATE" and "TABLE"
-     *                to generate a temporary table, if possible.
-     */
-    function _getTemporaryTableQuery()
-    {
-        return 'TEMPORARY';
-    }
-
-    // }}}
-    // {{{ createTable()
-
-    /**
-     * create a new table
-     *
-     * @param string $name   Name of the database that should be created
-     * @param array $fields  Associative array that contains the definition of each field of the new table
-     *                       The indexes of the array entries are the names of the fields of the table an
-     *                       the array entry values are associative arrays like those that are meant to be
-     *                       passed with the field definitions to get[Type]Declaration() functions.
-     *                          array(
-     *                              'id' => array(
-     *                                  'type' => 'integer',
-     *                                  'unsigned' => 1
-     *                                  'notnull' => 1
-     *                                  'default' => 0
-     *                              ),
-     *                              'name' => array(
-     *                                  'type' => 'text',
-     *                                  'length' => 12
-     *                              ),
-     *                              'password' => array(
-     *                                  'type' => 'text',
-     *                                  'length' => 12
-     *                              )
-     *                          );
-     * @param array $options  An associative array of table options:
-     *                          array(
-     *                              'comment' => 'Foo',
-     *                              'temporary' => true|false,
-     *                          );
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function createTable($name, $fields, $options = array())
-    {
-        $query = $this->_getCreateTableQuery($name, $fields, $options);
-        if (PEAR::isError($query)) {
-            return $query;
-        }
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-        $result = $db->exec($query);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ dropTable()
-
-    /**
-     * drop an existing table
-     *
-     * @param string $name name of the table that should be dropped
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function dropTable($name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $name = $db->quoteIdentifier($name, true);
-        return $db->exec("DROP TABLE $name");
-    }
-
-    // }}}
-    // {{{ truncateTable()
-
-    /**
-     * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported,
-     * it falls back to a DELETE FROM TABLE query)
-     *
-     * @param string $name name of the table that should be truncated
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function truncateTable($name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $name = $db->quoteIdentifier($name, true);
-        return $db->exec("DELETE FROM $name");
-    }
-
-    // }}}
-    // {{{ vacuum()
-
-    /**
-     * Optimize (vacuum) all the tables in the db (or only the specified table)
-     * and optionally run ANALYZE.
-     *
-     * @param string $table table name (all the tables if empty)
-     * @param array  $options an array with driver-specific options:
-     *               - timeout [int] (in seconds) [mssql-only]
-     *               - analyze [boolean] [pgsql and mysql]
-     *               - full [boolean] [pgsql-only]
-     *               - freeze [boolean] [pgsql-only]
-     *
-     * @return mixed MDB2_OK success, a MDB2 error on failure
-     * @access public
-     */
-    function vacuum($table = null, $options = array())
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ alterTable()
-
-    /**
-     * alter an existing table
-     *
-     * @param string $name         name of the table that is intended to be changed.
-     * @param array $changes     associative array that contains the details of each type
-     *                             of change that is intended to be performed. The types of
-     *                             changes that are currently supported are defined as follows:
-     *
-     *                             name
-     *
-     *                                New name for the table.
-     *
-     *                            add
-     *
-     *                                Associative array with the names of fields to be added as
-     *                                 indexes of the array. The value of each entry of the array
-     *                                 should be set to another associative array with the properties
-     *                                 of the fields to be added. The properties of the fields should
-     *                                 be the same as defined by the MDB2 parser.
-     *
-     *
-     *                            remove
-     *
-     *                                Associative array with the names of fields to be removed as indexes
-     *                                 of the array. Currently the values assigned to each entry are ignored.
-     *                                 An empty array should be used for future compatibility.
-     *
-     *                            rename
-     *
-     *                                Associative array with the names of fields to be renamed as indexes
-     *                                 of the array. The value of each entry of the array should be set to
-     *                                 another associative array with the entry named name with the new
-     *                                 field name and the entry named Declaration that is expected to contain
-     *                                 the portion of the field declaration already in DBMS specific SQL code
-     *                                 as it is used in the CREATE TABLE statement.
-     *
-     *                            change
-     *
-     *                                Associative array with the names of the fields to be changed as indexes
-     *                                 of the array. Keep in mind that if it is intended to change either the
-     *                                 name of a field and any other properties, the change array entries
-     *                                 should have the new names of the fields as array indexes.
-     *
-     *                                The value of each entry of the array should be set to another associative
-     *                                 array with the properties of the fields to that are meant to be changed as
-     *                                 array entries. These entries should be assigned to the new values of the
-     *                                 respective properties. The properties of the fields should be the same
-     *                                 as defined by the MDB2 parser.
-     *
-     *                            Example
-     *                                array(
-     *                                    'name' => 'userlist',
-     *                                    'add' => array(
-     *                                        'quota' => array(
-     *                                            'type' => 'integer',
-     *                                            'unsigned' => 1
-     *                                        )
-     *                                    ),
-     *                                    'remove' => array(
-     *                                        'file_limit' => array(),
-     *                                        'time_limit' => array()
-     *                                    ),
-     *                                    'change' => array(
-     *                                        'name' => array(
-     *                                            'length' => '20',
-     *                                            'definition' => array(
-     *                                                'type' => 'text',
-     *                                                'length' => 20,
-     *                                            ),
-     *                                        )
-     *                                    ),
-     *                                    'rename' => array(
-     *                                        'sex' => array(
-     *                                            'name' => 'gender',
-     *                                            'definition' => array(
-     *                                                'type' => 'text',
-     *                                                'length' => 1,
-     *                                                'default' => 'M',
-     *                                            ),
-     *                                        )
-     *                                    )
-     *                                )
-     *
-     * @param boolean $check     indicates whether the function should just check if the DBMS driver
-     *                             can perform the requested table alterations if the value is true or
-     *                             actually perform them otherwise.
-     * @access public
-     *
-      * @return mixed MDB2_OK on success, a MDB2 error on failure
-     */
-    function alterTable($name, $changes, $check)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ listDatabases()
-
-    /**
-     * list all databases
-     *
-     * @return mixed array of database names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listDatabases()
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implementedd', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ listUsers()
-
-    /**
-     * list all users
-     *
-     * @return mixed array of user names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listUsers()
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ listViews()
-
-    /**
-     * list all views in the current database
-     *
-     * @param string database, the current is default
-     *               NB: not all the drivers can get the view names from
-     *               a database other than the current one
-     * @return mixed array of view names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listViews($database = null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ listTableViews()
-
-    /**
-     * list the views in the database that reference a given table
-     *
-     * @param string table for which all referenced views should be found
-     * @return mixed array of view names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTableViews($table)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ listTableTriggers()
-
-    /**
-     * list all triggers in the database that reference a given table
-     *
-     * @param string table for which all referenced triggers should be found
-     * @return mixed array of trigger names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTableTriggers($table = null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ listFunctions()
-
-    /**
-     * list all functions in the current database
-     *
-     * @return mixed array of function names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listFunctions()
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ listTables()
-
-    /**
-     * list all tables in the current database
-     *
-     * @param string database, the current is default.
-     *               NB: not all the drivers can get the table names from
-     *               a database other than the current one
-     * @return mixed array of table names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTables($database = null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ listTableFields()
-
-    /**
-     * list all fields in a table in the current database
-     *
-     * @param string $table name of table that should be used in method
-     * @return mixed array of field names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTableFields($table)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ createIndex()
-
-    /**
-     * Get the stucture of a field into an array
-     *
-     * @param string    $table         name of the table on which the index is to be created
-     * @param string    $name         name of the index to be created
-     * @param array     $definition        associative array that defines properties of the index to be created.
-     *                                 Currently, only one property named FIELDS is supported. This property
-     *                                 is also an associative with the names of the index fields as array
-     *                                 indexes. Each entry of this array is set to another type of associative
-     *                                 array that specifies properties of the index that are specific to
-     *                                 each field.
-     *
-     *                                Currently, only the sorting property is supported. It should be used
-     *                                 to define the sorting direction of the index. It may be set to either
-     *                                 ascending or descending.
-     *
-     *                                Not all DBMS support index sorting direction configuration. The DBMS
-     *                                 drivers of those that do not support it ignore this property. Use the
-     *                                 function supports() to determine whether the DBMS driver can manage indexes.
-     *
-     *                                 Example
-     *                                    array(
-     *                                        'fields' => array(
-     *                                            'user_name' => array(
-     *                                                'sorting' => 'ascending'
-     *                                            ),
-     *                                            'last_login' => array()
-     *                                        )
-     *                                    )
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function createIndex($table, $name, $definition)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $table = $db->quoteIdentifier($table, true);
-        $name = $db->quoteIdentifier($db->getIndexName($name), true);
-        $query = "CREATE INDEX $name ON $table";
-        $fields = array();
-        foreach (array_keys($definition['fields']) as $field) {
-            $fields[] = $db->quoteIdentifier($field, true);
-        }
-        $query .= ' ('. implode(', ', $fields) . ')';
-        return $db->exec($query);
-    }
-
-    // }}}
-    // {{{ dropIndex()
-
-    /**
-     * drop existing index
-     *
-     * @param string    $table         name of table that should be used in method
-     * @param string    $name         name of the index to be dropped
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function dropIndex($table, $name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $name = $db->quoteIdentifier($db->getIndexName($name), true);
-        return $db->exec("DROP INDEX $name");
-    }
-
-    // }}}
-    // {{{ listTableIndexes()
-
-    /**
-     * list all indexes in a table
-     *
-     * @param string $table name of table that should be used in method
-     * @return mixed array of index names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTableIndexes($table)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ _getAdvancedFKOptions()
-
-    /**
-     * Return the FOREIGN KEY query section dealing with non-standard options
-     * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
-     *
-     * @param array $definition
-     * @return string
-     * @access protected
-     */
-    function _getAdvancedFKOptions($definition)
-    {
-        return '';
-    }
-
-    // }}}
-    // {{{ createConstraint()
-
-    /**
-     * create a constraint on a table
-     *
-     * @param string    $table       name of the table on which the constraint is to be created
-     * @param string    $name        name of the constraint to be created
-     * @param array     $definition  associative array that defines properties of the constraint to be created.
-     *                               The full structure of the array looks like this:
-     *          <pre>
-     *          array (
-     *              [primary] => 0
-     *              [unique]  => 0
-     *              [foreign] => 1
-     *              [check]   => 0
-     *              [fields] => array (
-     *                  [field1name] => array() // one entry per each field covered
-     *                  [field2name] => array() // by the index
-     *                  [field3name] => array(
-     *                      [sorting]  => ascending
-     *                      [position] => 3
-     *                  )
-     *              )
-     *              [references] => array(
-     *                  [table] => name
-     *                  [fields] => array(
-     *                      [field1name] => array(  //one entry per each referenced field
-     *                           [position] => 1
-     *                      )
-     *                  )
-     *              )
-     *              [deferrable] => 0
-     *              [initiallydeferred] => 0
-     *              [onupdate] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
-     *              [ondelete] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
-     *              [match] => SIMPLE|PARTIAL|FULL
-     *          );
-     *          </pre>
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function createConstraint($table, $name, $definition)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-        $table = $db->quoteIdentifier($table, true);
-        $name = $db->quoteIdentifier($db->getIndexName($name), true);
-        $query = "ALTER TABLE $table ADD CONSTRAINT $name";
-        if (!empty($definition['primary'])) {
-            $query.= ' PRIMARY KEY';
-        } elseif (!empty($definition['unique'])) {
-            $query.= ' UNIQUE';
-        } elseif (!empty($definition['foreign'])) {
-            $query.= ' FOREIGN KEY';
-        }
-        $fields = array();
-        foreach (array_keys($definition['fields']) as $field) {
-            $fields[] = $db->quoteIdentifier($field, true);
-        }
-        $query .= ' ('. implode(', ', $fields) . ')';
-        if (!empty($definition['foreign'])) {
-            $query.= ' REFERENCES ' . $db->quoteIdentifier($definition['references']['table'], true);
-            $referenced_fields = array();
-            foreach (array_keys($definition['references']['fields']) as $field) {
-                $referenced_fields[] = $db->quoteIdentifier($field, true);
-            }
-            $query .= ' ('. implode(', ', $referenced_fields) . ')';
-            $query .= $this->_getAdvancedFKOptions($definition);
-        }
-        return $db->exec($query);
-    }
-
-    // }}}
-    // {{{ dropConstraint()
-
-    /**
-     * drop existing constraint
-     *
-     * @param string    $table        name of table that should be used in method
-     * @param string    $name         name of the constraint to be dropped
-     * @param string    $primary      hint if the constraint is primary
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function dropConstraint($table, $name, $primary = false)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $table = $db->quoteIdentifier($table, true);
-        $name = $db->quoteIdentifier($db->getIndexName($name), true);
-        return $db->exec("ALTER TABLE $table DROP CONSTRAINT $name");
-    }
-
-    // }}}
-    // {{{ listTableConstraints()
-
-    /**
-     * list all constraints in a table
-     *
-     * @param string $table name of table that should be used in method
-     * @return mixed array of constraint names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTableConstraints($table)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ createSequence()
-
-    /**
-     * create sequence
-     *
-     * @param string    $seq_name     name of the sequence to be created
-     * @param string    $start         start value of the sequence; default is 1
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function createSequence($seq_name, $start = 1)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ dropSequence()
-
-    /**
-     * drop existing sequence
-     *
-     * @param string    $seq_name     name of the sequence to be dropped
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function dropSequence($name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ listSequences()
-
-    /**
-     * list all sequences in the current database
-     *
-     * @param string database, the current is default
-     *               NB: not all the drivers can get the sequence names from
-     *               a database other than the current one
-     * @return mixed array of sequence names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listSequences($database = null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-}
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Authors: Lukas Smith <smith@pooteeweet.org>                          |\r
+// |          Lorenzo Alberton <l.alberton@quipo.it>                      |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: Common.php 295587 2010-02-28 17:16:38Z quipo $\r
+//\r
+\r
+/**\r
+ * @package  MDB2\r
+ * @category Database\r
+ * @author   Lukas Smith <smith@pooteeweet.org>\r
+ * @author   Lorenzo Alberton <l.alberton@quipo.it>\r
+ */\r
+\r
+/**\r
+ * Base class for the management modules that is extended by each MDB2 driver\r
+ *\r
+ * To load this module in the MDB2 object:\r
+ * $mdb->loadModule('Manager');\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Driver_Manager_Common extends MDB2_Module_Common\r
+{\r
+    // {{{ splitTableSchema()\r
+\r
+    /**\r
+     * Split the "[owner|schema].table" notation into an array\r
+     *\r
+     * @param string $table [schema and] table name\r
+     *\r
+     * @return array array(schema, table)\r
+     * @access private\r
+     */\r
+    function splitTableSchema($table)\r
+    {\r
+        $ret = array();\r
+        if (strpos($table, '.') !== false) {\r
+            return explode('.', $table);\r
+        }\r
+        return array(null, $table);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getFieldDeclarationList()\r
+\r
+    /**\r
+     * Get declaration of a number of field in bulk\r
+     *\r
+     * @param array $fields  a multidimensional associative array.\r
+     *      The first dimension determines the field name, while the second\r
+     *      dimension is keyed with the name of the properties\r
+     *      of the field being declared as array indexes. Currently, the types\r
+     *      of supported field properties are as follows:\r
+     *\r
+     *      default\r
+     *          Boolean value to be used as default for this field.\r
+     *\r
+     *      notnull\r
+     *          Boolean flag that indicates whether this field is constrained\r
+     *          to not be set to null.\r
+     *\r
+     * @return mixed string on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function getFieldDeclarationList($fields)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        if (!is_array($fields) || empty($fields)) {\r
+            return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,\r
+                'missing any fields', __FUNCTION__);\r
+        }\r
+        foreach ($fields as $field_name => $field) {\r
+            $query = $db->getDeclaration($field['type'], $field_name, $field);\r
+            if (PEAR::isError($query)) {\r
+                return $query;\r
+            }\r
+            $query_fields[] = $query;\r
+        }\r
+        return implode(', ', $query_fields);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _fixSequenceName()\r
+\r
+    /**\r
+     * Removes any formatting in an sequence name using the 'seqname_format' option\r
+     *\r
+     * @param string $sqn string that containts name of a potential sequence\r
+     * @param bool $check if only formatted sequences should be returned\r
+     * @return string name of the sequence with possible formatting removed\r
+     * @access protected\r
+     */\r
+    function _fixSequenceName($sqn, $check = false)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $seq_pattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $db->options['seqname_format']).'$/i';\r
+        $seq_name = preg_replace($seq_pattern, '\\1', $sqn);\r
+        if ($seq_name && !strcasecmp($sqn, $db->getSequenceName($seq_name))) {\r
+            return $seq_name;\r
+        }\r
+        if ($check) {\r
+            return false;\r
+        }\r
+        return $sqn;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _fixIndexName()\r
+\r
+    /**\r
+     * Removes any formatting in an index name using the 'idxname_format' option\r
+     *\r
+     * @param string $idx string that containts name of anl index\r
+     * @return string name of the index with eventual formatting removed\r
+     * @access protected\r
+     */\r
+    function _fixIndexName($idx)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $idx_pattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $db->options['idxname_format']).'$/i';\r
+        $idx_name = preg_replace($idx_pattern, '\\1', $idx);\r
+        if ($idx_name && !strcasecmp($idx, $db->getIndexName($idx_name))) {\r
+            return $idx_name;\r
+        }\r
+        return $idx;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ createDatabase()\r
+\r
+    /**\r
+     * create a new database\r
+     *\r
+     * @param string $name    name of the database that should be created\r
+     * @param array  $options array with charset, collation info\r
+     *\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function createDatabase($database, $options = array())\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ alterDatabase()\r
+\r
+    /**\r
+     * alter an existing database\r
+     *\r
+     * @param string $name    name of the database that should be created\r
+     * @param array  $options array with charset, collation info\r
+     *\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function alterDatabase($database, $options = array())\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ dropDatabase()\r
+\r
+    /**\r
+     * drop an existing database\r
+     *\r
+     * @param string $name name of the database that should be dropped\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function dropDatabase($database)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getCreateTableQuery()\r
+\r
+    /**\r
+     * Create a basic SQL query for a new table creation\r
+     *\r
+     * @param string $name    Name of the database that should be created\r
+     * @param array  $fields  Associative array that contains the definition of each field of the new table\r
+     * @param array  $options An associative array of table options\r
+     *\r
+     * @return mixed string (the SQL query) on success, a MDB2 error on failure\r
+     * @see createTable()\r
+     */\r
+    function _getCreateTableQuery($name, $fields, $options = array())\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        if (!$name) {\r
+            return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,\r
+                'no valid table name specified', __FUNCTION__);\r
+        }\r
+        if (empty($fields)) {\r
+            return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,\r
+                'no fields specified for table "'.$name.'"', __FUNCTION__);\r
+        }\r
+        $query_fields = $this->getFieldDeclarationList($fields);\r
+        if (PEAR::isError($query_fields)) {\r
+            return $query_fields;\r
+        }\r
+        if (!empty($options['primary'])) {\r
+            $query_fields.= ', PRIMARY KEY ('.implode(', ', array_keys($options['primary'])).')';\r
+        }\r
+\r
+        $name = $db->quoteIdentifier($name, true);\r
+        $result = 'CREATE ';\r
+        if (!empty($options['temporary'])) {\r
+            $result .= $this->_getTemporaryTableQuery();\r
+        }\r
+        $result .= " TABLE $name ($query_fields)";\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getTemporaryTableQuery()\r
+\r
+    /**\r
+     * A method to return the required SQL string that fits between CREATE ... TABLE\r
+     * to create the table as a temporary table.\r
+     *\r
+     * Should be overridden in driver classes to return the correct string for the\r
+     * specific database type.\r
+     *\r
+     * The default is to return the string "TEMPORARY" - this will result in a\r
+     * SQL error for any database that does not support temporary tables, or that\r
+     * requires a different SQL command from "CREATE TEMPORARY TABLE".\r
+     *\r
+     * @return string The string required to be placed between "CREATE" and "TABLE"\r
+     *                to generate a temporary table, if possible.\r
+     */\r
+    function _getTemporaryTableQuery()\r
+    {\r
+        return 'TEMPORARY';\r
+    }\r
+\r
+    // }}}\r
+    // {{{ createTable()\r
+\r
+    /**\r
+     * create a new table\r
+     *\r
+     * @param string $name   Name of the database that should be created\r
+     * @param array $fields  Associative array that contains the definition of each field of the new table\r
+     *                       The indexes of the array entries are the names of the fields of the table an\r
+     *                       the array entry values are associative arrays like those that are meant to be\r
+     *                       passed with the field definitions to get[Type]Declaration() functions.\r
+     *                          array(\r
+     *                              'id' => array(\r
+     *                                  'type' => 'integer',\r
+     *                                  'unsigned' => 1\r
+     *                                  'notnull' => 1\r
+     *                                  'default' => 0\r
+     *                              ),\r
+     *                              'name' => array(\r
+     *                                  'type' => 'text',\r
+     *                                  'length' => 12\r
+     *                              ),\r
+     *                              'password' => array(\r
+     *                                  'type' => 'text',\r
+     *                                  'length' => 12\r
+     *                              )\r
+     *                          );\r
+     * @param array $options  An associative array of table options:\r
+     *                          array(\r
+     *                              'comment' => 'Foo',\r
+     *                              'temporary' => true|false,\r
+     *                          );\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function createTable($name, $fields, $options = array())\r
+    {\r
+        $query = $this->_getCreateTableQuery($name, $fields, $options);\r
+        if (PEAR::isError($query)) {\r
+            return $query;\r
+        }\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+        $result = $db->exec($query);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ dropTable()\r
+\r
+    /**\r
+     * drop an existing table\r
+     *\r
+     * @param string $name name of the table that should be dropped\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function dropTable($name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $name = $db->quoteIdentifier($name, true);\r
+        return $db->exec("DROP TABLE $name");\r
+    }\r
+\r
+    // }}}\r
+    // {{{ truncateTable()\r
+\r
+    /**\r
+     * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported,\r
+     * it falls back to a DELETE FROM TABLE query)\r
+     *\r
+     * @param string $name name of the table that should be truncated\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function truncateTable($name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $name = $db->quoteIdentifier($name, true);\r
+        return $db->exec("DELETE FROM $name");\r
+    }\r
+\r
+    // }}}\r
+    // {{{ vacuum()\r
+\r
+    /**\r
+     * Optimize (vacuum) all the tables in the db (or only the specified table)\r
+     * and optionally run ANALYZE.\r
+     *\r
+     * @param string $table table name (all the tables if empty)\r
+     * @param array  $options an array with driver-specific options:\r
+     *               - timeout [int] (in seconds) [mssql-only]\r
+     *               - analyze [boolean] [pgsql and mysql]\r
+     *               - full [boolean] [pgsql-only]\r
+     *               - freeze [boolean] [pgsql-only]\r
+     *\r
+     * @return mixed MDB2_OK success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function vacuum($table = null, $options = array())\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ alterTable()\r
+\r
+    /**\r
+     * alter an existing table\r
+     *\r
+     * @param string $name         name of the table that is intended to be changed.\r
+     * @param array $changes     associative array that contains the details of each type\r
+     *                             of change that is intended to be performed. The types of\r
+     *                             changes that are currently supported are defined as follows:\r
+     *\r
+     *                             name\r
+     *\r
+     *                                New name for the table.\r
+     *\r
+     *                            add\r
+     *\r
+     *                                Associative array with the names of fields to be added as\r
+     *                                 indexes of the array. The value of each entry of the array\r
+     *                                 should be set to another associative array with the properties\r
+     *                                 of the fields to be added. The properties of the fields should\r
+     *                                 be the same as defined by the MDB2 parser.\r
+     *\r
+     *\r
+     *                            remove\r
+     *\r
+     *                                Associative array with the names of fields to be removed as indexes\r
+     *                                 of the array. Currently the values assigned to each entry are ignored.\r
+     *                                 An empty array should be used for future compatibility.\r
+     *\r
+     *                            rename\r
+     *\r
+     *                                Associative array with the names of fields to be renamed as indexes\r
+     *                                 of the array. The value of each entry of the array should be set to\r
+     *                                 another associative array with the entry named name with the new\r
+     *                                 field name and the entry named Declaration that is expected to contain\r
+     *                                 the portion of the field declaration already in DBMS specific SQL code\r
+     *                                 as it is used in the CREATE TABLE statement.\r
+     *\r
+     *                            change\r
+     *\r
+     *                                Associative array with the names of the fields to be changed as indexes\r
+     *                                 of the array. Keep in mind that if it is intended to change either the\r
+     *                                 name of a field and any other properties, the change array entries\r
+     *                                 should have the new names of the fields as array indexes.\r
+     *\r
+     *                                The value of each entry of the array should be set to another associative\r
+     *                                 array with the properties of the fields to that are meant to be changed as\r
+     *                                 array entries. These entries should be assigned to the new values of the\r
+     *                                 respective properties. The properties of the fields should be the same\r
+     *                                 as defined by the MDB2 parser.\r
+     *\r
+     *                            Example\r
+     *                                array(\r
+     *                                    'name' => 'userlist',\r
+     *                                    'add' => array(\r
+     *                                        'quota' => array(\r
+     *                                            'type' => 'integer',\r
+     *                                            'unsigned' => 1\r
+     *                                        )\r
+     *                                    ),\r
+     *                                    'remove' => array(\r
+     *                                        'file_limit' => array(),\r
+     *                                        'time_limit' => array()\r
+     *                                    ),\r
+     *                                    'change' => array(\r
+     *                                        'name' => array(\r
+     *                                            'length' => '20',\r
+     *                                            'definition' => array(\r
+     *                                                'type' => 'text',\r
+     *                                                'length' => 20,\r
+     *                                            ),\r
+     *                                        )\r
+     *                                    ),\r
+     *                                    'rename' => array(\r
+     *                                        'sex' => array(\r
+     *                                            'name' => 'gender',\r
+     *                                            'definition' => array(\r
+     *                                                'type' => 'text',\r
+     *                                                'length' => 1,\r
+     *                                                'default' => 'M',\r
+     *                                            ),\r
+     *                                        )\r
+     *                                    )\r
+     *                                )\r
+     *\r
+     * @param boolean $check     indicates whether the function should just check if the DBMS driver\r
+     *                             can perform the requested table alterations if the value is true or\r
+     *                             actually perform them otherwise.\r
+     * @access public\r
+     *\r
+      * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     */\r
+    function alterTable($name, $changes, $check)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listDatabases()\r
+\r
+    /**\r
+     * list all databases\r
+     *\r
+     * @return mixed array of database names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listDatabases()\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implementedd', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listUsers()\r
+\r
+    /**\r
+     * list all users\r
+     *\r
+     * @return mixed array of user names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listUsers()\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listViews()\r
+\r
+    /**\r
+     * list all views in the current database\r
+     *\r
+     * @param string database, the current is default\r
+     *               NB: not all the drivers can get the view names from\r
+     *               a database other than the current one\r
+     * @return mixed array of view names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listViews($database = null)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTableViews()\r
+\r
+    /**\r
+     * list the views in the database that reference a given table\r
+     *\r
+     * @param string table for which all referenced views should be found\r
+     * @return mixed array of view names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTableViews($table)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTableTriggers()\r
+\r
+    /**\r
+     * list all triggers in the database that reference a given table\r
+     *\r
+     * @param string table for which all referenced triggers should be found\r
+     * @return mixed array of trigger names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTableTriggers($table = null)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listFunctions()\r
+\r
+    /**\r
+     * list all functions in the current database\r
+     *\r
+     * @return mixed array of function names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listFunctions()\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTables()\r
+\r
+    /**\r
+     * list all tables in the current database\r
+     *\r
+     * @param string database, the current is default.\r
+     *               NB: not all the drivers can get the table names from\r
+     *               a database other than the current one\r
+     * @return mixed array of table names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTables($database = null)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTableFields()\r
+\r
+    /**\r
+     * list all fields in a table in the current database\r
+     *\r
+     * @param string $table name of table that should be used in method\r
+     * @return mixed array of field names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTableFields($table)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ createIndex()\r
+\r
+    /**\r
+     * Get the stucture of a field into an array\r
+     *\r
+     * @param string    $table         name of the table on which the index is to be created\r
+     * @param string    $name         name of the index to be created\r
+     * @param array     $definition        associative array that defines properties of the index to be created.\r
+     *                                 Currently, only one property named FIELDS is supported. This property\r
+     *                                 is also an associative with the names of the index fields as array\r
+     *                                 indexes. Each entry of this array is set to another type of associative\r
+     *                                 array that specifies properties of the index that are specific to\r
+     *                                 each field.\r
+     *\r
+     *                                Currently, only the sorting property is supported. It should be used\r
+     *                                 to define the sorting direction of the index. It may be set to either\r
+     *                                 ascending or descending.\r
+     *\r
+     *                                Not all DBMS support index sorting direction configuration. The DBMS\r
+     *                                 drivers of those that do not support it ignore this property. Use the\r
+     *                                 function supports() to determine whether the DBMS driver can manage indexes.\r
+     *\r
+     *                                 Example\r
+     *                                    array(\r
+     *                                        'fields' => array(\r
+     *                                            'user_name' => array(\r
+     *                                                'sorting' => 'ascending'\r
+     *                                            ),\r
+     *                                            'last_login' => array()\r
+     *                                        )\r
+     *                                    )\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function createIndex($table, $name, $definition)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $table = $db->quoteIdentifier($table, true);\r
+        $name = $db->quoteIdentifier($db->getIndexName($name), true);\r
+        $query = "CREATE INDEX $name ON $table";\r
+        $fields = array();\r
+        foreach (array_keys($definition['fields']) as $field) {\r
+            $fields[] = $db->quoteIdentifier($field, true);\r
+        }\r
+        $query .= ' ('. implode(', ', $fields) . ')';\r
+        return $db->exec($query);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ dropIndex()\r
+\r
+    /**\r
+     * drop existing index\r
+     *\r
+     * @param string    $table         name of table that should be used in method\r
+     * @param string    $name         name of the index to be dropped\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function dropIndex($table, $name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $name = $db->quoteIdentifier($db->getIndexName($name), true);\r
+        return $db->exec("DROP INDEX $name");\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTableIndexes()\r
+\r
+    /**\r
+     * list all indexes in a table\r
+     *\r
+     * @param string $table name of table that should be used in method\r
+     * @return mixed array of index names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTableIndexes($table)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getAdvancedFKOptions()\r
+\r
+    /**\r
+     * Return the FOREIGN KEY query section dealing with non-standard options\r
+     * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...\r
+     *\r
+     * @param array $definition\r
+     * @return string\r
+     * @access protected\r
+     */\r
+    function _getAdvancedFKOptions($definition)\r
+    {\r
+        return '';\r
+    }\r
+\r
+    // }}}\r
+    // {{{ createConstraint()\r
+\r
+    /**\r
+     * create a constraint on a table\r
+     *\r
+     * @param string    $table       name of the table on which the constraint is to be created\r
+     * @param string    $name        name of the constraint to be created\r
+     * @param array     $definition  associative array that defines properties of the constraint to be created.\r
+     *                               The full structure of the array looks like this:\r
+     *          <pre>\r
+     *          array (\r
+     *              [primary] => 0\r
+     *              [unique]  => 0\r
+     *              [foreign] => 1\r
+     *              [check]   => 0\r
+     *              [fields] => array (\r
+     *                  [field1name] => array() // one entry per each field covered\r
+     *                  [field2name] => array() // by the index\r
+     *                  [field3name] => array(\r
+     *                      [sorting]  => ascending\r
+     *                      [position] => 3\r
+     *                  )\r
+     *              )\r
+     *              [references] => array(\r
+     *                  [table] => name\r
+     *                  [fields] => array(\r
+     *                      [field1name] => array(  //one entry per each referenced field\r
+     *                           [position] => 1\r
+     *                      )\r
+     *                  )\r
+     *              )\r
+     *              [deferrable] => 0\r
+     *              [initiallydeferred] => 0\r
+     *              [onupdate] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION\r
+     *              [ondelete] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION\r
+     *              [match] => SIMPLE|PARTIAL|FULL\r
+     *          );\r
+     *          </pre>\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function createConstraint($table, $name, $definition)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+        $table = $db->quoteIdentifier($table, true);\r
+        $name = $db->quoteIdentifier($db->getIndexName($name), true);\r
+        $query = "ALTER TABLE $table ADD CONSTRAINT $name";\r
+        if (!empty($definition['primary'])) {\r
+            $query.= ' PRIMARY KEY';\r
+        } elseif (!empty($definition['unique'])) {\r
+            $query.= ' UNIQUE';\r
+        } elseif (!empty($definition['foreign'])) {\r
+            $query.= ' FOREIGN KEY';\r
+        }\r
+        $fields = array();\r
+        foreach (array_keys($definition['fields']) as $field) {\r
+            $fields[] = $db->quoteIdentifier($field, true);\r
+        }\r
+        $query .= ' ('. implode(', ', $fields) . ')';\r
+        if (!empty($definition['foreign'])) {\r
+            $query.= ' REFERENCES ' . $db->quoteIdentifier($definition['references']['table'], true);\r
+            $referenced_fields = array();\r
+            foreach (array_keys($definition['references']['fields']) as $field) {\r
+                $referenced_fields[] = $db->quoteIdentifier($field, true);\r
+            }\r
+            $query .= ' ('. implode(', ', $referenced_fields) . ')';\r
+            $query .= $this->_getAdvancedFKOptions($definition);\r
+        }\r
+        return $db->exec($query);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ dropConstraint()\r
+\r
+    /**\r
+     * drop existing constraint\r
+     *\r
+     * @param string    $table        name of table that should be used in method\r
+     * @param string    $name         name of the constraint to be dropped\r
+     * @param string    $primary      hint if the constraint is primary\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function dropConstraint($table, $name, $primary = false)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $table = $db->quoteIdentifier($table, true);\r
+        $name = $db->quoteIdentifier($db->getIndexName($name), true);\r
+        return $db->exec("ALTER TABLE $table DROP CONSTRAINT $name");\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTableConstraints()\r
+\r
+    /**\r
+     * list all constraints in a table\r
+     *\r
+     * @param string $table name of table that should be used in method\r
+     * @return mixed array of constraint names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTableConstraints($table)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ createSequence()\r
+\r
+    /**\r
+     * create sequence\r
+     *\r
+     * @param string    $seq_name     name of the sequence to be created\r
+     * @param string    $start         start value of the sequence; default is 1\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function createSequence($seq_name, $start = 1)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ dropSequence()\r
+\r
+    /**\r
+     * drop existing sequence\r
+     *\r
+     * @param string    $seq_name     name of the sequence to be dropped\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function dropSequence($name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listSequences()\r
+\r
+    /**\r
+     * list all sequences in the current database\r
+     *\r
+     * @param string database, the current is default\r
+     *               NB: not all the drivers can get the sequence names from\r
+     *               a database other than the current one\r
+     * @return mixed array of sequence names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listSequences($database = null)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+}\r
 ?>
\ No newline at end of file
index 099ed48a84ffbb939face2c8c77f064daa99b486..8bcb338360499cf9e2671b4ffc1e0a6a72411c7d 100644 (file)
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: mysql.php,v 1.113 2008/11/23 20:30:29 quipo Exp $
-//
-
-require_once('MDB2/Driver/Manager/Common.php');
-
-/**
- * MDB2 MySQL driver for the management modules
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Manager_mysql extends MDB2_Driver_Manager_Common
-{
-
-    // }}}
-    // {{{ createDatabase()
-
-    /**
-     * create a new database
-     *
-     * @param string $name    name of the database that should be created
-     * @param array  $options array with charset, collation info
-     *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function createDatabase($name, $options = array())
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $name  = $db->quoteIdentifier($name, true);
-        $query = 'CREATE DATABASE ' . $name;
-        if (!empty($options['charset'])) {
-            $query .= ' DEFAULT CHARACTER SET ' . $db->quote($options['charset'], 'text');
-        }
-        if (!empty($options['collation'])) {
-            $query .= ' COLLATE ' . $db->quote($options['collation'], 'text');
-        }
-        return $db->standaloneQuery($query, null, true);
-    }
-
-    // }}}
-    // {{{ alterDatabase()
-
-    /**
-     * alter an existing database
-     *
-     * @param string $name    name of the database that is intended to be changed
-     * @param array  $options array with charset, collation info
-     *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function alterDatabase($name, $options = array())
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = 'ALTER DATABASE '. $db->quoteIdentifier($name, true);
-        if (!empty($options['charset'])) {
-            $query .= ' DEFAULT CHARACTER SET ' . $db->quote($options['charset'], 'text');
-        }
-        if (!empty($options['collation'])) {
-            $query .= ' COLLATE ' . $db->quote($options['collation'], 'text');
-        }
-        return $db->standaloneQuery($query, null, true);
-    }
-
-    // }}}
-    // {{{ dropDatabase()
-
-    /**
-     * drop an existing database
-     *
-     * @param string $name name of the database that should be dropped
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function dropDatabase($name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $name = $db->quoteIdentifier($name, true);
-        $query = "DROP DATABASE $name";
-        return $db->standaloneQuery($query, null, true);
-    }
-
-    // }}}
-    // {{{ _getAdvancedFKOptions()
-
-    /**
-     * Return the FOREIGN KEY query section dealing with non-standard options
-     * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
-     *
-     * @param array $definition
-     * @return string
-     * @access protected
-     */
-    function _getAdvancedFKOptions($definition)
-    {
-        $query = '';
-        if (!empty($definition['match'])) {
-            $query .= ' MATCH '.$definition['match'];
-        }
-        if (!empty($definition['onupdate'])) {
-            $query .= ' ON UPDATE '.$definition['onupdate'];
-        }
-        if (!empty($definition['ondelete'])) {
-            $query .= ' ON DELETE '.$definition['ondelete'];
-        }
-        return $query;
-    }
-
-    // }}}
-    // {{{ createTable()
-
-    /**
-     * create a new table
-     *
-     * @param string $name   Name of the database that should be created
-     * @param array $fields  Associative array that contains the definition of each field of the new table
-     *                       The indexes of the array entries are the names of the fields of the table an
-     *                       the array entry values are associative arrays like those that are meant to be
-     *                       passed with the field definitions to get[Type]Declaration() functions.
-     *                          array(
-     *                              'id' => array(
-     *                                  'type' => 'integer',
-     *                                  'unsigned' => 1
-     *                                  'notnull' => 1
-     *                                  'default' => 0
-     *                              ),
-     *                              'name' => array(
-     *                                  'type' => 'text',
-     *                                  'length' => 12
-     *                              ),
-     *                              'password' => array(
-     *                                  'type' => 'text',
-     *                                  'length' => 12
-     *                              )
-     *                          );
-     * @param array $options  An associative array of table options:
-     *                          array(
-     *                              'comment' => 'Foo',
-     *                              'charset' => 'utf8',
-     *                              'collate' => 'utf8_unicode_ci',
-     *                              'type'    => 'innodb',
-     *                          );
-     *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function createTable($name, $fields, $options = array())
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        // if we have an AUTO_INCREMENT column and a PK on more than one field,
-        // we have to handle it differently...
-        $autoincrement = null;
-        if (empty($options['primary'])) {
-            $pk_fields = array();
-            foreach ($fields as $fieldname => $def) {
-                if (!empty($def['primary'])) {
-                    $pk_fields[$fieldname] = true;
-                }
-                if (!empty($def['autoincrement'])) {
-                    $autoincrement = $fieldname;
-                }
-            }
-            if (!is_null($autoincrement) && count($pk_fields) > 1) {
-                $options['primary'] = $pk_fields;
-            } else {
-                // the PK constraint is on max one field => OK
-                $autoincrement = null;
-            }
-        }
-
-        $query = $this->_getCreateTableQuery($name, $fields, $options);
-        if (PEAR::isError($query)) {
-            return $query;
-        }
-
-        if (!is_null($autoincrement)) {
-            // we have to remove the PK clause added by _getIntegerDeclaration()
-            $query = str_replace('AUTO_INCREMENT PRIMARY KEY', 'AUTO_INCREMENT', $query);
-        }
-
-        $options_strings = array();
-
-        if (!empty($options['comment'])) {
-            $options_strings['comment'] = 'COMMENT = '.$db->quote($options['comment'], 'text');
-        }
-
-        if (!empty($options['charset'])) {
-            $options_strings['charset'] = 'DEFAULT CHARACTER SET '.$options['charset'];
-            if (!empty($options['collate'])) {
-                $options_strings['charset'].= ' COLLATE '.$options['collate'];
-            }
-        }
-
-        $type = false;
-        if (!empty($options['type'])) {
-            $type = $options['type'];
-        } elseif ($db->options['default_table_type']) {
-            $type = $db->options['default_table_type'];
-        }
-        if ($type) {
-            $options_strings[] = "ENGINE = $type";
-        }
-
-        if (!empty($options_strings)) {
-            $query .= ' '.implode(' ', $options_strings);
-        }
-        $result = $db->exec($query);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ dropTable()
-
-    /**
-     * drop an existing table
-     *
-     * @param string $name name of the table that should be dropped
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function dropTable($name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        //delete the triggers associated to existing FK constraints
-        $constraints = $this->listTableConstraints($name);
-        if (!PEAR::isError($constraints) && !empty($constraints)) {
-            $db->loadModule('Reverse', null, true);
-            foreach ($constraints as $constraint) {
-                $definition = $db->reverse->getTableConstraintDefinition($name, $constraint);
-                if (!PEAR::isError($definition) && !empty($definition['foreign'])) {
-                    $result = $this->_dropFKTriggers($name, $constraint, $definition['references']['table']);
-                    if (PEAR::isError($result)) {
-                        return $result;
-                    }
-                }
-            }
-        }
-
-        return parent::dropTable($name);
-    }
-
-    // }}}
-    // {{{ truncateTable()
-
-    /**
-     * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported,
-     * it falls back to a DELETE FROM TABLE query)
-     *
-     * @param string $name name of the table that should be truncated
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function truncateTable($name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $name = $db->quoteIdentifier($name, true);
-        return $db->exec("TRUNCATE TABLE $name");
-    }
-
-    // }}}
-    // {{{ vacuum()
-
-    /**
-     * Optimize (vacuum) all the tables in the db (or only the specified table)
-     * and optionally run ANALYZE.
-     *
-     * @param string $table table name (all the tables if empty)
-     * @param array  $options an array with driver-specific options:
-     *               - timeout [int] (in seconds) [mssql-only]
-     *               - analyze [boolean] [pgsql and mysql]
-     *               - full [boolean] [pgsql-only]
-     *               - freeze [boolean] [pgsql-only]
-     *
-     * @return mixed MDB2_OK success, a MDB2 error on failure
-     * @access public
-     */
-    function vacuum($table = null, $options = array())
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        if (empty($table)) {
-            $table = $this->listTables();
-            if (PEAR::isError($table)) {
-                return $table;
-            }
-        }
-        if (is_array($table)) {
-            foreach (array_keys($table) as $k) {
-               $table[$k] = $db->quoteIdentifier($table[$k], true);
-            }
-            $table = implode(', ', $table);
-        } else {
-            $table = $db->quoteIdentifier($table, true);
-        }
-        
-        $result = $db->exec('OPTIMIZE TABLE '.$table);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        if (!empty($options['analyze'])) {
-            return $db->exec('ANALYZE TABLE '.$table);
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ alterTable()
-
-    /**
-     * alter an existing table
-     *
-     * @param string $name         name of the table that is intended to be changed.
-     * @param array $changes     associative array that contains the details of each type
-     *                             of change that is intended to be performed. The types of
-     *                             changes that are currently supported are defined as follows:
-     *
-     *                             name
-     *
-     *                                New name for the table.
-     *
-     *                            add
-     *
-     *                                Associative array with the names of fields to be added as
-     *                                 indexes of the array. The value of each entry of the array
-     *                                 should be set to another associative array with the properties
-     *                                 of the fields to be added. The properties of the fields should
-     *                                 be the same as defined by the MDB2 parser.
-     *
-     *
-     *                            remove
-     *
-     *                                Associative array with the names of fields to be removed as indexes
-     *                                 of the array. Currently the values assigned to each entry are ignored.
-     *                                 An empty array should be used for future compatibility.
-     *
-     *                            rename
-     *
-     *                                Associative array with the names of fields to be renamed as indexes
-     *                                 of the array. The value of each entry of the array should be set to
-     *                                 another associative array with the entry named name with the new
-     *                                 field name and the entry named Declaration that is expected to contain
-     *                                 the portion of the field declaration already in DBMS specific SQL code
-     *                                 as it is used in the CREATE TABLE statement.
-     *
-     *                            change
-     *
-     *                                Associative array with the names of the fields to be changed as indexes
-     *                                 of the array. Keep in mind that if it is intended to change either the
-     *                                 name of a field and any other properties, the change array entries
-     *                                 should have the new names of the fields as array indexes.
-     *
-     *                                The value of each entry of the array should be set to another associative
-     *                                 array with the properties of the fields to that are meant to be changed as
-     *                                 array entries. These entries should be assigned to the new values of the
-     *                                 respective properties. The properties of the fields should be the same
-     *                                 as defined by the MDB2 parser.
-     *
-     *                            Example
-     *                                array(
-     *                                    'name' => 'userlist',
-     *                                    'add' => array(
-     *                                        'quota' => array(
-     *                                            'type' => 'integer',
-     *                                            'unsigned' => 1
-     *                                        )
-     *                                    ),
-     *                                    'remove' => array(
-     *                                        'file_limit' => array(),
-     *                                        'time_limit' => array()
-     *                                    ),
-     *                                    'change' => array(
-     *                                        'name' => array(
-     *                                            'length' => '20',
-     *                                            'definition' => array(
-     *                                                'type' => 'text',
-     *                                                'length' => 20,
-     *                                            ),
-     *                                        )
-     *                                    ),
-     *                                    'rename' => array(
-     *                                        'sex' => array(
-     *                                            'name' => 'gender',
-     *                                            'definition' => array(
-     *                                                'type' => 'text',
-     *                                                'length' => 1,
-     *                                                'default' => 'M',
-     *                                            ),
-     *                                        )
-     *                                    )
-     *                                )
-     *
-     * @param boolean $check     indicates whether the function should just check if the DBMS driver
-     *                             can perform the requested table alterations if the value is true or
-     *                             actually perform them otherwise.
-     * @access public
-     *
-      * @return mixed MDB2_OK on success, a MDB2 error on failure
-     */
-    function alterTable($name, $changes, $check)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        foreach ($changes as $change_name => $change) {
-            switch ($change_name) {
-            case 'add':
-            case 'remove':
-            case 'change':
-            case 'rename':
-            case 'name':
-                break;
-            default:
-                return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
-                    'change type "'.$change_name.'" not yet supported', __FUNCTION__);
-            }
-        }
-
-        if ($check) {
-            return MDB2_OK;
-        }
-
-        $query = '';
-        if (!empty($changes['name'])) {
-            $change_name = $db->quoteIdentifier($changes['name'], true);
-            $query .= 'RENAME TO ' . $change_name;
-        }
-
-        if (!empty($changes['add']) && is_array($changes['add'])) {
-            foreach ($changes['add'] as $field_name => $field) {
-                if ($query) {
-                    $query.= ', ';
-                }
-                $query.= 'ADD ' . $db->getDeclaration($field['type'], $field_name, $field);
-            }
-        }
-
-        if (!empty($changes['remove']) && is_array($changes['remove'])) {
-            foreach ($changes['remove'] as $field_name => $field) {
-                if ($query) {
-                    $query.= ', ';
-                }
-                $field_name = $db->quoteIdentifier($field_name, true);
-                $query.= 'DROP ' . $field_name;
-            }
-        }
-
-        $rename = array();
-        if (!empty($changes['rename']) && is_array($changes['rename'])) {
-            foreach ($changes['rename'] as $field_name => $field) {
-                $rename[$field['name']] = $field_name;
-            }
-        }
-
-        if (!empty($changes['change']) && is_array($changes['change'])) {
-            foreach ($changes['change'] as $field_name => $field) {
-                if ($query) {
-                    $query.= ', ';
-                }
-                if (isset($rename[$field_name])) {
-                    $old_field_name = $rename[$field_name];
-                    unset($rename[$field_name]);
-                } else {
-                    $old_field_name = $field_name;
-                }
-                $old_field_name = $db->quoteIdentifier($old_field_name, true);
-                $query.= "CHANGE $old_field_name " . $db->getDeclaration($field['definition']['type'], $field_name, $field['definition']);
-            }
-        }
-
-        if (!empty($rename) && is_array($rename)) {
-            foreach ($rename as $rename_name => $renamed_field) {
-                if ($query) {
-                    $query.= ', ';
-                }
-                $field = $changes['rename'][$renamed_field];
-                $renamed_field = $db->quoteIdentifier($renamed_field, true);
-                $query.= 'CHANGE ' . $renamed_field . ' ' . $db->getDeclaration($field['definition']['type'], $field['name'], $field['definition']);
-            }
-        }
-
-        if (!$query) {
-            return MDB2_OK;
-        }
-
-        $name = $db->quoteIdentifier($name, true);
-        return $db->exec("ALTER TABLE $name $query");
-    }
-
-    // }}}
-    // {{{ listDatabases()
-
-    /**
-     * list all databases
-     *
-     * @return mixed array of database names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listDatabases()
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $result = $db->queryCol('SHOW DATABASES');
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
-        }
-        return $result;
-    }
-
-    // }}}
-    // {{{ listUsers()
-
-    /**
-     * list all users
-     *
-     * @return mixed array of user names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listUsers()
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->queryCol('SELECT DISTINCT USER FROM mysql.USER');
-    }
-
-    // }}}
-    // {{{ listFunctions()
-
-    /**
-     * list all functions in the current database
-     *
-     * @return mixed array of function names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listFunctions()
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = "SELECT name FROM mysql.proc";
-        /*
-        SELECT ROUTINE_NAME
-          FROM INFORMATION_SCHEMA.ROUTINES
-         WHERE ROUTINE_TYPE = 'FUNCTION'
-        */
-        $result = $db->queryCol($query);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
-        }
-        return $result;
-    }
-
-    // }}}
-    // {{{ listTableTriggers()
-
-    /**
-     * list all triggers in the database that reference a given table
-     *
-     * @param string table for which all referenced triggers should be found
-     * @return mixed array of trigger names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTableTriggers($table = null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = 'SHOW TRIGGERS';
-        if (!is_null($table)) {
-            $table = $db->quote($table, 'text');
-            $query .= " LIKE $table";
-        }
-        $result = $db->queryCol($query);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
-        }
-        return $result;
-    }
-
-    // }}}
-    // {{{ listTables()
-
-    /**
-     * list all tables in the current database
-     *
-     * @param string database, the current is default
-     * @return mixed array of table names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTables($database = null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = "SHOW /*!50002 FULL*/ TABLES";
-        if (!is_null($database)) {
-            $query .= " FROM $database";
-        }
-        $query.= "/*!50002  WHERE Table_type = 'BASE TABLE'*/";
-
-        $table_names = $db->queryAll($query, null, MDB2_FETCHMODE_ORDERED);
-        if (PEAR::isError($table_names)) {
-            return $table_names;
-        }
-
-        $result = array();
-        foreach ($table_names as $table) {
-            if (!$this->_fixSequenceName($table[0], true)) {
-                $result[] = $table[0];
-            }
-        }
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
-        }
-        return $result;
-    }
-
-    // }}}
-    // {{{ listViews()
-
-    /**
-     * list all views in the current database
-     *
-     * @param string database, the current is default
-     * @return mixed array of view names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listViews($database = null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = 'SHOW FULL TABLES';
-        if (!is_null($database)) {
-            $query.= " FROM $database";
-        }
-        $query.= " WHERE Table_type = 'VIEW'";
-
-        $result = $db->queryCol($query);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
-        }
-        return $result;
-    }
-
-    // }}}
-    // {{{ listTableFields()
-
-    /**
-     * list all fields in a table in the current database
-     *
-     * @param string $table name of table that should be used in method
-     * @return mixed array of field names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTableFields($table)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $table = $db->quoteIdentifier($table, true);
-        $result = $db->queryCol("SHOW COLUMNS FROM $table");
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
-        }
-        return $result;
-    }
-
-    // }}}
-    // {{{ createIndex()
-
-    /**
-     * Get the stucture of a field into an array
-     *
-     * @author Leoncx
-     * @param string $table      name of the table on which the index is to be created
-     * @param string $name       name of the index to be created
-     * @param array  $definition associative array that defines properties of the index to be created.
-     *                           Currently, only one property named FIELDS is supported. This property
-     *                           is also an associative with the names of the index fields as array
-     *                           indexes. Each entry of this array is set to another type of associative
-     *                           array that specifies properties of the index that are specific to
-     *                           each field.
-     *
-     *                           Currently, only the sorting property is supported. It should be used
-     *                           to define the sorting direction of the index. It may be set to either
-     *                           ascending or descending.
-     *
-     *                           Not all DBMS support index sorting direction configuration. The DBMS
-     *                           drivers of those that do not support it ignore this property. Use the
-     *                           function supports() to determine whether the DBMS driver can manage indexes.
-     *
-     *                           Example
-     *                               array(
-     *                                   'fields' => array(
-     *                                       'user_name' => array(
-     *                                           'sorting' => 'ascending'
-     *                                           'length' => 10
-     *                                       ),
-     *                                       'last_login' => array()
-     *                                    )
-     *                                )
-     *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function createIndex($table, $name, $definition)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $table = $db->quoteIdentifier($table, true);
-        $name = $db->quoteIdentifier($db->getIndexName($name), true);
-        $query = "CREATE INDEX $name ON $table";
-        $fields = array();
-        foreach ($definition['fields'] as $field => $fieldinfo) {
-            if (!empty($fieldinfo['length'])) {
-                $fields[] = $db->quoteIdentifier($field, true) . '(' . $fieldinfo['length'] . ')';
-            } else {
-                $fields[] = $db->quoteIdentifier($field, true);
-            }
-        }
-        $query .= ' ('. implode(', ', $fields) . ')';
-        return $db->exec($query);
-    }
-
-    // }}}
-    // {{{ dropIndex()
-
-    /**
-     * drop existing index
-     *
-     * @param string    $table         name of table that should be used in method
-     * @param string    $name         name of the index to be dropped
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function dropIndex($table, $name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $table = $db->quoteIdentifier($table, true);
-        $name = $db->quoteIdentifier($db->getIndexName($name), true);
-        return $db->exec("DROP INDEX $name ON $table");
-    }
-
-    // }}}
-    // {{{ listTableIndexes()
-
-    /**
-     * list all indexes in a table
-     *
-     * @param string $table name of table that should be used in method
-     * @return mixed array of index names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTableIndexes($table)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $key_name = 'Key_name';
-        $non_unique = 'Non_unique';
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            if ($db->options['field_case'] == CASE_LOWER) {
-                $key_name = strtolower($key_name);
-                $non_unique = strtolower($non_unique);
-            } else {
-                $key_name = strtoupper($key_name);
-                $non_unique = strtoupper($non_unique);
-            }
-        }
-
-        $table = $db->quoteIdentifier($table, true);
-        $query = "SHOW INDEX FROM $table";
-        $indexes = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);
-        if (PEAR::isError($indexes)) {
-            return $indexes;
-        }
-
-        $result = array();
-        foreach ($indexes as $index_data) {
-            if ($index_data[$non_unique] && ($index = $this->_fixIndexName($index_data[$key_name]))) {
-                $result[$index] = true;
-            }
-        }
-
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_change_key_case($result, $db->options['field_case']);
-        }
-        return array_keys($result);
-    }
-
-    // }}}
-    // {{{ createConstraint()
-
-    /**
-     * create a constraint on a table
-     *
-     * @param string    $table        name of the table on which the constraint is to be created
-     * @param string    $name         name of the constraint to be created
-     * @param array     $definition   associative array that defines properties of the constraint to be created.
-     *                                Currently, only one property named FIELDS is supported. This property
-     *                                is also an associative with the names of the constraint fields as array
-     *                                constraints. Each entry of this array is set to another type of associative
-     *                                array that specifies properties of the constraint that are specific to
-     *                                each field.
-     *
-     *                                Example
-     *                                   array(
-     *                                       'fields' => array(
-     *                                           'user_name' => array(),
-     *                                           'last_login' => array()
-     *                                       )
-     *                                   )
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function createConstraint($table, $name, $definition)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $type = '';
-        $idx_name = $db->quoteIdentifier($db->getIndexName($name), true);
-        if (!empty($definition['primary'])) {
-            $type = 'PRIMARY';
-            $idx_name = 'KEY';
-        } elseif (!empty($definition['unique'])) {
-            $type = 'UNIQUE';
-        } elseif (!empty($definition['foreign'])) {
-            $type = 'CONSTRAINT';
-        }
-        if (empty($type)) {
-            return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                'invalid definition, could not create constraint', __FUNCTION__);
-        }
-
-        $table_quoted = $db->quoteIdentifier($table, true);
-        $query = "ALTER TABLE $table_quoted ADD $type $idx_name";
-        if (!empty($definition['foreign'])) {
-            $query .= ' FOREIGN KEY';
-        }
-        $fields = array();
-        foreach ($definition['fields'] as $field => $fieldinfo) {
-            $quoted = $db->quoteIdentifier($field, true);
-            if (!empty($fieldinfo['length'])) {
-                $quoted .= '(' . $fieldinfo['length'] . ')';
-            }
-            $fields[] = $quoted;
-        }
-        $query .= ' ('. implode(', ', $fields) . ')';
-        if (!empty($definition['foreign'])) {
-            $query.= ' REFERENCES ' . $db->quoteIdentifier($definition['references']['table'], true);
-            $referenced_fields = array();
-            foreach (array_keys($definition['references']['fields']) as $field) {
-                $referenced_fields[] = $db->quoteIdentifier($field, true);
-            }
-            $query .= ' ('. implode(', ', $referenced_fields) . ')';
-            $query .= $this->_getAdvancedFKOptions($definition);
-
-            // add index on FK column(s) or we can't add a FK constraint
-            // @see http://forums.mysql.com/read.php?22,19755,226009
-            $result = $this->createIndex($table, $name.'_fkidx', $definition);
-            if (PEAR::isError($result)) {
-                return $result;
-            }
-        }
-        $res = $db->exec($query);
-        if (PEAR::isError($res)) {
-            return $res;
-        }
-        if (!empty($definition['foreign'])) {
-            return $this->_createFKTriggers($table, array($name => $definition));
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ dropConstraint()
-
-    /**
-     * drop existing constraint
-     *
-     * @param string    $table        name of table that should be used in method
-     * @param string    $name         name of the constraint to be dropped
-     * @param string    $primary      hint if the constraint is primary
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function dropConstraint($table, $name, $primary = false)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        if ($primary || strtolower($name) == 'primary') {
-            $query = 'ALTER TABLE '. $db->quoteIdentifier($table, true) .' DROP PRIMARY KEY';
-            return $db->exec($query);
-        }
-
-        //is it a FK constraint? If so, also delete the associated triggers
-        $db->loadModule('Reverse', null, true);
-        $definition = $db->reverse->getTableConstraintDefinition($table, $name);
-        if (!PEAR::isError($definition) && !empty($definition['foreign'])) {
-            //first drop the FK enforcing triggers
-            $result = $this->_dropFKTriggers($table, $name, $definition['references']['table']);
-            if (PEAR::isError($result)) {
-                return $result;
-            }
-            //then drop the constraint itself
-            $table = $db->quoteIdentifier($table, true);
-            $name = $db->quoteIdentifier($db->getIndexName($name), true);
-            $query = "ALTER TABLE $table DROP FOREIGN KEY $name";
-            return $db->exec($query);
-        }
-
-        $table = $db->quoteIdentifier($table, true);
-        $name = $db->quoteIdentifier($db->getIndexName($name), true);
-        $query = "ALTER TABLE $table DROP INDEX $name";
-        return $db->exec($query);
-    }
-
-    // }}}
-    // {{{ _createFKTriggers()
-
-    /**
-     * Create triggers to enforce the FOREIGN KEY constraint on the table
-     *
-     * NB: since there's no RAISE_APPLICATION_ERROR facility in mysql,
-     * we call a non-existent procedure to raise the FK violation message.
-     * @see http://forums.mysql.com/read.php?99,55108,71877#msg-71877
-     *
-     * @param string $table        table name
-     * @param array  $foreign_keys FOREIGN KEY definitions
-     *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access private
-     */
-    function _createFKTriggers($table, $foreign_keys)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-        // create triggers to enforce FOREIGN KEY constraints
-        if ($db->supports('triggers') && !empty($foreign_keys)) {
-            $table_quoted = $db->quoteIdentifier($table, true);
-            foreach ($foreign_keys as $fkname => $fkdef) {
-                if (empty($fkdef)) {
-                    continue;
-                }
-                //set actions to default if not set
-                $fkdef['onupdate'] = empty($fkdef['onupdate']) ? $db->options['default_fk_action_onupdate'] : strtoupper($fkdef['onupdate']);
-                $fkdef['ondelete'] = empty($fkdef['ondelete']) ? $db->options['default_fk_action_ondelete'] : strtoupper($fkdef['ondelete']);
-
-                $trigger_names = array(
-                    'insert'    => $fkname.'_insert_trg',
-                    'update'    => $fkname.'_update_trg',
-                    'pk_update' => $fkname.'_pk_update_trg',
-                    'pk_delete' => $fkname.'_pk_delete_trg',
-                );
-                $table_fields = array_keys($fkdef['fields']);
-                $referenced_fields = array_keys($fkdef['references']['fields']);
-
-                //create the ON [UPDATE|DELETE] triggers on the primary table
-                $restrict_action = ' IF (SELECT ';
-                $aliased_fields = array();
-                foreach ($table_fields as $field) {
-                    $aliased_fields[] = $table_quoted .'.'.$field .' AS '.$field;
-                }
-                $restrict_action .= implode(',', $aliased_fields)
-                       .' FROM '.$table_quoted
-                       .' WHERE ';
-                $conditions  = array();
-                $new_values  = array();
-                $null_values = array();
-                for ($i=0; $i<count($table_fields); $i++) {
-                    $conditions[]  = $table_fields[$i] .' = OLD.'.$referenced_fields[$i];
-                    $new_values[]  = $table_fields[$i] .' = NEW.'.$referenced_fields[$i];
-                    $null_values[] = $table_fields[$i] .' = NULL';
-                }
-                $conditions2 = array();
-                for ($i=0; $i<count($referenced_fields); $i++) {
-                    $conditions2[]  = 'NEW.'.$referenced_fields[$i] .' <> OLD.'.$referenced_fields[$i];
-                }
-                $restrict_action .= implode(' AND ', $conditions).') IS NOT NULL'
-                                .' AND (' .implode(' OR ', $conditions2) .')'
-                                .' THEN CALL %s_ON_TABLE_'.$table.'_VIOLATES_FOREIGN_KEY_CONSTRAINT();'
-                                .' END IF;';
-
-                $cascade_action_update = 'UPDATE '.$table_quoted.' SET '.implode(', ', $new_values) .' WHERE '.implode(' AND ', $conditions). ';';
-                $cascade_action_delete = 'DELETE FROM '.$table_quoted.' WHERE '.implode(' AND ', $conditions). ';';
-                $setnull_action        = 'UPDATE '.$table_quoted.' SET '.implode(', ', $null_values).' WHERE '.implode(' AND ', $conditions). ';';
-
-                if ('SET DEFAULT' == $fkdef['onupdate'] || 'SET DEFAULT' == $fkdef['ondelete']) {
-                    $db->loadModule('Reverse', null, true);
-                    $default_values = array();
-                    foreach ($table_fields as $table_field) {
-                        $field_definition = $db->reverse->getTableFieldDefinition($table, $field);
-                        if (PEAR::isError($field_definition)) {
-                            return $field_definition;
-                        }
-                        $default_values[] = $table_field .' = '. $field_definition[0]['default'];
-                    }
-                    $setdefault_action = 'UPDATE '.$table_quoted.' SET '.implode(', ', $default_values).' WHERE '.implode(' AND ', $conditions). ';';
-                }
-
-                $query = 'CREATE TRIGGER %s'
-                        .' %s ON '.$fkdef['references']['table']
-                        .' FOR EACH ROW BEGIN '
-                        .' SET FOREIGN_KEY_CHECKS = 0; ';  //only really needed for ON UPDATE CASCADE
-
-                if ('CASCADE' == $fkdef['onupdate']) {
-                    $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE',  'update') . $cascade_action_update;
-                } elseif ('SET NULL' == $fkdef['onupdate']) {
-                    $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setnull_action;
-                } elseif ('SET DEFAULT' == $fkdef['onupdate']) {
-                    $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setdefault_action;
-                } elseif ('NO ACTION' == $fkdef['onupdate']) {
-                    $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'AFTER UPDATE', 'update');
-                } elseif ('RESTRICT' == $fkdef['onupdate']) {
-                    $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update');
-                }
-                if ('CASCADE' == $fkdef['ondelete']) {
-                    $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE',  'delete') . $cascade_action_delete;
-                } elseif ('SET NULL' == $fkdef['ondelete']) {
-                    $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setnull_action;
-                } elseif ('SET DEFAULT' == $fkdef['ondelete']) {
-                    $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setdefault_action;
-                } elseif ('NO ACTION' == $fkdef['ondelete']) {
-                    $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete');
-                } elseif ('RESTRICT' == $fkdef['ondelete']) {
-                    $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete');
-                }
-                $sql_update .= ' SET FOREIGN_KEY_CHECKS = 1; END;';
-                $sql_delete .= ' SET FOREIGN_KEY_CHECKS = 1; END;';
-
-                $db->pushErrorHandling(PEAR_ERROR_RETURN);
-                $db->expectError(MDB2_ERROR_CANNOT_CREATE);
-                $result = $db->exec($sql_delete);
-                $expected_errmsg = 'This MySQL version doesn\'t support multiple triggers with the same action time and event for one table';
-                $db->popExpect();
-                $db->popErrorHandling();
-                if (PEAR::isError($result)) {
-                    if ($result->getCode() != MDB2_ERROR_CANNOT_CREATE) {
-                        return $result;
-                    }
-                    $db->warnings[] = $expected_errmsg;
-                }
-                $db->pushErrorHandling(PEAR_ERROR_RETURN);
-                $db->expectError(MDB2_ERROR_CANNOT_CREATE);
-                $result = $db->exec($sql_update);
-                $db->popExpect();
-                $db->popErrorHandling();
-                if (PEAR::isError($result) && $result->getCode() != MDB2_ERROR_CANNOT_CREATE) {
-                    if ($result->getCode() != MDB2_ERROR_CANNOT_CREATE) {
-                        return $result;
-                    }
-                    $db->warnings[] = $expected_errmsg;
-                }
-            }
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ _dropFKTriggers()
-
-    /**
-     * Drop the triggers created to enforce the FOREIGN KEY constraint on the table
-     *
-     * @param string $table            table name
-     * @param string $fkname           FOREIGN KEY constraint name
-     * @param string $referenced_table referenced table name
-     *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access private
-     */
-    function _dropFKTriggers($table, $fkname, $referenced_table)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $triggers  = $this->listTableTriggers($table);
-        $triggers2 = $this->listTableTriggers($referenced_table);
-        if (!PEAR::isError($triggers2) && !PEAR::isError($triggers)) {
-            $triggers = array_merge($triggers, $triggers2);
-            $pattern = '/^'.$fkname.'(_pk)?_(insert|update|delete)_trg$/i';
-            foreach ($triggers as $trigger) {
-                if (preg_match($pattern, $trigger)) {
-                    $result = $db->exec('DROP TRIGGER '.$trigger);
-                    if (PEAR::isError($result)) {
-                        return $result;
-                    }
-                }
-            }
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ listTableConstraints()
-
-    /**
-     * list all constraints in a table
-     *
-     * @param string $table name of table that should be used in method
-     * @return mixed array of constraint names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTableConstraints($table)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $key_name = 'Key_name';
-        $non_unique = 'Non_unique';
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            if ($db->options['field_case'] == CASE_LOWER) {
-                $key_name = strtolower($key_name);
-                $non_unique = strtolower($non_unique);
-            } else {
-                $key_name = strtoupper($key_name);
-                $non_unique = strtoupper($non_unique);
-            }
-        }
-
-        $query = 'SHOW INDEX FROM ' . $db->quoteIdentifier($table, true);
-        $indexes = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);
-        if (PEAR::isError($indexes)) {
-            return $indexes;
-        }
-
-        $result = array();
-        foreach ($indexes as $index_data) {
-            if (!$index_data[$non_unique]) {
-                if ($index_data[$key_name] !== 'PRIMARY') {
-                    $index = $this->_fixIndexName($index_data[$key_name]);
-                } else {
-                    $index = 'PRIMARY';
-                }
-                if (!empty($index)) {
-                    $result[$index] = true;
-                }
-            }
-        }
-        
-        //list FOREIGN KEY constraints...
-        $query = 'SHOW CREATE TABLE '. $db->escape($table);
-        $definition = $db->queryOne($query, 'text', 1);
-        if (!PEAR::isError($definition) && !empty($definition)) {
-            $pattern = '/\bCONSTRAINT\b\s+([^\s]+)\s+\bFOREIGN KEY\b/Uims';
-            if (preg_match_all($pattern, str_replace('`', '', $definition), $matches) > 0) {
-                foreach ($matches[1] as $constraint) {
-                    $result[$constraint] = true;
-                }
-            }
-        }
-
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_change_key_case($result, $db->options['field_case']);
-        }
-        return array_keys($result);
-    }
-
-    // }}}
-    // {{{ createSequence()
-
-    /**
-     * create sequence
-     *
-     * @param string    $seq_name name of the sequence to be created
-     * @param string    $start    start value of the sequence; default is 1
-     * @param array     $options  An associative array of table options:
-     *                          array(
-     *                              'comment' => 'Foo',
-     *                              'charset' => 'utf8',
-     *                              'collate' => 'utf8_unicode_ci',
-     *                              'type'    => 'innodb',
-     *                          );
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function createSequence($seq_name, $start = 1, $options = array())
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
-        $seqcol_name = $db->quoteIdentifier($db->options['seqcol_name'], true);
-        
-        $options_strings = array();
-
-        if (!empty($options['comment'])) {
-            $options_strings['comment'] = 'COMMENT = '.$db->quote($options['comment'], 'text');
-        }
-
-        if (!empty($options['charset'])) {
-            $options_strings['charset'] = 'DEFAULT CHARACTER SET '.$options['charset'];
-            if (!empty($options['collate'])) {
-                $options_strings['charset'].= ' COLLATE '.$options['collate'];
-            }
-        }
-
-        $type = false;
-        if (!empty($options['type'])) {
-            $type = $options['type'];
-        } elseif ($db->options['default_table_type']) {
-            $type = $db->options['default_table_type'];
-        }
-        if ($type) {
-            $options_strings[] = "ENGINE = $type";
-        }
-
-        $query = "CREATE TABLE $sequence_name ($seqcol_name INT NOT NULL AUTO_INCREMENT, PRIMARY KEY ($seqcol_name))";
-        if (!empty($options_strings)) {
-            $query .= ' '.implode(' ', $options_strings);
-        }
-        $res = $db->exec($query);
-        if (PEAR::isError($res)) {
-            return $res;
-        }
-
-        if ($start == 1) {
-            return MDB2_OK;
-        }
-
-        $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (".($start-1).')';
-        $res = $db->exec($query);
-        if (!PEAR::isError($res)) {
-            return MDB2_OK;
-        }
-
-        // Handle error
-        $result = $db->exec("DROP TABLE $sequence_name");
-        if (PEAR::isError($result)) {
-            return $db->raiseError($result, null, null,
-                'could not drop inconsistent sequence table', __FUNCTION__);
-        }
-
-        return $db->raiseError($res, null, null,
-            'could not create sequence table', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ dropSequence()
-
-    /**
-     * drop existing sequence
-     *
-     * @param string    $seq_name     name of the sequence to be dropped
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function dropSequence($seq_name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
-        return $db->exec("DROP TABLE $sequence_name");
-    }
-
-    // }}}
-    // {{{ listSequences()
-
-    /**
-     * list all sequences in the current database
-     *
-     * @param string database, the current is default
-     * @return mixed array of sequence names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listSequences($database = null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = "SHOW TABLES";
-        if (!is_null($database)) {
-            $query .= " FROM $database";
-        }
-        $table_names = $db->queryCol($query);
-        if (PEAR::isError($table_names)) {
-            return $table_names;
-        }
-
-        $result = array();
-        foreach ($table_names as $table_name) {
-            if ($sqn = $this->_fixSequenceName($table_name, true)) {
-                $result[] = $sqn;
-            }
-        }
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
-        }
-        return $result;
-    }
-
-    // }}}
-}
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: mysql.php 302865 2010-08-29 10:30:55Z quipo $\r
+//\r
+\r
+require_once 'MDB2/Driver/Manager/Common.php';\r
+\r
+/**\r
+ * MDB2 MySQL driver for the management modules\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Driver_Manager_mysql extends MDB2_Driver_Manager_Common\r
+{\r
+\r
+    // }}}\r
+    // {{{ createDatabase()\r
+\r
+    /**\r
+     * create a new database\r
+     *\r
+     * @param string $name    name of the database that should be created\r
+     * @param array  $options array with charset, collation info\r
+     *\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function createDatabase($name, $options = array())\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $name  = $db->quoteIdentifier($name, true);\r
+        $query = 'CREATE DATABASE ' . $name;\r
+        if (!empty($options['charset'])) {\r
+            $query .= ' DEFAULT CHARACTER SET ' . $db->quote($options['charset'], 'text');\r
+        }\r
+        if (!empty($options['collation'])) {\r
+            $query .= ' COLLATE ' . $db->quote($options['collation'], 'text');\r
+        }\r
+        return $db->standaloneQuery($query, null, true);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ alterDatabase()\r
+\r
+    /**\r
+     * alter an existing database\r
+     *\r
+     * @param string $name    name of the database that is intended to be changed\r
+     * @param array  $options array with charset, collation info\r
+     *\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function alterDatabase($name, $options = array())\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = 'ALTER DATABASE '. $db->quoteIdentifier($name, true);\r
+        if (!empty($options['charset'])) {\r
+            $query .= ' DEFAULT CHARACTER SET ' . $db->quote($options['charset'], 'text');\r
+        }\r
+        if (!empty($options['collation'])) {\r
+            $query .= ' COLLATE ' . $db->quote($options['collation'], 'text');\r
+        }\r
+        return $db->standaloneQuery($query, null, true);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ dropDatabase()\r
+\r
+    /**\r
+     * drop an existing database\r
+     *\r
+     * @param string $name name of the database that should be dropped\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function dropDatabase($name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $name = $db->quoteIdentifier($name, true);\r
+        $query = "DROP DATABASE $name";\r
+        return $db->standaloneQuery($query, null, true);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getAdvancedFKOptions()\r
+\r
+    /**\r
+     * Return the FOREIGN KEY query section dealing with non-standard options\r
+     * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...\r
+     *\r
+     * @param array $definition\r
+     * @return string\r
+     * @access protected\r
+     */\r
+    function _getAdvancedFKOptions($definition)\r
+    {\r
+        $query = '';\r
+        if (!empty($definition['match'])) {\r
+            $query .= ' MATCH '.$definition['match'];\r
+        }\r
+        if (!empty($definition['onupdate'])) {\r
+            $query .= ' ON UPDATE '.$definition['onupdate'];\r
+        }\r
+        if (!empty($definition['ondelete'])) {\r
+            $query .= ' ON DELETE '.$definition['ondelete'];\r
+        }\r
+        return $query;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ createTable()\r
+\r
+    /**\r
+     * create a new table\r
+     *\r
+     * @param string $name   Name of the database that should be created\r
+     * @param array $fields  Associative array that contains the definition of each field of the new table\r
+     *                       The indexes of the array entries are the names of the fields of the table an\r
+     *                       the array entry values are associative arrays like those that are meant to be\r
+     *                       passed with the field definitions to get[Type]Declaration() functions.\r
+     *                          array(\r
+     *                              'id' => array(\r
+     *                                  'type' => 'integer',\r
+     *                                  'unsigned' => 1\r
+     *                                  'notnull' => 1\r
+     *                                  'default' => 0\r
+     *                              ),\r
+     *                              'name' => array(\r
+     *                                  'type' => 'text',\r
+     *                                  'length' => 12\r
+     *                              ),\r
+     *                              'password' => array(\r
+     *                                  'type' => 'text',\r
+     *                                  'length' => 12\r
+     *                              )\r
+     *                          );\r
+     * @param array $options  An associative array of table options:\r
+     *                          array(\r
+     *                              'comment' => 'Foo',\r
+     *                              'charset' => 'utf8',\r
+     *                              'collate' => 'utf8_unicode_ci',\r
+     *                              'type'    => 'innodb',\r
+     *                          );\r
+     *\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function createTable($name, $fields, $options = array())\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        // if we have an AUTO_INCREMENT column and a PK on more than one field,\r
+        // we have to handle it differently...\r
+        $autoincrement = null;\r
+        if (empty($options['primary'])) {\r
+            $pk_fields = array();\r
+            foreach ($fields as $fieldname => $def) {\r
+                if (!empty($def['primary'])) {\r
+                    $pk_fields[$fieldname] = true;\r
+                }\r
+                if (!empty($def['autoincrement'])) {\r
+                    $autoincrement = $fieldname;\r
+                }\r
+            }\r
+            if ((null !== $autoincrement) && count($pk_fields) > 1) {\r
+                $options['primary'] = $pk_fields;\r
+            } else {\r
+                // the PK constraint is on max one field => OK\r
+                $autoincrement = null;\r
+            }\r
+        }\r
+\r
+        $query = $this->_getCreateTableQuery($name, $fields, $options);\r
+        if (PEAR::isError($query)) {\r
+            return $query;\r
+        }\r
+\r
+        if (null !== $autoincrement) {\r
+            // we have to remove the PK clause added by _getIntegerDeclaration()\r
+            $query = str_replace('AUTO_INCREMENT PRIMARY KEY', 'AUTO_INCREMENT', $query);\r
+        }\r
+\r
+        $options_strings = array();\r
+\r
+        if (!empty($options['comment'])) {\r
+            $options_strings['comment'] = 'COMMENT = '.$db->quote($options['comment'], 'text');\r
+        }\r
+\r
+        if (!empty($options['charset'])) {\r
+            $options_strings['charset'] = 'DEFAULT CHARACTER SET '.$options['charset'];\r
+            if (!empty($options['collate'])) {\r
+                $options_strings['charset'].= ' COLLATE '.$options['collate'];\r
+            }\r
+        }\r
+\r
+        $type = false;\r
+        if (!empty($options['type'])) {\r
+            $type = $options['type'];\r
+        } elseif ($db->options['default_table_type']) {\r
+            $type = $db->options['default_table_type'];\r
+        }\r
+        if ($type) {\r
+            $options_strings[] = "ENGINE = $type";\r
+        }\r
+\r
+        if (!empty($options_strings)) {\r
+            $query .= ' '.implode(' ', $options_strings);\r
+        }\r
+        $result = $db->exec($query);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ dropTable()\r
+\r
+    /**\r
+     * drop an existing table\r
+     *\r
+     * @param string $name name of the table that should be dropped\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function dropTable($name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        //delete the triggers associated to existing FK constraints\r
+        $constraints = $this->listTableConstraints($name);\r
+        if (!PEAR::isError($constraints) && !empty($constraints)) {\r
+            $db->loadModule('Reverse', null, true);\r
+            foreach ($constraints as $constraint) {\r
+                $definition = $db->reverse->getTableConstraintDefinition($name, $constraint);\r
+                if (!PEAR::isError($definition) && !empty($definition['foreign'])) {\r
+                    $result = $this->_dropFKTriggers($name, $constraint, $definition['references']['table']);\r
+                    if (PEAR::isError($result)) {\r
+                        return $result;\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+        return parent::dropTable($name);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ truncateTable()\r
+\r
+    /**\r
+     * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported,\r
+     * it falls back to a DELETE FROM TABLE query)\r
+     *\r
+     * @param string $name name of the table that should be truncated\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function truncateTable($name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $name = $db->quoteIdentifier($name, true);\r
+        return $db->exec("TRUNCATE TABLE $name");\r
+    }\r
+\r
+    // }}}\r
+    // {{{ vacuum()\r
+\r
+    /**\r
+     * Optimize (vacuum) all the tables in the db (or only the specified table)\r
+     * and optionally run ANALYZE.\r
+     *\r
+     * @param string $table table name (all the tables if empty)\r
+     * @param array  $options an array with driver-specific options:\r
+     *               - timeout [int] (in seconds) [mssql-only]\r
+     *               - analyze [boolean] [pgsql and mysql]\r
+     *               - full [boolean] [pgsql-only]\r
+     *               - freeze [boolean] [pgsql-only]\r
+     *\r
+     * @return mixed MDB2_OK success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function vacuum($table = null, $options = array())\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        if (empty($table)) {\r
+            $table = $this->listTables();\r
+            if (PEAR::isError($table)) {\r
+                return $table;\r
+            }\r
+        }\r
+        if (is_array($table)) {\r
+            foreach (array_keys($table) as $k) {\r
+               $table[$k] = $db->quoteIdentifier($table[$k], true);\r
+            }\r
+            $table = implode(', ', $table);\r
+        } else {\r
+            $table = $db->quoteIdentifier($table, true);\r
+        }\r
+        \r
+        $result = $db->exec('OPTIMIZE TABLE '.$table);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        if (!empty($options['analyze'])) {\r
+            return $db->exec('ANALYZE TABLE '.$table);\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ alterTable()\r
+\r
+    /**\r
+     * alter an existing table\r
+     *\r
+     * @param string $name         name of the table that is intended to be changed.\r
+     * @param array $changes     associative array that contains the details of each type\r
+     *                             of change that is intended to be performed. The types of\r
+     *                             changes that are currently supported are defined as follows:\r
+     *\r
+     *                             name\r
+     *\r
+     *                                New name for the table.\r
+     *\r
+     *                            add\r
+     *\r
+     *                                Associative array with the names of fields to be added as\r
+     *                                 indexes of the array. The value of each entry of the array\r
+     *                                 should be set to another associative array with the properties\r
+     *                                 of the fields to be added. The properties of the fields should\r
+     *                                 be the same as defined by the MDB2 parser.\r
+     *\r
+     *\r
+     *                            remove\r
+     *\r
+     *                                Associative array with the names of fields to be removed as indexes\r
+     *                                 of the array. Currently the values assigned to each entry are ignored.\r
+     *                                 An empty array should be used for future compatibility.\r
+     *\r
+     *                            rename\r
+     *\r
+     *                                Associative array with the names of fields to be renamed as indexes\r
+     *                                 of the array. The value of each entry of the array should be set to\r
+     *                                 another associative array with the entry named name with the new\r
+     *                                 field name and the entry named Declaration that is expected to contain\r
+     *                                 the portion of the field declaration already in DBMS specific SQL code\r
+     *                                 as it is used in the CREATE TABLE statement.\r
+     *\r
+     *                            change\r
+     *\r
+     *                                Associative array with the names of the fields to be changed as indexes\r
+     *                                 of the array. Keep in mind that if it is intended to change either the\r
+     *                                 name of a field and any other properties, the change array entries\r
+     *                                 should have the new names of the fields as array indexes.\r
+     *\r
+     *                                The value of each entry of the array should be set to another associative\r
+     *                                 array with the properties of the fields to that are meant to be changed as\r
+     *                                 array entries. These entries should be assigned to the new values of the\r
+     *                                 respective properties. The properties of the fields should be the same\r
+     *                                 as defined by the MDB2 parser.\r
+     *\r
+     *                            Example\r
+     *                                array(\r
+     *                                    'name' => 'userlist',\r
+     *                                    'add' => array(\r
+     *                                        'quota' => array(\r
+     *                                            'type' => 'integer',\r
+     *                                            'unsigned' => 1\r
+     *                                        )\r
+     *                                    ),\r
+     *                                    'remove' => array(\r
+     *                                        'file_limit' => array(),\r
+     *                                        'time_limit' => array()\r
+     *                                    ),\r
+     *                                    'change' => array(\r
+     *                                        'name' => array(\r
+     *                                            'length' => '20',\r
+     *                                            'definition' => array(\r
+     *                                                'type' => 'text',\r
+     *                                                'length' => 20,\r
+     *                                            ),\r
+     *                                        )\r
+     *                                    ),\r
+     *                                    'rename' => array(\r
+     *                                        'sex' => array(\r
+     *                                            'name' => 'gender',\r
+     *                                            'definition' => array(\r
+     *                                                'type' => 'text',\r
+     *                                                'length' => 1,\r
+     *                                                'default' => 'M',\r
+     *                                            ),\r
+     *                                        )\r
+     *                                    )\r
+     *                                )\r
+     *\r
+     * @param boolean $check     indicates whether the function should just check if the DBMS driver\r
+     *                             can perform the requested table alterations if the value is true or\r
+     *                             actually perform them otherwise.\r
+     * @access public\r
+     *\r
+      * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     */\r
+    function alterTable($name, $changes, $check)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        foreach ($changes as $change_name => $change) {\r
+            switch ($change_name) {\r
+            case 'add':\r
+            case 'remove':\r
+            case 'change':\r
+            case 'rename':\r
+            case 'name':\r
+                break;\r
+            default:\r
+                return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,\r
+                    'change type "'.$change_name.'" not yet supported', __FUNCTION__);\r
+            }\r
+        }\r
+\r
+        if ($check) {\r
+            return MDB2_OK;\r
+        }\r
+\r
+        $query = '';\r
+        if (!empty($changes['name'])) {\r
+            $change_name = $db->quoteIdentifier($changes['name'], true);\r
+            $query .= 'RENAME TO ' . $change_name;\r
+        }\r
+\r
+        if (!empty($changes['add']) && is_array($changes['add'])) {\r
+            foreach ($changes['add'] as $field_name => $field) {\r
+                if ($query) {\r
+                    $query.= ', ';\r
+                }\r
+                $query.= 'ADD ' . $db->getDeclaration($field['type'], $field_name, $field);\r
+            }\r
+        }\r
+\r
+        if (!empty($changes['remove']) && is_array($changes['remove'])) {\r
+            foreach ($changes['remove'] as $field_name => $field) {\r
+                if ($query) {\r
+                    $query.= ', ';\r
+                }\r
+                $field_name = $db->quoteIdentifier($field_name, true);\r
+                $query.= 'DROP ' . $field_name;\r
+            }\r
+        }\r
+\r
+        $rename = array();\r
+        if (!empty($changes['rename']) && is_array($changes['rename'])) {\r
+            foreach ($changes['rename'] as $field_name => $field) {\r
+                $rename[$field['name']] = $field_name;\r
+            }\r
+        }\r
+\r
+        if (!empty($changes['change']) && is_array($changes['change'])) {\r
+            foreach ($changes['change'] as $field_name => $field) {\r
+                if ($query) {\r
+                    $query.= ', ';\r
+                }\r
+                if (isset($rename[$field_name])) {\r
+                    $old_field_name = $rename[$field_name];\r
+                    unset($rename[$field_name]);\r
+                } else {\r
+                    $old_field_name = $field_name;\r
+                }\r
+                $old_field_name = $db->quoteIdentifier($old_field_name, true);\r
+                $query.= "CHANGE $old_field_name " . $db->getDeclaration($field['definition']['type'], $field_name, $field['definition']);\r
+            }\r
+        }\r
+\r
+        if (!empty($rename) && is_array($rename)) {\r
+            foreach ($rename as $rename_name => $renamed_field) {\r
+                if ($query) {\r
+                    $query.= ', ';\r
+                }\r
+                $field = $changes['rename'][$renamed_field];\r
+                $renamed_field = $db->quoteIdentifier($renamed_field, true);\r
+                $query.= 'CHANGE ' . $renamed_field . ' ' . $db->getDeclaration($field['definition']['type'], $field['name'], $field['definition']);\r
+            }\r
+        }\r
+\r
+        if (!$query) {\r
+            return MDB2_OK;\r
+        }\r
+\r
+        $name = $db->quoteIdentifier($name, true);\r
+        return $db->exec("ALTER TABLE $name $query");\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listDatabases()\r
+\r
+    /**\r
+     * list all databases\r
+     *\r
+     * @return mixed array of database names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listDatabases()\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $result = $db->queryCol('SHOW DATABASES');\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listUsers()\r
+\r
+    /**\r
+     * list all users\r
+     *\r
+     * @return mixed array of user names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listUsers()\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->queryCol('SELECT DISTINCT USER FROM mysql.USER');\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listFunctions()\r
+\r
+    /**\r
+     * list all functions in the current database\r
+     *\r
+     * @return mixed array of function names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listFunctions()\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = "SELECT name FROM mysql.proc";\r
+        /*\r
+        SELECT ROUTINE_NAME\r
+          FROM INFORMATION_SCHEMA.ROUTINES\r
+         WHERE ROUTINE_TYPE = 'FUNCTION'\r
+        */\r
+        $result = $db->queryCol($query);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTableTriggers()\r
+\r
+    /**\r
+     * list all triggers in the database that reference a given table\r
+     *\r
+     * @param string table for which all referenced triggers should be found\r
+     * @return mixed array of trigger names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTableTriggers($table = null)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = 'SHOW TRIGGERS';\r
+        if (null !== $table) {\r
+            $table = $db->quote($table, 'text');\r
+            $query .= " LIKE $table";\r
+        }\r
+        $result = $db->queryCol($query);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTables()\r
+\r
+    /**\r
+     * list all tables in the current database\r
+     *\r
+     * @param string database, the current is default\r
+     * @return mixed array of table names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTables($database = null)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = "SHOW /*!50002 FULL*/ TABLES";\r
+        if (null !== $database) {\r
+            $query .= " FROM $database";\r
+        }\r
+        $query.= "/*!50002  WHERE Table_type = 'BASE TABLE'*/";\r
+\r
+        $table_names = $db->queryAll($query, null, MDB2_FETCHMODE_ORDERED);\r
+        if (PEAR::isError($table_names)) {\r
+            return $table_names;\r
+        }\r
+\r
+        $result = array();\r
+        foreach ($table_names as $table) {\r
+            if (!$this->_fixSequenceName($table[0], true)) {\r
+                $result[] = $table[0];\r
+            }\r
+        }\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listViews()\r
+\r
+    /**\r
+     * list all views in the current database\r
+     *\r
+     * @param string database, the current is default\r
+     * @return mixed array of view names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listViews($database = null)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = 'SHOW FULL TABLES';\r
+        if (null !== $database) {\r
+            $query.= " FROM $database";\r
+        }\r
+        $query.= " WHERE Table_type = 'VIEW'";\r
+\r
+        $result = $db->queryCol($query);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTableFields()\r
+\r
+    /**\r
+     * list all fields in a table in the current database\r
+     *\r
+     * @param string $table name of table that should be used in method\r
+     * @return mixed array of field names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTableFields($table)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $table = $db->quoteIdentifier($table, true);\r
+        $result = $db->queryCol("SHOW COLUMNS FROM $table");\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ createIndex()\r
+\r
+    /**\r
+     * Get the stucture of a field into an array\r
+     *\r
+     * @author Leoncx\r
+     * @param string $table      name of the table on which the index is to be created\r
+     * @param string $name       name of the index to be created\r
+     * @param array  $definition associative array that defines properties of the index to be created.\r
+     *                           Currently, only one property named FIELDS is supported. This property\r
+     *                           is also an associative with the names of the index fields as array\r
+     *                           indexes. Each entry of this array is set to another type of associative\r
+     *                           array that specifies properties of the index that are specific to\r
+     *                           each field.\r
+     *\r
+     *                           Currently, only the sorting property is supported. It should be used\r
+     *                           to define the sorting direction of the index. It may be set to either\r
+     *                           ascending or descending.\r
+     *\r
+     *                           Not all DBMS support index sorting direction configuration. The DBMS\r
+     *                           drivers of those that do not support it ignore this property. Use the\r
+     *                           function supports() to determine whether the DBMS driver can manage indexes.\r
+     *\r
+     *                           Example\r
+     *                               array(\r
+     *                                   'fields' => array(\r
+     *                                       'user_name' => array(\r
+     *                                           'sorting' => 'ascending'\r
+     *                                           'length' => 10\r
+     *                                       ),\r
+     *                                       'last_login' => array()\r
+     *                                    )\r
+     *                                )\r
+     *\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function createIndex($table, $name, $definition)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $table = $db->quoteIdentifier($table, true);\r
+        $name = $db->quoteIdentifier($db->getIndexName($name), true);\r
+        $query = "CREATE INDEX $name ON $table";\r
+        $fields = array();\r
+        foreach ($definition['fields'] as $field => $fieldinfo) {\r
+            if (!empty($fieldinfo['length'])) {\r
+                $fields[] = $db->quoteIdentifier($field, true) . '(' . $fieldinfo['length'] . ')';\r
+            } else {\r
+                $fields[] = $db->quoteIdentifier($field, true);\r
+            }\r
+        }\r
+        $query .= ' ('. implode(', ', $fields) . ')';\r
+        return $db->exec($query);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ dropIndex()\r
+\r
+    /**\r
+     * drop existing index\r
+     *\r
+     * @param string    $table         name of table that should be used in method\r
+     * @param string    $name         name of the index to be dropped\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function dropIndex($table, $name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $table = $db->quoteIdentifier($table, true);\r
+        $name = $db->quoteIdentifier($db->getIndexName($name), true);\r
+        return $db->exec("DROP INDEX $name ON $table");\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTableIndexes()\r
+\r
+    /**\r
+     * list all indexes in a table\r
+     *\r
+     * @param string $table name of table that should be used in method\r
+     * @return mixed array of index names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTableIndexes($table)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $key_name = 'Key_name';\r
+        $non_unique = 'Non_unique';\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            if ($db->options['field_case'] == CASE_LOWER) {\r
+                $key_name = strtolower($key_name);\r
+                $non_unique = strtolower($non_unique);\r
+            } else {\r
+                $key_name = strtoupper($key_name);\r
+                $non_unique = strtoupper($non_unique);\r
+            }\r
+        }\r
+\r
+        $table = $db->quoteIdentifier($table, true);\r
+        $query = "SHOW INDEX FROM $table";\r
+        $indexes = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);\r
+        if (PEAR::isError($indexes)) {\r
+            return $indexes;\r
+        }\r
+\r
+        $result = array();\r
+        foreach ($indexes as $index_data) {\r
+            if ($index_data[$non_unique] && ($index = $this->_fixIndexName($index_data[$key_name]))) {\r
+                $result[$index] = true;\r
+            }\r
+        }\r
+\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_change_key_case($result, $db->options['field_case']);\r
+        }\r
+        return array_keys($result);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ createConstraint()\r
+\r
+    /**\r
+     * create a constraint on a table\r
+     *\r
+     * @param string    $table        name of the table on which the constraint is to be created\r
+     * @param string    $name         name of the constraint to be created\r
+     * @param array     $definition   associative array that defines properties of the constraint to be created.\r
+     *                                Currently, only one property named FIELDS is supported. This property\r
+     *                                is also an associative with the names of the constraint fields as array\r
+     *                                constraints. Each entry of this array is set to another type of associative\r
+     *                                array that specifies properties of the constraint that are specific to\r
+     *                                each field.\r
+     *\r
+     *                                Example\r
+     *                                   array(\r
+     *                                       'fields' => array(\r
+     *                                           'user_name' => array(),\r
+     *                                           'last_login' => array()\r
+     *                                       )\r
+     *                                   )\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function createConstraint($table, $name, $definition)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $type = '';\r
+        $idx_name = $db->quoteIdentifier($db->getIndexName($name), true);\r
+        if (!empty($definition['primary'])) {\r
+            $type = 'PRIMARY';\r
+            $idx_name = 'KEY';\r
+        } elseif (!empty($definition['unique'])) {\r
+            $type = 'UNIQUE';\r
+        } elseif (!empty($definition['foreign'])) {\r
+            $type = 'CONSTRAINT';\r
+        }\r
+        if (empty($type)) {\r
+            return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,\r
+                'invalid definition, could not create constraint', __FUNCTION__);\r
+        }\r
+\r
+        $table_quoted = $db->quoteIdentifier($table, true);\r
+        $query = "ALTER TABLE $table_quoted ADD $type $idx_name";\r
+        if (!empty($definition['foreign'])) {\r
+            $query .= ' FOREIGN KEY';\r
+        }\r
+        $fields = array();\r
+        foreach ($definition['fields'] as $field => $fieldinfo) {\r
+            $quoted = $db->quoteIdentifier($field, true);\r
+            if (!empty($fieldinfo['length'])) {\r
+                $quoted .= '(' . $fieldinfo['length'] . ')';\r
+            }\r
+            $fields[] = $quoted;\r
+        }\r
+        $query .= ' ('. implode(', ', $fields) . ')';\r
+        if (!empty($definition['foreign'])) {\r
+            $query.= ' REFERENCES ' . $db->quoteIdentifier($definition['references']['table'], true);\r
+            $referenced_fields = array();\r
+            foreach (array_keys($definition['references']['fields']) as $field) {\r
+                $referenced_fields[] = $db->quoteIdentifier($field, true);\r
+            }\r
+            $query .= ' ('. implode(', ', $referenced_fields) . ')';\r
+            $query .= $this->_getAdvancedFKOptions($definition);\r
+\r
+            // add index on FK column(s) or we can't add a FK constraint\r
+            // @see http://forums.mysql.com/read.php?22,19755,226009\r
+            $result = $this->createIndex($table, $name.'_fkidx', $definition);\r
+            if (PEAR::isError($result)) {\r
+                return $result;\r
+            }\r
+        }\r
+        $res = $db->exec($query);\r
+        if (PEAR::isError($res)) {\r
+            return $res;\r
+        }\r
+        if (!empty($definition['foreign'])) {\r
+            return $this->_createFKTriggers($table, array($name => $definition));\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ dropConstraint()\r
+\r
+    /**\r
+     * drop existing constraint\r
+     *\r
+     * @param string    $table        name of table that should be used in method\r
+     * @param string    $name         name of the constraint to be dropped\r
+     * @param string    $primary      hint if the constraint is primary\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function dropConstraint($table, $name, $primary = false)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        if ($primary || strtolower($name) == 'primary') {\r
+            $query = 'ALTER TABLE '. $db->quoteIdentifier($table, true) .' DROP PRIMARY KEY';\r
+            return $db->exec($query);\r
+        }\r
+\r
+        //is it a FK constraint? If so, also delete the associated triggers\r
+        $db->loadModule('Reverse', null, true);\r
+        $definition = $db->reverse->getTableConstraintDefinition($table, $name);\r
+        if (!PEAR::isError($definition) && !empty($definition['foreign'])) {\r
+            //first drop the FK enforcing triggers\r
+            $result = $this->_dropFKTriggers($table, $name, $definition['references']['table']);\r
+            if (PEAR::isError($result)) {\r
+                return $result;\r
+            }\r
+            //then drop the constraint itself\r
+            $table = $db->quoteIdentifier($table, true);\r
+            $name = $db->quoteIdentifier($db->getIndexName($name), true);\r
+            $query = "ALTER TABLE $table DROP FOREIGN KEY $name";\r
+            return $db->exec($query);\r
+        }\r
+\r
+        $table = $db->quoteIdentifier($table, true);\r
+        $name = $db->quoteIdentifier($db->getIndexName($name), true);\r
+        $query = "ALTER TABLE $table DROP INDEX $name";\r
+        return $db->exec($query);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _createFKTriggers()\r
+\r
+    /**\r
+     * Create triggers to enforce the FOREIGN KEY constraint on the table\r
+     *\r
+     * NB: since there's no RAISE_APPLICATION_ERROR facility in mysql,\r
+     * we call a non-existent procedure to raise the FK violation message.\r
+     * @see http://forums.mysql.com/read.php?99,55108,71877#msg-71877\r
+     *\r
+     * @param string $table        table name\r
+     * @param array  $foreign_keys FOREIGN KEY definitions\r
+     *\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access private\r
+     */\r
+    function _createFKTriggers($table, $foreign_keys)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+        // create triggers to enforce FOREIGN KEY constraints\r
+        if ($db->supports('triggers') && !empty($foreign_keys)) {\r
+            $table_quoted = $db->quoteIdentifier($table, true);\r
+            foreach ($foreign_keys as $fkname => $fkdef) {\r
+                if (empty($fkdef)) {\r
+                    continue;\r
+                }\r
+                //set actions to default if not set\r
+                $fkdef['onupdate'] = empty($fkdef['onupdate']) ? $db->options['default_fk_action_onupdate'] : strtoupper($fkdef['onupdate']);\r
+                $fkdef['ondelete'] = empty($fkdef['ondelete']) ? $db->options['default_fk_action_ondelete'] : strtoupper($fkdef['ondelete']);\r
+\r
+                $trigger_names = array(\r
+                    'insert'    => $fkname.'_insert_trg',\r
+                    'update'    => $fkname.'_update_trg',\r
+                    'pk_update' => $fkname.'_pk_update_trg',\r
+                    'pk_delete' => $fkname.'_pk_delete_trg',\r
+                );\r
+                $table_fields = array_keys($fkdef['fields']);\r
+                $referenced_fields = array_keys($fkdef['references']['fields']);\r
+\r
+                //create the ON [UPDATE|DELETE] triggers on the primary table\r
+                $restrict_action = ' IF (SELECT ';\r
+                $aliased_fields = array();\r
+                foreach ($table_fields as $field) {\r
+                    $aliased_fields[] = $table_quoted .'.'.$field .' AS '.$field;\r
+                }\r
+                $restrict_action .= implode(',', $aliased_fields)\r
+                       .' FROM '.$table_quoted\r
+                       .' WHERE ';\r
+                $conditions  = array();\r
+                $new_values  = array();\r
+                $null_values = array();\r
+                for ($i=0; $i<count($table_fields); $i++) {\r
+                    $conditions[]  = $table_fields[$i] .' = OLD.'.$referenced_fields[$i];\r
+                    $new_values[]  = $table_fields[$i] .' = NEW.'.$referenced_fields[$i];\r
+                    $null_values[] = $table_fields[$i] .' = NULL';\r
+                }\r
+                $conditions2 = array();\r
+                for ($i=0; $i<count($referenced_fields); $i++) {\r
+                    $conditions2[]  = 'NEW.'.$referenced_fields[$i] .' <> OLD.'.$referenced_fields[$i];\r
+                }\r
+\r
+                $restrict_action .= implode(' AND ', $conditions).') IS NOT NULL';\r
+                $restrict_action2 = empty($conditions2) ? '' : ' AND (' .implode(' OR ', $conditions2) .')';\r
+                $restrict_action3 = ' THEN CALL %s_ON_TABLE_'.$table.'_VIOLATES_FOREIGN_KEY_CONSTRAINT();'\r
+                                   .' END IF;';\r
+\r
+                $restrict_action_update = $restrict_action . $restrict_action2 . $restrict_action3;\r
+                $restrict_action_delete = $restrict_action . $restrict_action3; // There is no NEW row in on DELETE trigger\r
+\r
+                $cascade_action_update = 'UPDATE '.$table_quoted.' SET '.implode(', ', $new_values) .' WHERE '.implode(' AND ', $conditions). ';';\r
+                $cascade_action_delete = 'DELETE FROM '.$table_quoted.' WHERE '.implode(' AND ', $conditions). ';';\r
+                $setnull_action        = 'UPDATE '.$table_quoted.' SET '.implode(', ', $null_values).' WHERE '.implode(' AND ', $conditions). ';';\r
+\r
+                if ('SET DEFAULT' == $fkdef['onupdate'] || 'SET DEFAULT' == $fkdef['ondelete']) {\r
+                    $db->loadModule('Reverse', null, true);\r
+                    $default_values = array();\r
+                    foreach ($table_fields as $table_field) {\r
+                        $field_definition = $db->reverse->getTableFieldDefinition($table, $field);\r
+                        if (PEAR::isError($field_definition)) {\r
+                            return $field_definition;\r
+                        }\r
+                        $default_values[] = $table_field .' = '. $field_definition[0]['default'];\r
+                    }\r
+                    $setdefault_action = 'UPDATE '.$table_quoted.' SET '.implode(', ', $default_values).' WHERE '.implode(' AND ', $conditions). ';';\r
+                }\r
+\r
+                $query = 'CREATE TRIGGER %s'\r
+                        .' %s ON '.$fkdef['references']['table']\r
+                        .' FOR EACH ROW BEGIN '\r
+                        .' SET FOREIGN_KEY_CHECKS = 0; ';  //only really needed for ON UPDATE CASCADE\r
+\r
+                if ('CASCADE' == $fkdef['onupdate']) {\r
+                    $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE',  'update') . $cascade_action_update;\r
+                } elseif ('SET NULL' == $fkdef['onupdate']) {\r
+                    $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setnull_action;\r
+                } elseif ('SET DEFAULT' == $fkdef['onupdate']) {\r
+                    $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setdefault_action;\r
+                } elseif ('NO ACTION' == $fkdef['onupdate']) {\r
+                    $sql_update = sprintf($query.$restrict_action_update, $trigger_names['pk_update'], 'AFTER UPDATE', 'update');\r
+                } elseif ('RESTRICT' == $fkdef['onupdate']) {\r
+                    $sql_update = sprintf($query.$restrict_action_update, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update');\r
+                }\r
+                if ('CASCADE' == $fkdef['ondelete']) {\r
+                    $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE',  'delete') . $cascade_action_delete;\r
+                } elseif ('SET NULL' == $fkdef['ondelete']) {\r
+                    $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setnull_action;\r
+                } elseif ('SET DEFAULT' == $fkdef['ondelete']) {\r
+                    $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setdefault_action;\r
+                } elseif ('NO ACTION' == $fkdef['ondelete']) {\r
+                    $sql_delete = sprintf($query.$restrict_action_delete, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete');\r
+                } elseif ('RESTRICT' == $fkdef['ondelete']) {\r
+                    $sql_delete = sprintf($query.$restrict_action_delete, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete');\r
+                }\r
+                $sql_update .= ' SET FOREIGN_KEY_CHECKS = 1; END;';\r
+                $sql_delete .= ' SET FOREIGN_KEY_CHECKS = 1; END;';\r
+\r
+                $db->pushErrorHandling(PEAR_ERROR_RETURN);\r
+                $db->expectError(MDB2_ERROR_CANNOT_CREATE);\r
+                $result = $db->exec($sql_delete);\r
+                $expected_errmsg = 'This MySQL version doesn\'t support multiple triggers with the same action time and event for one table';\r
+                $db->popExpect();\r
+                $db->popErrorHandling();\r
+                if (PEAR::isError($result)) {\r
+                    if ($result->getCode() != MDB2_ERROR_CANNOT_CREATE) {\r
+                        return $result;\r
+                    }\r
+                    $db->warnings[] = $expected_errmsg;\r
+                }\r
+                $db->pushErrorHandling(PEAR_ERROR_RETURN);\r
+                $db->expectError(MDB2_ERROR_CANNOT_CREATE);\r
+                $result = $db->exec($sql_update);\r
+                $db->popExpect();\r
+                $db->popErrorHandling();\r
+                if (PEAR::isError($result) && $result->getCode() != MDB2_ERROR_CANNOT_CREATE) {\r
+                    if ($result->getCode() != MDB2_ERROR_CANNOT_CREATE) {\r
+                        return $result;\r
+                    }\r
+                    $db->warnings[] = $expected_errmsg;\r
+                }\r
+            }\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _dropFKTriggers()\r
+\r
+    /**\r
+     * Drop the triggers created to enforce the FOREIGN KEY constraint on the table\r
+     *\r
+     * @param string $table            table name\r
+     * @param string $fkname           FOREIGN KEY constraint name\r
+     * @param string $referenced_table referenced table name\r
+     *\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access private\r
+     */\r
+    function _dropFKTriggers($table, $fkname, $referenced_table)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $triggers  = $this->listTableTriggers($table);\r
+        $triggers2 = $this->listTableTriggers($referenced_table);\r
+        if (!PEAR::isError($triggers2) && !PEAR::isError($triggers)) {\r
+            $triggers = array_merge($triggers, $triggers2);\r
+            $pattern = '/^'.$fkname.'(_pk)?_(insert|update|delete)_trg$/i';\r
+            foreach ($triggers as $trigger) {\r
+                if (preg_match($pattern, $trigger)) {\r
+                    $result = $db->exec('DROP TRIGGER '.$trigger);\r
+                    if (PEAR::isError($result)) {\r
+                        return $result;\r
+                    }\r
+                }\r
+            }\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTableConstraints()\r
+\r
+    /**\r
+     * list all constraints in a table\r
+     *\r
+     * @param string $table name of table that should be used in method\r
+     * @return mixed array of constraint names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTableConstraints($table)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $key_name = 'Key_name';\r
+        $non_unique = 'Non_unique';\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            if ($db->options['field_case'] == CASE_LOWER) {\r
+                $key_name = strtolower($key_name);\r
+                $non_unique = strtolower($non_unique);\r
+            } else {\r
+                $key_name = strtoupper($key_name);\r
+                $non_unique = strtoupper($non_unique);\r
+            }\r
+        }\r
+\r
+        $query = 'SHOW INDEX FROM ' . $db->quoteIdentifier($table, true);\r
+        $indexes = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);\r
+        if (PEAR::isError($indexes)) {\r
+            return $indexes;\r
+        }\r
+\r
+        $result = array();\r
+        foreach ($indexes as $index_data) {\r
+            if (!$index_data[$non_unique]) {\r
+                if ($index_data[$key_name] !== 'PRIMARY') {\r
+                    $index = $this->_fixIndexName($index_data[$key_name]);\r
+                } else {\r
+                    $index = 'PRIMARY';\r
+                }\r
+                if (!empty($index)) {\r
+                    $result[$index] = true;\r
+                }\r
+            }\r
+        }\r
+        \r
+        //list FOREIGN KEY constraints...\r
+        $query = 'SHOW CREATE TABLE '. $db->escape($table);\r
+        $definition = $db->queryOne($query, 'text', 1);\r
+        if (!PEAR::isError($definition) && !empty($definition)) {\r
+            $pattern = '/\bCONSTRAINT\b\s+([^\s]+)\s+\bFOREIGN KEY\b/Uims';\r
+            if (preg_match_all($pattern, str_replace('`', '', $definition), $matches) > 0) {\r
+                foreach ($matches[1] as $constraint) {\r
+                    $result[$constraint] = true;\r
+                }\r
+            }\r
+        }\r
+\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_change_key_case($result, $db->options['field_case']);\r
+        }\r
+        return array_keys($result);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ createSequence()\r
+\r
+    /**\r
+     * create sequence\r
+     *\r
+     * @param string    $seq_name name of the sequence to be created\r
+     * @param string    $start    start value of the sequence; default is 1\r
+     * @param array     $options  An associative array of table options:\r
+     *                          array(\r
+     *                              'comment' => 'Foo',\r
+     *                              'charset' => 'utf8',\r
+     *                              'collate' => 'utf8_unicode_ci',\r
+     *                              'type'    => 'innodb',\r
+     *                          );\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function createSequence($seq_name, $start = 1, $options = array())\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);\r
+        $seqcol_name = $db->quoteIdentifier($db->options['seqcol_name'], true);\r
+        \r
+        $options_strings = array();\r
+\r
+        if (!empty($options['comment'])) {\r
+            $options_strings['comment'] = 'COMMENT = '.$db->quote($options['comment'], 'text');\r
+        }\r
+\r
+        if (!empty($options['charset'])) {\r
+            $options_strings['charset'] = 'DEFAULT CHARACTER SET '.$options['charset'];\r
+            if (!empty($options['collate'])) {\r
+                $options_strings['charset'].= ' COLLATE '.$options['collate'];\r
+            }\r
+        }\r
+\r
+        $type = false;\r
+        if (!empty($options['type'])) {\r
+            $type = $options['type'];\r
+        } elseif ($db->options['default_table_type']) {\r
+            $type = $db->options['default_table_type'];\r
+        }\r
+        if ($type) {\r
+            $options_strings[] = "ENGINE = $type";\r
+        }\r
+\r
+        $query = "CREATE TABLE $sequence_name ($seqcol_name INT NOT NULL AUTO_INCREMENT, PRIMARY KEY ($seqcol_name))";\r
+        if (!empty($options_strings)) {\r
+            $query .= ' '.implode(' ', $options_strings);\r
+        }\r
+        $res = $db->exec($query);\r
+        if (PEAR::isError($res)) {\r
+            return $res;\r
+        }\r
+\r
+        if ($start == 1) {\r
+            return MDB2_OK;\r
+        }\r
+\r
+        $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (".($start-1).')';\r
+        $res = $db->exec($query);\r
+        if (!PEAR::isError($res)) {\r
+            return MDB2_OK;\r
+        }\r
+\r
+        // Handle error\r
+        $result = $db->exec("DROP TABLE $sequence_name");\r
+        if (PEAR::isError($result)) {\r
+            return $db->raiseError($result, null, null,\r
+                'could not drop inconsistent sequence table', __FUNCTION__);\r
+        }\r
+\r
+        return $db->raiseError($res, null, null,\r
+            'could not create sequence table', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ dropSequence()\r
+\r
+    /**\r
+     * drop existing sequence\r
+     *\r
+     * @param string    $seq_name     name of the sequence to be dropped\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function dropSequence($seq_name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);\r
+        return $db->exec("DROP TABLE $sequence_name");\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listSequences()\r
+\r
+    /**\r
+     * list all sequences in the current database\r
+     *\r
+     * @param string database, the current is default\r
+     * @return mixed array of sequence names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listSequences($database = null)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = "SHOW TABLES";\r
+        if (null !== $database) {\r
+            $query .= " FROM $database";\r
+        }\r
+        $table_names = $db->queryCol($query);\r
+        if (PEAR::isError($table_names)) {\r
+            return $table_names;\r
+        }\r
+\r
+        $result = array();\r
+        foreach ($table_names as $table_name) {\r
+            if ($sqn = $this->_fixSequenceName($table_name, true)) {\r
+                $result[] = $sqn;\r
+            }\r
+        }\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+}\r
 ?>
\ No newline at end of file
index 44a611d399d32bf95dd6b79e46e55b6a559737e8..ec1b08975f0e3d4b769048866fdd92875d60355f 100644 (file)
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Paul Cooper <pgc@ucecom.com>                                 |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.87 2008/11/29 14:09:59 afz Exp $
-
-require_once('MDB2/Driver/Manager/Common.php');
-
-/**
- * MDB2 MySQL driver for the management modules
- *
- * @package MDB2
- * @category Database
- * @author  Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_Driver_Manager_pgsql extends MDB2_Driver_Manager_Common
-{
-    // {{{ createDatabase()
-
-    /**
-     * create a new database
-     *
-     * @param string $name    name of the database that should be created
-     * @param array  $options array with charset info
-     *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function createDatabase($name, $options = array())
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $name  = $db->quoteIdentifier($name, true);
-        $query = 'CREATE DATABASE ' . $name;
-        if (!empty($options['charset'])) {
-            $query .= ' WITH ENCODING ' . $db->quote($options['charset'], 'text');
-        }
-        return $db->standaloneQuery($query, null, true);
-    }
-
-    // }}}
-    // {{{ alterDatabase()
-
-    /**
-     * alter an existing database
-     *
-     * @param string $name    name of the database that is intended to be changed
-     * @param array  $options array with name, owner info
-     *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function alterDatabase($name, $options = array())
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = 'ALTER DATABASE '. $db->quoteIdentifier($name, true);
-        if (!empty($options['name'])) {
-            $query .= ' RENAME TO ' . $options['name'];
-        }
-        if (!empty($options['owner'])) {
-            $query .= ' OWNER TO ' . $options['owner'];
-        }
-        return $db->standaloneQuery($query, null, true);
-    }
-
-    // }}}
-    // {{{ dropDatabase()
-
-    /**
-     * drop an existing database
-     *
-     * @param string $name name of the database that should be dropped
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function dropDatabase($name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $name = $db->quoteIdentifier($name, true);
-        $query = "DROP DATABASE $name";
-        return $db->standaloneQuery($query, null, true);
-    }
-
-    // }}}
-    // {{{ _getAdvancedFKOptions()
-
-    /**
-     * Return the FOREIGN KEY query section dealing with non-standard options
-     * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
-     *
-     * @param array $definition
-     * @return string
-     * @access protected
-     */
-    function _getAdvancedFKOptions($definition)
-    {
-        $query = '';
-        if (!empty($definition['match'])) {
-            $query .= ' MATCH '.$definition['match'];
-        }
-        if (!empty($definition['onupdate'])) {
-            $query .= ' ON UPDATE '.$definition['onupdate'];
-        }
-        if (!empty($definition['ondelete'])) {
-            $query .= ' ON DELETE '.$definition['ondelete'];
-        }
-        if (!empty($definition['deferrable'])) {
-            $query .= ' DEFERRABLE';
-        } else {
-            $query .= ' NOT DEFERRABLE';
-        }
-        if (!empty($definition['initiallydeferred'])) {
-            $query .= ' INITIALLY DEFERRED';
-        } else {
-            $query .= ' INITIALLY IMMEDIATE';
-        }
-        return $query;
-    }
-
-    // }}}
-    // {{{ truncateTable()
-
-    /**
-     * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported,
-     * it falls back to a DELETE FROM TABLE query)
-     *
-     * @param string $name name of the table that should be truncated
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function truncateTable($name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $name = $db->quoteIdentifier($name, true);
-        return $db->exec("TRUNCATE TABLE $name");
-    }
-
-    // }}}
-    // {{{ vacuum()
-
-    /**
-     * Optimize (vacuum) all the tables in the db (or only the specified table)
-     * and optionally run ANALYZE.
-     *
-     * @param string $table table name (all the tables if empty)
-     * @param array  $options an array with driver-specific options:
-     *               - timeout [int] (in seconds) [mssql-only]
-     *               - analyze [boolean] [pgsql and mysql]
-     *               - full [boolean] [pgsql-only]
-     *               - freeze [boolean] [pgsql-only]
-     *
-     * @return mixed MDB2_OK success, a MDB2 error on failure
-     * @access public
-     */
-    function vacuum($table = null, $options = array())
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-        $query = 'VACUUM';
-
-        if (!empty($options['full'])) {
-            $query .= ' FULL';
-        }
-        if (!empty($options['freeze'])) {
-            $query .= ' FREEZE';
-        }
-        if (!empty($options['analyze'])) {
-            $query .= ' ANALYZE';
-        }
-
-        if (!empty($table)) {
-            $query .= ' '.$db->quoteIdentifier($table, true);
-        }
-        return $db->exec($query);
-    }
-
-    // }}}
-    // {{{ alterTable()
-
-    /**
-     * alter an existing table
-     *
-     * @param string $name         name of the table that is intended to be changed.
-     * @param array $changes     associative array that contains the details of each type
-     *                             of change that is intended to be performed. The types of
-     *                             changes that are currently supported are defined as follows:
-     *
-     *                             name
-     *
-     *                                New name for the table.
-     *
-     *                            add
-     *
-     *                                Associative array with the names of fields to be added as
-     *                                 indexes of the array. The value of each entry of the array
-     *                                 should be set to another associative array with the properties
-     *                                 of the fields to be added. The properties of the fields should
-     *                                 be the same as defined by the MDB2 parser.
-     *
-     *
-     *                            remove
-     *
-     *                                Associative array with the names of fields to be removed as indexes
-     *                                 of the array. Currently the values assigned to each entry are ignored.
-     *                                 An empty array should be used for future compatibility.
-     *
-     *                            rename
-     *
-     *                                Associative array with the names of fields to be renamed as indexes
-     *                                 of the array. The value of each entry of the array should be set to
-     *                                 another associative array with the entry named name with the new
-     *                                 field name and the entry named Declaration that is expected to contain
-     *                                 the portion of the field declaration already in DBMS specific SQL code
-     *                                 as it is used in the CREATE TABLE statement.
-     *
-     *                            change
-     *
-     *                                Associative array with the names of the fields to be changed as indexes
-     *                                 of the array. Keep in mind that if it is intended to change either the
-     *                                 name of a field and any other properties, the change array entries
-     *                                 should have the new names of the fields as array indexes.
-     *
-     *                                The value of each entry of the array should be set to another associative
-     *                                 array with the properties of the fields to that are meant to be changed as
-     *                                 array entries. These entries should be assigned to the new values of the
-     *                                 respective properties. The properties of the fields should be the same
-     *                                 as defined by the MDB2 parser.
-     *
-     *                            Example
-     *                                array(
-     *                                    'name' => 'userlist',
-     *                                    'add' => array(
-     *                                        'quota' => array(
-     *                                            'type' => 'integer',
-     *                                            'unsigned' => 1
-     *                                        )
-     *                                    ),
-     *                                    'remove' => array(
-     *                                        'file_limit' => array(),
-     *                                        'time_limit' => array()
-     *                                    ),
-     *                                    'change' => array(
-     *                                        'name' => array(
-     *                                            'length' => '20',
-     *                                            'definition' => array(
-     *                                                'type' => 'text',
-     *                                                'length' => 20,
-     *                                            ),
-     *                                        )
-     *                                    ),
-     *                                    'rename' => array(
-     *                                        'sex' => array(
-     *                                            'name' => 'gender',
-     *                                            'definition' => array(
-     *                                                'type' => 'text',
-     *                                                'length' => 1,
-     *                                                'default' => 'M',
-     *                                            ),
-     *                                        )
-     *                                    )
-     *                                )
-     *
-     * @param boolean $check     indicates whether the function should just check if the DBMS driver
-     *                             can perform the requested table alterations if the value is true or
-     *                             actually perform them otherwise.
-     * @access public
-     *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     */
-    function alterTable($name, $changes, $check)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        foreach ($changes as $change_name => $change) {
-            switch ($change_name) {
-            case 'add':
-            case 'remove':
-            case 'change':
-            case 'name':
-            case 'rename':
-                break;
-            default:
-                return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
-                    'change type "'.$change_name.'\" not yet supported', __FUNCTION__);
-            }
-        }
-
-        if ($check) {
-            return MDB2_OK;
-        }
-
-        $name = $db->quoteIdentifier($name, true);
-
-        if (!empty($changes['remove']) && is_array($changes['remove'])) {
-            foreach ($changes['remove'] as $field_name => $field) {
-                $field_name = $db->quoteIdentifier($field_name, true);
-                $query = 'DROP ' . $field_name;
-                $result = $db->exec("ALTER TABLE $name $query");
-                if (PEAR::isError($result)) {
-                    return $result;
-                }
-            }
-        }
-
-        if (!empty($changes['rename']) && is_array($changes['rename'])) {
-            foreach ($changes['rename'] as $field_name => $field) {
-                $field_name = $db->quoteIdentifier($field_name, true);
-                $result = $db->exec("ALTER TABLE $name RENAME COLUMN $field_name TO ".$db->quoteIdentifier($field['name'], true));
-                if (PEAR::isError($result)) {
-                    return $result;
-                }
-            }
-        }
-
-        if (!empty($changes['add']) && is_array($changes['add'])) {
-            foreach ($changes['add'] as $field_name => $field) {
-                $query = 'ADD ' . $db->getDeclaration($field['type'], $field_name, $field);
-                $result = $db->exec("ALTER TABLE $name $query");
-                if (PEAR::isError($result)) {
-                    return $result;
-                }
-            }
-        }
-
-        if (!empty($changes['change']) && is_array($changes['change'])) {
-            foreach ($changes['change'] as $field_name => $field) {
-                $field_name = $db->quoteIdentifier($field_name, true);
-                if (!empty($field['definition']['type'])) {
-                    $server_info = $db->getServerVersion();
-                    if (PEAR::isError($server_info)) {
-                        return $server_info;
-                    }
-                    if (is_array($server_info) && $server_info['major'] < 8) {
-                        return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
-                            'changing column type for "'.$change_name.'\" requires PostgreSQL 8.0 or above', __FUNCTION__);
-                    }
-                    $db->loadModule('Datatype', null, true);
-                    $type = $db->datatype->getTypeDeclaration($field['definition']);
-                    if($type=='SERIAL PRIMARY KEY'){//not correct when altering a table, since serials arent a real type
-                                               $type='INTEGER';//use integer instead
-                    }
-                    $query = "ALTER $field_name TYPE $type USING CAST($field_name AS $type)";
-                    $result = $db->exec("ALTER TABLE $name $query");
-                    if (PEAR::isError($result)) {
-                        return $result;
-                    }
-                }
-                if (array_key_exists('default', $field['definition'])) {
-                    $query = "ALTER $field_name SET DEFAULT ".$db->quote($field['definition']['default'], $field['definition']['type']);
-                    $result = $db->exec("ALTER TABLE $name $query");
-                    if (PEAR::isError($result)) {
-                        return $result;
-                    }
-                }
-                if (!empty($field['definition']['notnull'])) {
-                    $query = "ALTER $field_name ".($field['definition']['notnull'] ? 'SET' : 'DROP').' NOT NULL';
-                    $result = $db->exec("ALTER TABLE $name $query");
-                    if (PEAR::isError($result)) {
-                        return $result;
-                    }
-                }
-            }
-        }
-
-        if (!empty($changes['name'])) {
-            $change_name = $db->quoteIdentifier($changes['name'], true);
-            $result = $db->exec("ALTER TABLE $name RENAME TO ".$change_name);
-            if (PEAR::isError($result)) {
-                return $result;
-            }
-        }
-
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ listDatabases()
-
-    /**
-     * list all databases
-     *
-     * @return mixed array of database names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listDatabases()
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = 'SELECT datname FROM pg_database';
-        $result2 = $db->standaloneQuery($query, array('text'), false);
-        if (!MDB2::isResultCommon($result2)) {
-            return $result2;
-        }
-
-        $result = $result2->fetchCol();
-        $result2->free();
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
-        }
-        return $result;
-    }
-
-    // }}}
-    // {{{ listUsers()
-
-    /**
-     * list all users
-     *
-     * @return mixed array of user names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listUsers()
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = 'SELECT usename FROM pg_user';
-        $result2 = $db->standaloneQuery($query, array('text'), false);
-        if (!MDB2::isResultCommon($result2)) {
-            return $result2;
-        }
-
-        $result = $result2->fetchCol();
-        $result2->free();
-        return $result;
-    }
-
-    // }}}
-    // {{{ listViews()
-
-    /**
-     * list all views in the current database
-     *
-     * @return mixed array of view names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listViews($database = null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = "SELECT viewname
-                    FROM pg_views
-                   WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
-                     AND viewname !~ '^pg_'";
-        $result = $db->queryCol($query);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
-        }
-        return $result;
-    }
-
-    // }}}
-    // {{{ listTableViews()
-
-    /**
-     * list the views in the database that reference a given table
-     *
-     * @param string table for which all referenced views should be found
-     * @return mixed array of view names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTableViews($table)
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = 'SELECT viewname FROM pg_views NATURAL JOIN pg_tables';
-        $query.= ' WHERE tablename ='.$db->quote($table, 'text');
-        $result = $db->queryCol($query);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
-        }
-        return $result;
-    }
-
-    // }}}
-    // {{{ listFunctions()
-
-    /**
-     * list all functions in the current database
-     *
-     * @return mixed array of function names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listFunctions()
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = "
-            SELECT
-                proname
-            FROM
-                pg_proc pr,
-                pg_type tp
-            WHERE
-                tp.oid = pr.prorettype
-                AND pr.proisagg = FALSE
-                AND tp.typname <> 'trigger'
-                AND pr.pronamespace IN
-                    (SELECT oid FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema')";
-        $result = $db->queryCol($query);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
-        }
-        return $result;
-    }
-
-    // }}}
-    // {{{ listTableTriggers()
-
-    /**
-     * list all triggers in the database that reference a given table
-     *
-     * @param string table for which all referenced triggers should be found
-     * @return mixed array of trigger names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTableTriggers($table = null)
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = 'SELECT trg.tgname AS trigger_name
-                    FROM pg_trigger trg,
-                         pg_class tbl
-                   WHERE trg.tgrelid = tbl.oid';
-        if (!is_null($table)) {
-            $table = $db->quote(strtoupper($table), 'text');
-            $query .= " AND tbl.relname = $table";
-        }
-        $result = $db->queryCol($query);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
-        }
-        return $result;
-    }
-
-    // }}}
-    // {{{ listTables()
-
-    /**
-     * list all tables in the current database
-     *
-     * @return mixed array of table names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTables($database = null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        // gratuitously stolen from PEAR DB _getSpecialQuery in pgsql.php
-        $query = 'SELECT c.relname AS "Name"'
-            . ' FROM pg_class c, pg_user u'
-            . ' WHERE c.relowner = u.usesysid'
-            . " AND c.relkind = 'r'"
-            . ' AND NOT EXISTS'
-            . ' (SELECT 1 FROM pg_views'
-            . '  WHERE viewname = c.relname)'
-            . " AND c.relname !~ '^(pg_|sql_)'"
-            . ' UNION'
-            . ' SELECT c.relname AS "Name"'
-            . ' FROM pg_class c'
-            . " WHERE c.relkind = 'r'"
-            . ' AND NOT EXISTS'
-            . ' (SELECT 1 FROM pg_views'
-            . '  WHERE viewname = c.relname)'
-            . ' AND NOT EXISTS'
-            . ' (SELECT 1 FROM pg_user'
-            . '  WHERE usesysid = c.relowner)'
-            . " AND c.relname !~ '^pg_'";
-        $result = $db->queryCol($query);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
-        }
-        return $result;
-    }
-
-    // }}}
-    // {{{ listTableFields()
-
-    /**
-     * list all fields in a table in the current database
-     *
-     * @param string $table name of table that should be used in method
-     * @return mixed array of field names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTableFields($table)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        list($schema, $table) = $this->splitTableSchema($table);
-
-        $table = $db->quoteIdentifier($table, true);
-        if (!empty($schema)) {
-            $table = $db->quoteIdentifier($schema, true) . '.' .$table;
-        }
-        $db->setLimit(1);
-        $result2 = $db->query("SELECT * FROM $table LIMIT 1");
-        if (PEAR::isError($result2)) {
-            return $result2;
-        }
-        $result = $result2->getColumnNames();
-        $result2->free();
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        return array_flip($result);
-    }
-
-    // }}}
-    // {{{ listTableIndexes()
-
-    /**
-     * list all indexes in a table
-     *
-     * @param string $table name of table that should be used in method
-     * @return mixed array of index names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTableIndexes($table)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        list($schema, $table) = $this->splitTableSchema($table);
-
-        $table = $db->quote($table, 'text');
-        $subquery = "SELECT indexrelid
-                       FROM pg_index
-                  LEFT JOIN pg_class ON pg_class.oid = pg_index.indrelid
-                  LEFT JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid
-                      WHERE pg_class.relname = $table
-                        AND indisunique != 't'
-                        AND indisprimary != 't'";
-        if (!empty($schema)) {
-            $subquery .= ' AND pg_namespace.nspname = '.$db->quote($schema, 'text');
-        }
-        $query = "SELECT relname FROM pg_class WHERE oid IN ($subquery)";
-        $indexes = $db->queryCol($query, 'text');
-        if (PEAR::isError($indexes)) {
-            return $indexes;
-        }
-
-        $result = array();
-        foreach ($indexes as $index) {
-            $index = $this->_fixIndexName($index);
-            if (!empty($index)) {
-                $result[$index] = true;
-            }
-        }
-
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_change_key_case($result, $db->options['field_case']);
-        }
-        return array_keys($result);
-    }
-
-    // }}}
-    // {{{ dropConstraint()
-
-    /**
-     * drop existing constraint
-     *
-     * @param string $table   name of table that should be used in method
-     * @param string $name    name of the constraint to be dropped
-     * @param string $primary hint if the constraint is primary
-     *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function dropConstraint($table, $name, $primary = false)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        // is it an UNIQUE index?
-        $query = 'SELECT relname
-                    FROM pg_class
-                   WHERE oid IN (
-                         SELECT indexrelid
-                           FROM pg_index, pg_class
-                          WHERE pg_class.relname = '.$db->quote($table, 'text').'
-                            AND pg_class.oid = pg_index.indrelid
-                            AND indisunique = \'t\')
-                  EXCEPT
-                  SELECT conname
-                   FROM pg_constraint, pg_class
-                  WHERE pg_constraint.conrelid = pg_class.oid
-                    AND relname = '. $db->quote($table, 'text');
-        $unique = $db->queryCol($query, 'text');
-        if (PEAR::isError($unique) || empty($unique)) {
-            // not an UNIQUE index, maybe a CONSTRAINT
-            return parent::dropConstraint($table, $name, $primary);
-        }
-
-        if (in_array($name, $unique)) {
-            return $db->exec('DROP INDEX '.$db->quoteIdentifier($name, true));
-        }
-        $idxname = $db->getIndexName($name);
-        if (in_array($idxname, $unique)) {
-            return $db->exec('DROP INDEX '.$db->quoteIdentifier($idxname, true));
-        }
-        return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-            $name . ' is not an existing constraint for table ' . $table, __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ listTableConstraints()
-
-    /**
-     * list all constraints in a table
-     *
-     * @param string $table name of table that should be used in method
-     * @return mixed array of constraint names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTableConstraints($table)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        list($schema, $table) = $this->splitTableSchema($table);
-
-        $table = $db->quote($table, 'text');
-        $query = 'SELECT conname
-                    FROM pg_constraint
-               LEFT JOIN pg_class ON pg_constraint.conrelid = pg_class.oid
-               LEFT JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid
-                   WHERE relname = ' .$table;
-        if (!empty($schema)) {
-            $query .= ' AND pg_namespace.nspname = ' . $db->quote($schema, 'text');
-        }
-        $query .= '
-                   UNION DISTINCT
-                  SELECT relname
-                    FROM pg_class
-                   WHERE oid IN (
-                         SELECT indexrelid
-                           FROM pg_index
-                      LEFT JOIN pg_class ON pg_class.oid = pg_index.indrelid
-                      LEFT JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid
-                          WHERE pg_class.relname = '.$table.'
-                            AND indisunique = \'t\'';
-        if (!empty($schema)) {
-            $query .= ' AND pg_namespace.nspname = ' . $db->quote($schema, 'text');
-        }
-        $query .= ')';
-        $constraints = $db->queryCol($query);
-        if (PEAR::isError($constraints)) {
-            return $constraints;
-        }
-
-        $result = array();
-        foreach ($constraints as $constraint) {
-            $constraint = $this->_fixIndexName($constraint);
-            if (!empty($constraint)) {
-                $result[$constraint] = true;
-            }
-        }
-
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
-            && $db->options['field_case'] == CASE_LOWER
-        ) {
-            $result = array_change_key_case($result, $db->options['field_case']);
-        }
-        return array_keys($result);
-    }
-
-    // }}}
-    // {{{ createSequence()
-
-    /**
-     * create sequence
-     *
-     * @param string $seq_name name of the sequence to be created
-     * @param string $start start value of the sequence; default is 1
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function createSequence($seq_name, $start = 1)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
-        return $db->exec("CREATE SEQUENCE $sequence_name INCREMENT 1".
-            ($start < 1 ? " MINVALUE $start" : '')." START $start");
-    }
-
-    // }}}
-    // {{{ dropSequence()
-
-    /**
-     * drop existing sequence
-     *
-     * @param string $seq_name name of the sequence to be dropped
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function dropSequence($seq_name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
-        return $db->exec("DROP SEQUENCE $sequence_name");
-    }
-
-    // }}}
-    // {{{ listSequences()
-
-    /**
-     * list all sequences in the current database
-     *
-     * @return mixed array of sequence names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listSequences($database = null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = "SELECT relname FROM pg_class WHERE relkind = 'S' AND relnamespace IN";
-        $query.= "(SELECT oid FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema')";
-        $table_names = $db->queryCol($query);
-        if (PEAR::isError($table_names)) {
-            return $table_names;
-        }
-        $result = array();
-        foreach ($table_names as $table_name) {
-            $result[] = $this->_fixSequenceName($table_name);
-        }
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
-        }
-        return $result;
-    }
-}
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Paul Cooper <pgc@ucecom.com>                                 |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: pgsql.php 299393 2010-05-14 17:49:49Z afz $\r
+\r
+require_once 'MDB2/Driver/Manager/Common.php';\r
+\r
+/**\r
+ * MDB2 MySQL driver for the management modules\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Paul Cooper <pgc@ucecom.com>\r
+ */\r
+class MDB2_Driver_Manager_pgsql extends MDB2_Driver_Manager_Common\r
+{\r
+    // {{{ createDatabase()\r
+\r
+    /**\r
+     * create a new database\r
+     *\r
+     * @param string $name    name of the database that should be created\r
+     * @param array  $options array with charset info\r
+     *\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function createDatabase($name, $options = array())\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $name  = $db->quoteIdentifier($name, true);\r
+        $query = 'CREATE DATABASE ' . $name;\r
+        if (!empty($options['charset'])) {\r
+            $query .= ' WITH ENCODING ' . $db->quote($options['charset'], 'text');\r
+        }\r
+        return $db->standaloneQuery($query, null, true);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ alterDatabase()\r
+\r
+    /**\r
+     * alter an existing database\r
+     *\r
+     * @param string $name    name of the database that is intended to be changed\r
+     * @param array  $options array with name, owner info\r
+     *\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function alterDatabase($name, $options = array())\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = '';\r
+        if (!empty($options['name'])) {\r
+            $query .= ' RENAME TO ' . $options['name'];\r
+        }\r
+        if (!empty($options['owner'])) {\r
+            $query .= ' OWNER TO ' . $options['owner'];\r
+        }\r
+\r
+        if (empty($query)) {\r
+            return MDB2_OK;\r
+        }\r
+\r
+        $query = 'ALTER DATABASE '. $db->quoteIdentifier($name, true) . $query;\r
+        return $db->standaloneQuery($query, null, true);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ dropDatabase()\r
+\r
+    /**\r
+     * drop an existing database\r
+     *\r
+     * @param string $name name of the database that should be dropped\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function dropDatabase($name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $name = $db->quoteIdentifier($name, true);\r
+        $query = "DROP DATABASE $name";\r
+        return $db->standaloneQuery($query, null, true);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getAdvancedFKOptions()\r
+\r
+    /**\r
+     * Return the FOREIGN KEY query section dealing with non-standard options\r
+     * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...\r
+     *\r
+     * @param array $definition\r
+     * @return string\r
+     * @access protected\r
+     */\r
+    function _getAdvancedFKOptions($definition)\r
+    {\r
+        $query = '';\r
+        if (!empty($definition['match'])) {\r
+            $query .= ' MATCH '.$definition['match'];\r
+        }\r
+        if (!empty($definition['onupdate'])) {\r
+            $query .= ' ON UPDATE '.$definition['onupdate'];\r
+        }\r
+        if (!empty($definition['ondelete'])) {\r
+            $query .= ' ON DELETE '.$definition['ondelete'];\r
+        }\r
+        if (!empty($definition['deferrable'])) {\r
+            $query .= ' DEFERRABLE';\r
+        } else {\r
+            $query .= ' NOT DEFERRABLE';\r
+        }\r
+        if (!empty($definition['initiallydeferred'])) {\r
+            $query .= ' INITIALLY DEFERRED';\r
+        } else {\r
+            $query .= ' INITIALLY IMMEDIATE';\r
+        }\r
+        return $query;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ truncateTable()\r
+\r
+    /**\r
+     * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported,\r
+     * it falls back to a DELETE FROM TABLE query)\r
+     *\r
+     * @param string $name name of the table that should be truncated\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function truncateTable($name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $name = $db->quoteIdentifier($name, true);\r
+        return $db->exec("TRUNCATE TABLE $name");\r
+    }\r
+\r
+    // }}}\r
+    // {{{ vacuum()\r
+\r
+    /**\r
+     * Optimize (vacuum) all the tables in the db (or only the specified table)\r
+     * and optionally run ANALYZE.\r
+     *\r
+     * @param string $table table name (all the tables if empty)\r
+     * @param array  $options an array with driver-specific options:\r
+     *               - timeout [int] (in seconds) [mssql-only]\r
+     *               - analyze [boolean] [pgsql and mysql]\r
+     *               - full [boolean] [pgsql-only]\r
+     *               - freeze [boolean] [pgsql-only]\r
+     *\r
+     * @return mixed MDB2_OK success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function vacuum($table = null, $options = array())\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+        $query = 'VACUUM';\r
+\r
+        if (!empty($options['full'])) {\r
+            $query .= ' FULL';\r
+        }\r
+        if (!empty($options['freeze'])) {\r
+            $query .= ' FREEZE';\r
+        }\r
+        if (!empty($options['analyze'])) {\r
+            $query .= ' ANALYZE';\r
+        }\r
+\r
+        if (!empty($table)) {\r
+            $query .= ' '.$db->quoteIdentifier($table, true);\r
+        }\r
+        return $db->exec($query);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ alterTable()\r
+\r
+    /**\r
+     * alter an existing table\r
+     *\r
+     * @param string $name         name of the table that is intended to be changed.\r
+     * @param array $changes     associative array that contains the details of each type\r
+     *                             of change that is intended to be performed. The types of\r
+     *                             changes that are currently supported are defined as follows:\r
+     *\r
+     *                             name\r
+     *\r
+     *                                New name for the table.\r
+     *\r
+     *                            add\r
+     *\r
+     *                                Associative array with the names of fields to be added as\r
+     *                                 indexes of the array. The value of each entry of the array\r
+     *                                 should be set to another associative array with the properties\r
+     *                                 of the fields to be added. The properties of the fields should\r
+     *                                 be the same as defined by the MDB2 parser.\r
+     *\r
+     *\r
+     *                            remove\r
+     *\r
+     *                                Associative array with the names of fields to be removed as indexes\r
+     *                                 of the array. Currently the values assigned to each entry are ignored.\r
+     *                                 An empty array should be used for future compatibility.\r
+     *\r
+     *                            rename\r
+     *\r
+     *                                Associative array with the names of fields to be renamed as indexes\r
+     *                                 of the array. The value of each entry of the array should be set to\r
+     *                                 another associative array with the entry named name with the new\r
+     *                                 field name and the entry named Declaration that is expected to contain\r
+     *                                 the portion of the field declaration already in DBMS specific SQL code\r
+     *                                 as it is used in the CREATE TABLE statement.\r
+     *\r
+     *                            change\r
+     *\r
+     *                                Associative array with the names of the fields to be changed as indexes\r
+     *                                 of the array. Keep in mind that if it is intended to change either the\r
+     *                                 name of a field and any other properties, the change array entries\r
+     *                                 should have the new names of the fields as array indexes.\r
+     *\r
+     *                                The value of each entry of the array should be set to another associative\r
+     *                                 array with the properties of the fields to that are meant to be changed as\r
+     *                                 array entries. These entries should be assigned to the new values of the\r
+     *                                 respective properties. The properties of the fields should be the same\r
+     *                                 as defined by the MDB2 parser.\r
+     *\r
+     *                            Example\r
+     *                                array(\r
+     *                                    'name' => 'userlist',\r
+     *                                    'add' => array(\r
+     *                                        'quota' => array(\r
+     *                                            'type' => 'integer',\r
+     *                                            'unsigned' => 1\r
+     *                                        )\r
+     *                                    ),\r
+     *                                    'remove' => array(\r
+     *                                        'file_limit' => array(),\r
+     *                                        'time_limit' => array()\r
+     *                                    ),\r
+     *                                    'change' => array(\r
+     *                                        'name' => array(\r
+     *                                            'length' => '20',\r
+     *                                            'definition' => array(\r
+     *                                                'type' => 'text',\r
+     *                                                'length' => 20,\r
+     *                                            ),\r
+     *                                        )\r
+     *                                    ),\r
+     *                                    'rename' => array(\r
+     *                                        'sex' => array(\r
+     *                                            'name' => 'gender',\r
+     *                                            'definition' => array(\r
+     *                                                'type' => 'text',\r
+     *                                                'length' => 1,\r
+     *                                                'default' => 'M',\r
+     *                                            ),\r
+     *                                        )\r
+     *                                    )\r
+     *                                )\r
+     *\r
+     * @param boolean $check     indicates whether the function should just check if the DBMS driver\r
+     *                             can perform the requested table alterations if the value is true or\r
+     *                             actually perform them otherwise.\r
+     * @access public\r
+     *\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     */\r
+    function alterTable($name, $changes, $check)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        foreach ($changes as $change_name => $change) {\r
+            switch ($change_name) {\r
+            case 'add':\r
+            case 'remove':\r
+            case 'change':\r
+            case 'name':\r
+            case 'rename':\r
+                break;\r
+            default:\r
+                return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,\r
+                    'change type "'.$change_name.'\" not yet supported', __FUNCTION__);\r
+            }\r
+        }\r
+\r
+        if ($check) {\r
+            return MDB2_OK;\r
+        }\r
+\r
+        $name = $db->quoteIdentifier($name, true);\r
+\r
+        if (!empty($changes['remove']) && is_array($changes['remove'])) {\r
+            foreach ($changes['remove'] as $field_name => $field) {\r
+                $field_name = $db->quoteIdentifier($field_name, true);\r
+                $query = 'DROP ' . $field_name;\r
+                $result = $db->exec("ALTER TABLE $name $query");\r
+                if (PEAR::isError($result)) {\r
+                    return $result;\r
+                }\r
+            }\r
+        }\r
+\r
+        if (!empty($changes['rename']) && is_array($changes['rename'])) {\r
+            foreach ($changes['rename'] as $field_name => $field) {\r
+                $field_name = $db->quoteIdentifier($field_name, true);\r
+                $result = $db->exec("ALTER TABLE $name RENAME COLUMN $field_name TO ".$db->quoteIdentifier($field['name'], true));\r
+                if (PEAR::isError($result)) {\r
+                    return $result;\r
+                }\r
+            }\r
+        }\r
+\r
+        if (!empty($changes['add']) && is_array($changes['add'])) {\r
+            foreach ($changes['add'] as $field_name => $field) {\r
+                $query = 'ADD ' . $db->getDeclaration($field['type'], $field_name, $field);\r
+                $result = $db->exec("ALTER TABLE $name $query");\r
+                if (PEAR::isError($result)) {\r
+                    return $result;\r
+                }\r
+            }\r
+        }\r
+\r
+        if (!empty($changes['change']) && is_array($changes['change'])) {\r
+            foreach ($changes['change'] as $field_name => $field) {\r
+                $field_name = $db->quoteIdentifier($field_name, true);\r
+                if (!empty($field['definition']['type'])) {\r
+                    $server_info = $db->getServerVersion();\r
+                    if (PEAR::isError($server_info)) {\r
+                        return $server_info;\r
+                    }\r
+                    if (is_array($server_info) && $server_info['major'] < 8) {\r
+                        return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,\r
+                            'changing column type for "'.$change_name.'\" requires PostgreSQL 8.0 or above', __FUNCTION__);\r
+                    }\r
+                    $db->loadModule('Datatype', null, true);\r
+                    $type = $db->datatype->getTypeDeclaration($field['definition']);\r
+                    $query = "ALTER $field_name TYPE $type USING CAST($field_name AS $type)";\r
+                    $result = $db->exec("ALTER TABLE $name $query");\r
+                    if (PEAR::isError($result)) {\r
+                        return $result;\r
+                    }\r
+                }\r
+                if (array_key_exists('default', $field['definition'])) {\r
+                    $query = "ALTER $field_name SET DEFAULT ".$db->quote($field['definition']['default'], $field['definition']['type']);\r
+                    $result = $db->exec("ALTER TABLE $name $query");\r
+                    if (PEAR::isError($result)) {\r
+                        return $result;\r
+                    }\r
+                }\r
+                if (array_key_exists('notnull', $field['definition'])) {\r
+                    $query = "ALTER $field_name ".($field['definition']['notnull'] ? 'SET' : 'DROP').' NOT NULL';\r
+                    $result = $db->exec("ALTER TABLE $name $query");\r
+                    if (PEAR::isError($result)) {\r
+                        return $result;\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+        if (!empty($changes['name'])) {\r
+            $change_name = $db->quoteIdentifier($changes['name'], true);\r
+            $result = $db->exec("ALTER TABLE $name RENAME TO ".$change_name);\r
+            if (PEAR::isError($result)) {\r
+                return $result;\r
+            }\r
+        }\r
+\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listDatabases()\r
+\r
+    /**\r
+     * list all databases\r
+     *\r
+     * @return mixed array of database names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listDatabases()\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = 'SELECT datname FROM pg_database';\r
+        $result2 = $db->standaloneQuery($query, array('text'), false);\r
+        if (!MDB2::isResultCommon($result2)) {\r
+            return $result2;\r
+        }\r
+\r
+        $result = $result2->fetchCol();\r
+        $result2->free();\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listUsers()\r
+\r
+    /**\r
+     * list all users\r
+     *\r
+     * @return mixed array of user names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listUsers()\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = 'SELECT usename FROM pg_user';\r
+        $result2 = $db->standaloneQuery($query, array('text'), false);\r
+        if (!MDB2::isResultCommon($result2)) {\r
+            return $result2;\r
+        }\r
+\r
+        $result = $result2->fetchCol();\r
+        $result2->free();\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listViews()\r
+\r
+    /**\r
+     * list all views in the current database\r
+     *\r
+     * @return mixed array of view names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listViews()\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = "SELECT viewname\r
+                    FROM pg_views\r
+                   WHERE schemaname NOT IN ('pg_catalog', 'information_schema')\r
+                     AND viewname !~ '^pg_'";\r
+        $result = $db->queryCol($query);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTableViews()\r
+\r
+    /**\r
+     * list the views in the database that reference a given table\r
+     *\r
+     * @param string table for which all referenced views should be found\r
+     * @return mixed array of view names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTableViews($table)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = 'SELECT viewname FROM pg_views NATURAL JOIN pg_tables';\r
+        $query.= ' WHERE tablename ='.$db->quote($table, 'text');\r
+        $result = $db->queryCol($query);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listFunctions()\r
+\r
+    /**\r
+     * list all functions in the current database\r
+     *\r
+     * @return mixed array of function names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listFunctions()\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = "\r
+            SELECT\r
+                proname\r
+            FROM\r
+                pg_proc pr,\r
+                pg_type tp\r
+            WHERE\r
+                tp.oid = pr.prorettype\r
+                AND pr.proisagg = FALSE\r
+                AND tp.typname <> 'trigger'\r
+                AND pr.pronamespace IN\r
+                    (SELECT oid FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema')";\r
+        $result = $db->queryCol($query);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTableTriggers()\r
+\r
+    /**\r
+     * list all triggers in the database that reference a given table\r
+     *\r
+     * @param string table for which all referenced triggers should be found\r
+     * @return mixed array of trigger names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTableTriggers($table = null)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = 'SELECT trg.tgname AS trigger_name\r
+                    FROM pg_trigger trg,\r
+                         pg_class tbl\r
+                   WHERE trg.tgrelid = tbl.oid';\r
+        if (null !== $table) {\r
+            $table = $db->quote(strtoupper($table), 'text');\r
+            $query .= " AND UPPER(tbl.relname) = $table";\r
+        }\r
+        $result = $db->queryCol($query);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTables()\r
+\r
+    /**\r
+     * list all tables in the current database\r
+     *\r
+     * @return mixed array of table names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTables()\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        // gratuitously stolen from PEAR DB _getSpecialQuery in pgsql.php\r
+        $query = 'SELECT c.relname AS "Name"'\r
+            . ' FROM pg_class c, pg_user u'\r
+            . ' WHERE c.relowner = u.usesysid'\r
+            . " AND c.relkind = 'r'"\r
+            . ' AND NOT EXISTS'\r
+            . ' (SELECT 1 FROM pg_views'\r
+            . '  WHERE viewname = c.relname)'\r
+            . " AND c.relname !~ '^(pg_|sql_)'"\r
+            . ' UNION'\r
+            . ' SELECT c.relname AS "Name"'\r
+            . ' FROM pg_class c'\r
+            . " WHERE c.relkind = 'r'"\r
+            . ' AND NOT EXISTS'\r
+            . ' (SELECT 1 FROM pg_views'\r
+            . '  WHERE viewname = c.relname)'\r
+            . ' AND NOT EXISTS'\r
+            . ' (SELECT 1 FROM pg_user'\r
+            . '  WHERE usesysid = c.relowner)'\r
+            . " AND c.relname !~ '^pg_'";\r
+        $result = $db->queryCol($query);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTableFields()\r
+\r
+    /**\r
+     * list all fields in a table in the current database\r
+     *\r
+     * @param string $table name of table that should be used in method\r
+     * @return mixed array of field names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTableFields($table)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        list($schema, $table) = $this->splitTableSchema($table);\r
+\r
+        $table = $db->quoteIdentifier($table, true);\r
+        if (!empty($schema)) {\r
+            $table = $db->quoteIdentifier($schema, true) . '.' .$table;\r
+        }\r
+        $db->setLimit(1);\r
+        $result2 = $db->query("SELECT * FROM $table");\r
+        if (PEAR::isError($result2)) {\r
+            return $result2;\r
+        }\r
+        $result = $result2->getColumnNames();\r
+        $result2->free();\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        return array_flip($result);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTableIndexes()\r
+\r
+    /**\r
+     * list all indexes in a table\r
+     *\r
+     * @param string $table name of table that should be used in method\r
+     * @return mixed array of index names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTableIndexes($table)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        list($schema, $table) = $this->splitTableSchema($table);\r
+\r
+        $table = $db->quote($table, 'text');\r
+        $subquery = "SELECT indexrelid\r
+                       FROM pg_index\r
+                  LEFT JOIN pg_class ON pg_class.oid = pg_index.indrelid\r
+                  LEFT JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid\r
+                      WHERE pg_class.relname = $table\r
+                        AND indisunique != 't'\r
+                        AND indisprimary != 't'";\r
+        if (!empty($schema)) {\r
+            $subquery .= ' AND pg_namespace.nspname = '.$db->quote($schema, 'text');\r
+        }\r
+        $query = "SELECT relname FROM pg_class WHERE oid IN ($subquery)";\r
+        $indexes = $db->queryCol($query, 'text');\r
+        if (PEAR::isError($indexes)) {\r
+            return $indexes;\r
+        }\r
+\r
+        $result = array();\r
+        foreach ($indexes as $index) {\r
+            $index = $this->_fixIndexName($index);\r
+            if (!empty($index)) {\r
+                $result[$index] = true;\r
+            }\r
+        }\r
+\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_change_key_case($result, $db->options['field_case']);\r
+        }\r
+        return array_keys($result);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ dropConstraint()\r
+\r
+    /**\r
+     * drop existing constraint\r
+     *\r
+     * @param string $table   name of table that should be used in method\r
+     * @param string $name    name of the constraint to be dropped\r
+     * @param string $primary hint if the constraint is primary\r
+     *\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function dropConstraint($table, $name, $primary = false)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        // is it an UNIQUE index?\r
+        $query = 'SELECT relname\r
+                    FROM pg_class\r
+                   WHERE oid IN (\r
+                         SELECT indexrelid\r
+                           FROM pg_index, pg_class\r
+                          WHERE pg_class.relname = '.$db->quote($table, 'text').'\r
+                            AND pg_class.oid = pg_index.indrelid\r
+                            AND indisunique = \'t\')\r
+                  EXCEPT\r
+                  SELECT conname\r
+                   FROM pg_constraint, pg_class\r
+                  WHERE pg_constraint.conrelid = pg_class.oid\r
+                    AND relname = '. $db->quote($table, 'text');\r
+        $unique = $db->queryCol($query, 'text');\r
+        if (PEAR::isError($unique) || empty($unique)) {\r
+            // not an UNIQUE index, maybe a CONSTRAINT\r
+            return parent::dropConstraint($table, $name, $primary);\r
+        }\r
+\r
+        if (in_array($name, $unique)) {\r
+            return $db->exec('DROP INDEX '.$db->quoteIdentifier($name, true));\r
+        }\r
+        $idxname = $db->getIndexName($name);\r
+        if (in_array($idxname, $unique)) {\r
+            return $db->exec('DROP INDEX '.$db->quoteIdentifier($idxname, true));\r
+        }\r
+        return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+            $name . ' is not an existing constraint for table ' . $table, __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTableConstraints()\r
+\r
+    /**\r
+     * list all constraints in a table\r
+     *\r
+     * @param string $table name of table that should be used in method\r
+     * @return mixed array of constraint names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTableConstraints($table)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        list($schema, $table) = $this->splitTableSchema($table);\r
+\r
+        $table = $db->quote($table, 'text');\r
+        $query = 'SELECT conname\r
+                    FROM pg_constraint\r
+               LEFT JOIN pg_class ON pg_constraint.conrelid = pg_class.oid\r
+               LEFT JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid\r
+                   WHERE relname = ' .$table;\r
+        if (!empty($schema)) {\r
+            $query .= ' AND pg_namespace.nspname = ' . $db->quote($schema, 'text');\r
+        }\r
+        $query .= '\r
+                   UNION DISTINCT\r
+                  SELECT relname\r
+                    FROM pg_class\r
+                   WHERE oid IN (\r
+                         SELECT indexrelid\r
+                           FROM pg_index\r
+                      LEFT JOIN pg_class ON pg_class.oid = pg_index.indrelid\r
+                      LEFT JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid\r
+                          WHERE pg_class.relname = '.$table.'\r
+                            AND indisunique = \'t\'';\r
+        if (!empty($schema)) {\r
+            $query .= ' AND pg_namespace.nspname = ' . $db->quote($schema, 'text');\r
+        }\r
+        $query .= ')';\r
+        $constraints = $db->queryCol($query);\r
+        if (PEAR::isError($constraints)) {\r
+            return $constraints;\r
+        }\r
+\r
+        $result = array();\r
+        foreach ($constraints as $constraint) {\r
+            $constraint = $this->_fixIndexName($constraint);\r
+            if (!empty($constraint)) {\r
+                $result[$constraint] = true;\r
+            }\r
+        }\r
+\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE\r
+            && $db->options['field_case'] == CASE_LOWER\r
+        ) {\r
+            $result = array_change_key_case($result, $db->options['field_case']);\r
+        }\r
+        return array_keys($result);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ createSequence()\r
+\r
+    /**\r
+     * create sequence\r
+     *\r
+     * @param string $seq_name name of the sequence to be created\r
+     * @param string $start start value of the sequence; default is 1\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function createSequence($seq_name, $start = 1)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);\r
+        return $db->exec("CREATE SEQUENCE $sequence_name INCREMENT 1".\r
+            ($start < 1 ? " MINVALUE $start" : '')." START $start");\r
+    }\r
+\r
+    // }}}\r
+    // {{{ dropSequence()\r
+\r
+    /**\r
+     * drop existing sequence\r
+     *\r
+     * @param string $seq_name name of the sequence to be dropped\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function dropSequence($seq_name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);\r
+        return $db->exec("DROP SEQUENCE $sequence_name");\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listSequences()\r
+\r
+    /**\r
+     * list all sequences in the current database\r
+     *\r
+     * @return mixed array of sequence names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listSequences()\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = "SELECT relname FROM pg_class WHERE relkind = 'S' AND relnamespace IN";\r
+        $query.= "(SELECT oid FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema')";\r
+        $table_names = $db->queryCol($query);\r
+        if (PEAR::isError($table_names)) {\r
+            return $table_names;\r
+        }\r
+        $result = array();\r
+        foreach ($table_names as $table_name) {\r
+            $result[] = $this->_fixSequenceName($table_name);\r
+        }\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);\r
+        }\r
+        return $result;\r
+    }\r
+}\r
 ?>
\ No newline at end of file
index 1b7239876f115f29d7f2cbc637b073186ee555ff..c4c30c9ddad3b4a0d5b07e4d1440825eaf435088 100644 (file)
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith, Lorenzo Alberton                       |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Authors: Lukas Smith <smith@pooteeweet.org>                          |
-// |          Lorenzo Alberton <l.alberton@quipo.it>                      |
-// +----------------------------------------------------------------------+
-//
-// $Id: sqlite.php,v 1.76 2008/05/31 11:48:48 quipo Exp $
-//
-
-require_once('MDB2/Driver/Manager/Common.php');
-
-/**
- * MDB2 SQLite driver for the management modules
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- * @author  Lorenzo Alberton <l.alberton@quipo.it>
- */
-class MDB2_Driver_Manager_sqlite extends MDB2_Driver_Manager_Common
-{
-    // {{{ createDatabase()
-
-    /**
-     * create a new database
-     *
-     * @param string $name    name of the database that should be created
-     * @param array  $options array with charset info
-     *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function createDatabase($name, $options = array())
-    {
-               $datadir=OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" );
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $database_file = $db->_getDatabaseFile($name);
-        if (file_exists($database_file)) {
-            return $db->raiseError(MDB2_ERROR_ALREADY_EXISTS, null, null,
-                'database already exists', __FUNCTION__);
-        }
-        $php_errormsg = '';
-        $database_file="$datadir/$database_file.db";
-        $handle = sqlite_open($database_file, $db->dsn['mode'], $php_errormsg);
-        if (!$handle) {
-            return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
-                (isset($php_errormsg) ? $php_errormsg : 'could not create the database file'), __FUNCTION__);
-        }
-        if (!empty($options['charset'])) {
-            $query = 'PRAGMA encoding = ' . $db->quote($options['charset'], 'text');
-            @sqlite_query($query, $handle);
-        }
-        @sqlite_close($handle);
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ dropDatabase()
-
-    /**
-     * drop an existing database
-     *
-     * @param string $name name of the database that should be dropped
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function dropDatabase($name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $database_file = $db->_getDatabaseFile($name);
-        if (!@file_exists($database_file)) {
-            return $db->raiseError(MDB2_ERROR_CANNOT_DROP, null, null,
-                'database does not exist', __FUNCTION__);
-        }
-        $result = @unlink($database_file);
-        if (!$result) {
-            return $db->raiseError(MDB2_ERROR_CANNOT_DROP, null, null,
-                (isset($php_errormsg) ? $php_errormsg : 'could not remove the database file'), __FUNCTION__);
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ _getAdvancedFKOptions()
-
-    /**
-     * Return the FOREIGN KEY query section dealing with non-standard options
-     * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
-     *
-     * @param array $definition
-     * @return string
-     * @access protected
-     */
-    function _getAdvancedFKOptions($definition)
-    {
-        $query = '';
-        if (!empty($definition['match'])) {
-            $query .= ' MATCH '.$definition['match'];
-        }
-        if (!empty($definition['onupdate']) && (strtoupper($definition['onupdate']) != 'NO ACTION')) {
-            $query .= ' ON UPDATE '.$definition['onupdate'];
-        }
-        if (!empty($definition['ondelete']) && (strtoupper($definition['ondelete']) != 'NO ACTION')) {
-            $query .= ' ON DELETE '.$definition['ondelete'];
-        }
-        if (!empty($definition['deferrable'])) {
-            $query .= ' DEFERRABLE';
-        } else {
-            $query .= ' NOT DEFERRABLE';
-        }
-        if (!empty($definition['initiallydeferred'])) {
-            $query .= ' INITIALLY DEFERRED';
-        } else {
-            $query .= ' INITIALLY IMMEDIATE';
-        }
-        return $query;
-    }
-
-    // }}}
-    // {{{ _getCreateTableQuery()
-
-    /**
-     * Create a basic SQL query for a new table creation
-     * @param string $name   Name of the database that should be created
-     * @param array $fields  Associative array that contains the definition of each field of the new table
-     * @param array $options  An associative array of table options
-     * @return mixed string (the SQL query) on success, a MDB2 error on failure
-     * @see createTable()
-     */
-    function _getCreateTableQuery($name, $fields, $options = array())
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        if (!$name) {
-            return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
-                'no valid table name specified', __FUNCTION__);
-        }
-        if (empty($fields)) {
-            return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
-                'no fields specified for table "'.$name.'"', __FUNCTION__);
-        }
-        $query_fields = $this->getFieldDeclarationList($fields);
-        if (PEAR::isError($query_fields)) {
-            return $query_fields;
-        }
-        if (!empty($options['primary'])) {
-            $query_fields.= ', PRIMARY KEY ('.implode(', ', array_keys($options['primary'])).')';
-        }
-        if (!empty($options['foreign_keys'])) {
-            foreach ($options['foreign_keys'] as $fkname => $fkdef) {
-                if (empty($fkdef)) {
-                    continue;
-                }
-                $query_fields.= ', CONSTRAINT '.$fkname.' FOREIGN KEY ('.implode(', ', array_keys($fkdef['fields'])).')';
-                $query_fields.= ' REFERENCES '.$fkdef['references']['table'].' ('.implode(', ', array_keys($fkdef['references']['fields'])).')';
-                $query_fields.= $this->_getAdvancedFKOptions($fkdef);
-            }
-        }
-
-        $name = $db->quoteIdentifier($name, true);
-        $result = 'CREATE ';
-        if (!empty($options['temporary'])) {
-            $result .= $this->_getTemporaryTableQuery();
-        }
-        $result .= " TABLE $name ($query_fields)";
-        return $result;
-    }
-
-    // }}}
-    // {{{ createTable()
-
-    /**
-     * create a new table
-     *
-     * @param string $name    Name of the database that should be created
-     * @param array  $fields  Associative array that contains the definition
-     *                        of each field of the new table
-     * @param array  $options An associative array of table options
-     *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function createTable($name, $fields, $options = array())
-    {
-        $result = parent::createTable($name, $fields, $options);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        // create triggers to enforce FOREIGN KEY constraints
-        if (!empty($options['foreign_keys'])) {
-            $db =$this->getDBInstance();
-            if (PEAR::isError($db)) {
-                return $db;
-            }
-            foreach ($options['foreign_keys'] as $fkname => $fkdef) {
-                if (empty($fkdef)) {
-                    continue;
-                }
-                //set actions to default if not set
-                $fkdef['onupdate'] = empty($fkdef['onupdate']) ? $db->options['default_fk_action_onupdate'] : strtoupper($fkdef['onupdate']);
-                $fkdef['ondelete'] = empty($fkdef['ondelete']) ? $db->options['default_fk_action_ondelete'] : strtoupper($fkdef['ondelete']);
-
-                $trigger_names = array(
-                    'insert'    => $fkname.'_insert_trg',
-                    'update'    => $fkname.'_update_trg',
-                    'pk_update' => $fkname.'_pk_update_trg',
-                    'pk_delete' => $fkname.'_pk_delete_trg',
-                );
-                
-                //create the [insert|update] triggers on the FK table
-                $table_fields = array_keys($fkdef['fields']);
-                $referenced_fields = array_keys($fkdef['references']['fields']);
-                $query = 'CREATE TRIGGER %s BEFORE %s ON '.$name
-                        .' FOR EACH ROW BEGIN'
-                        .' SELECT RAISE(ROLLBACK, \'%s on table "'.$name.'" violates FOREIGN KEY constraint "'.$fkname.'"\')'
-                        .' WHERE  (SELECT ';
-                $aliased_fields = array();
-                foreach ($referenced_fields as $field) {
-                    $aliased_fields[] = $fkdef['references']['table'] .'.'.$field .' AS '.$field;
-                }
-                $query .= implode(',', $aliased_fields)
-                       .' FROM '.$fkdef['references']['table']
-                       .' WHERE ';
-                $conditions = array();
-                for ($i=0; $i<count($table_fields); $i++) {
-                    $conditions[] = $referenced_fields[$i] .' = NEW.'.$table_fields[$i];
-                }
-                $query .= implode(' AND ', $conditions).') IS NULL; END;';
-                $result = $db->exec(sprintf($query, $trigger_names['insert'], 'INSERT', 'insert'));
-                if (PEAR::isError($result)) {
-                    return $result;
-                }
-
-                $result = $db->exec(sprintf($query, $trigger_names['update'], 'UPDATE', 'update'));
-                if (PEAR::isError($result)) {
-                    return $result;
-                }
-                
-                //create the ON [UPDATE|DELETE] triggers on the primary table
-                $restrict_action = 'SELECT RAISE(ROLLBACK, \'%s on table "'.$name.'" violates FOREIGN KEY constraint "'.$fkname.'"\')'
-                                  .' WHERE  (SELECT ';
-                $aliased_fields = array();
-                foreach ($table_fields as $field) {
-                    $aliased_fields[] = $name .'.'.$field .' AS '.$field;
-                }
-                $restrict_action .= implode(',', $aliased_fields)
-                       .' FROM '.$name
-                       .' WHERE ';
-                $conditions  = array();
-                $new_values  = array();
-                $null_values = array();
-                for ($i=0; $i<count($table_fields); $i++) {
-                    $conditions[]  = $table_fields[$i] .' = OLD.'.$referenced_fields[$i];
-                    $new_values[]  = $table_fields[$i] .' = NEW.'.$referenced_fields[$i];
-                    $null_values[] = $table_fields[$i] .' = NULL';
-                }
-                $conditions2 = array();
-                for ($i=0; $i<count($referenced_fields); $i++) {
-                    $conditions2[]  = 'NEW.'.$referenced_fields[$i] .' <> OLD.'.$referenced_fields[$i];
-                }
-                $restrict_action .= implode(' AND ', $conditions).') IS NOT NULL'
-                                 .' AND (' .implode(' OR ', $conditions2) .')';
-
-                $cascade_action_update = 'UPDATE '.$name.' SET '.implode(', ', $new_values) .' WHERE '.implode(' AND ', $conditions);
-                $cascade_action_delete = 'DELETE FROM '.$name.' WHERE '.implode(' AND ', $conditions);
-                $setnull_action        = 'UPDATE '.$name.' SET '.implode(', ', $null_values).' WHERE '.implode(' AND ', $conditions);
-
-                if ('SET DEFAULT' == $fkdef['onupdate'] || 'SET DEFAULT' == $fkdef['ondelete']) {
-                    $db->loadModule('Reverse', null, true);
-                    $default_values = array();
-                    foreach ($table_fields as $table_field) {
-                        $field_definition = $db->reverse->getTableFieldDefinition($name, $field);
-                        if (PEAR::isError($field_definition)) {
-                            return $field_definition;
-                        }
-                        $default_values[] = $table_field .' = '. $field_definition[0]['default'];
-                    }
-                    $setdefault_action = 'UPDATE '.$name.' SET '.implode(', ', $default_values).' WHERE '.implode(' AND ', $conditions);
-                }
-
-                $query = 'CREATE TRIGGER %s'
-                        .' %s ON '.$fkdef['references']['table']
-                        .' FOR EACH ROW BEGIN ';
-
-                if ('CASCADE' == $fkdef['onupdate']) {
-                    $sql_update = sprintf($query, $trigger_names['pk_update'], 'AFTER UPDATE',  'update') . $cascade_action_update. '; END;';
-                } elseif ('SET NULL' == $fkdef['onupdate']) {
-                    $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setnull_action. '; END;';
-                } elseif ('SET DEFAULT' == $fkdef['onupdate']) {
-                    $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setdefault_action. '; END;';
-                } elseif ('NO ACTION' == $fkdef['onupdate']) {
-                    $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'AFTER UPDATE', 'update') . '; END;';
-                } elseif ('RESTRICT' == $fkdef['onupdate']) {
-                    $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . '; END;';
-                }
-                if ('CASCADE' == $fkdef['ondelete']) {
-                    $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'AFTER DELETE',  'delete') . $cascade_action_delete. '; END;';
-                } elseif ('SET NULL' == $fkdef['ondelete']) {
-                    $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setnull_action. '; END;';
-                } elseif ('SET DEFAULT' == $fkdef['ondelete']) {
-                    $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setdefault_action. '; END;';
-                } elseif ('NO ACTION' == $fkdef['ondelete']) {
-                    $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete')  . '; END;';
-                } elseif ('RESTRICT' == $fkdef['ondelete']) {
-                    $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . '; END;';
-                }
-
-                if (PEAR::isError($result)) {
-                    return $result;
-                }
-                $result = $db->exec($sql_delete);
-                if (PEAR::isError($result)) {
-                    return $result;
-                }
-                $result = $db->exec($sql_update);
-                if (PEAR::isError($result)) {
-                    return $result;
-                }
-            }
-        }
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ dropTable()
-
-    /**
-     * drop an existing table
-     *
-     * @param string $name name of the table that should be dropped
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function dropTable($name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-        
-        //delete the triggers associated to existing FK constraints
-        $constraints = $this->listTableConstraints($name);
-        if (!PEAR::isError($constraints) && !empty($constraints)) {
-            $db->loadModule('Reverse', null, true);
-            foreach ($constraints as $constraint) {
-                $definition = $db->reverse->getTableConstraintDefinition($name, $constraint);
-                if (!PEAR::isError($definition) && !empty($definition['foreign'])) {
-                    $result = $this->_dropFKTriggers($name, $constraint, $definition['references']['table']);
-                    if (PEAR::isError($result)) {
-                        return $result;
-                    }
-                }
-            }
-        }
-
-        $name = $db->quoteIdentifier($name, true);
-        return $db->exec("DROP TABLE $name");
-    }
-
-    // }}}
-    // {{{ vacuum()
-
-    /**
-     * Optimize (vacuum) all the tables in the db (or only the specified table)
-     * and optionally run ANALYZE.
-     *
-     * @param string $table table name (all the tables if empty)
-     * @param array  $options an array with driver-specific options:
-     *               - timeout [int] (in seconds) [mssql-only]
-     *               - analyze [boolean] [pgsql and mysql]
-     *               - full [boolean] [pgsql-only]
-     *               - freeze [boolean] [pgsql-only]
-     *
-     * @return mixed MDB2_OK success, a MDB2 error on failure
-     * @access public
-     */
-    function vacuum($table = null, $options = array())
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = 'VACUUM';
-        if (!empty($table)) {
-            $query .= ' '.$db->quoteIdentifier($table, true);
-        }
-        return $db->exec($query);
-    }
-
-    // }}}
-    // {{{ alterTable()
-
-    /**
-     * alter an existing table
-     *
-     * @param string $name         name of the table that is intended to be changed.
-     * @param array $changes     associative array that contains the details of each type
-     *                             of change that is intended to be performed. The types of
-     *                             changes that are currently supported are defined as follows:
-     *
-     *                             name
-     *
-     *                                New name for the table.
-     *
-     *                            add
-     *
-     *                                Associative array with the names of fields to be added as
-     *                                 indexes of the array. The value of each entry of the array
-     *                                 should be set to another associative array with the properties
-     *                                 of the fields to be added. The properties of the fields should
-     *                                 be the same as defined by the MDB2 parser.
-     *
-     *
-     *                            remove
-     *
-     *                                Associative array with the names of fields to be removed as indexes
-     *                                 of the array. Currently the values assigned to each entry are ignored.
-     *                                 An empty array should be used for future compatibility.
-     *
-     *                            rename
-     *
-     *                                Associative array with the names of fields to be renamed as indexes
-     *                                 of the array. The value of each entry of the array should be set to
-     *                                 another associative array with the entry named name with the new
-     *                                 field name and the entry named Declaration that is expected to contain
-     *                                 the portion of the field declaration already in DBMS specific SQL code
-     *                                 as it is used in the CREATE TABLE statement.
-     *
-     *                            change
-     *
-     *                                Associative array with the names of the fields to be changed as indexes
-     *                                 of the array. Keep in mind that if it is intended to change either the
-     *                                 name of a field and any other properties, the change array entries
-     *                                 should have the new names of the fields as array indexes.
-     *
-     *                                The value of each entry of the array should be set to another associative
-     *                                 array with the properties of the fields to that are meant to be changed as
-     *                                 array entries. These entries should be assigned to the new values of the
-     *                                 respective properties. The properties of the fields should be the same
-     *                                 as defined by the MDB2 parser.
-     *
-     *                            Example
-     *                                array(
-     *                                    'name' => 'userlist',
-     *                                    'add' => array(
-     *                                        'quota' => array(
-     *                                            'type' => 'integer',
-     *                                            'unsigned' => 1
-     *                                        )
-     *                                    ),
-     *                                    'remove' => array(
-     *                                        'file_limit' => array(),
-     *                                        'time_limit' => array()
-     *                                    ),
-     *                                    'change' => array(
-     *                                        'name' => array(
-     *                                            'length' => '20',
-     *                                            'definition' => array(
-     *                                                'type' => 'text',
-     *                                                'length' => 20,
-     *                                            ),
-     *                                        )
-     *                                    ),
-     *                                    'rename' => array(
-     *                                        'sex' => array(
-     *                                            'name' => 'gender',
-     *                                            'definition' => array(
-     *                                                'type' => 'text',
-     *                                                'length' => 1,
-     *                                                'default' => 'M',
-     *                                            ),
-     *                                        )
-     *                                    )
-     *                                )
-     *
-     * @param boolean $check     indicates whether the function should just check if the DBMS driver
-     *                             can perform the requested table alterations if the value is true or
-     *                             actually perform them otherwise.
-     * @access public
-     *
-      * @return mixed MDB2_OK on success, a MDB2 error on failure
-     */
-    function alterTable($name, $changes, $check, $options = array())
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        foreach ($changes as $change_name => $change) {
-            switch ($change_name) {
-            case 'add':
-            case 'remove':
-            case 'change':
-            case 'name':
-            case 'rename':
-                break;
-            default:
-                return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
-                    'change type "'.$change_name.'" not yet supported', __FUNCTION__);
-            }
-        }
-
-        if ($check) {
-            return MDB2_OK;
-        }
-
-        $db->loadModule('Reverse', null, true);
-
-        // actually sqlite 2.x supports no ALTER TABLE at all .. so we emulate it
-        $fields = $db->manager->listTableFields($name);
-        if (PEAR::isError($fields)) {
-            return $fields;
-        }
-
-        $fields = array_flip($fields);
-        foreach ($fields as $field => $value) {
-            $definition = $db->reverse->getTableFieldDefinition($name, $field);
-            if (PEAR::isError($definition)) {
-                return $definition;
-            }
-            $fields[$field] = $definition[0];
-        }
-
-        $indexes = $db->manager->listTableIndexes($name);
-        if (PEAR::isError($indexes)) {
-            return $indexes;
-        }
-
-        $indexes = array_flip($indexes);
-        foreach ($indexes as $index => $value) {
-            $definition = $db->reverse->getTableIndexDefinition($name, $index);
-            if (PEAR::isError($definition)) {
-                return $definition;
-            }
-            $indexes[$index] = $definition;
-        }
-
-        $constraints = $db->manager->listTableConstraints($name);
-        if (PEAR::isError($constraints)) {
-            return $constraints;
-        }
-
-        if (!array_key_exists('foreign_keys', $options)) {
-            $options['foreign_keys'] = array();
-        }
-        $constraints = array_flip($constraints);
-        foreach ($constraints as $constraint => $value) {
-                       if (!empty($definition['primary'])) {
-                if (!array_key_exists('primary', $options)) {
-                    $options['primary'] = $definition['fields'];
-                    //remove from the $constraint array, it's already handled by createTable()
-                    unset($constraints[$constraint]);
-                }
-            } else {
-                $c_definition = $db->reverse->getTableConstraintDefinition($name, $constraint);
-                if (PEAR::isError($c_definition)) {
-                    return $c_definition;
-                }
-                if (!empty($c_definition['foreign'])) {
-                    if (!array_key_exists($constraint, $options['foreign_keys'])) {
-                        $options['foreign_keys'][$constraint] = $c_definition;
-                    }
-                    //remove from the $constraint array, it's already handled by createTable()
-                    unset($constraints[$constraint]);
-                } else {
-                    $constraints[$constraint] = $c_definition;
-                }
-            }
-        }
-
-        $name_new = $name;
-        $create_order = $select_fields = array_keys($fields);
-        foreach ($changes as $change_name => $change) {
-            switch ($change_name) {
-            case 'add':
-                foreach ($change as $field_name => $field) {
-                    $fields[$field_name] = $field;
-                    $create_order[] = $field_name;
-                }
-                break;
-            case 'remove':
-                foreach ($change as $field_name => $field) {
-                    unset($fields[$field_name]);
-                    $select_fields = array_diff($select_fields, array($field_name));
-                    $create_order = array_diff($create_order, array($field_name));
-                }
-                break;
-            case 'change':
-                foreach ($change as $field_name => $field) {
-                    $fields[$field_name] = $field['definition'];
-                }
-                break;
-            case 'name':
-                $name_new = $change;
-                break;
-            case 'rename':
-                foreach ($change as $field_name => $field) {
-                    unset($fields[$field_name]);
-                    $fields[$field['name']] = $field['definition'];
-                    $create_order[array_search($field_name, $create_order)] = $field['name'];
-                }
-                break;
-            default:
-                return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
-                    'change type "'.$change_name.'" not yet supported', __FUNCTION__);
-            }
-        }
-
-        $data = null;
-        if (!empty($select_fields)) {
-            $query = 'SELECT '.implode(', ', $select_fields).' FROM '.$db->quoteIdentifier($name, true);
-            $data = $db->queryAll($query, null, MDB2_FETCHMODE_ORDERED);
-        }
-
-        $result = $this->dropTable($name);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-
-        $result = $this->createTable($name_new, $fields, $options);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-
-        foreach ($indexes as $index => $definition) {
-            $this->createIndex($name_new, $index, $definition);
-        }
-
-        foreach ($constraints as $constraint => $definition) {
-                       if(empty($definition['primary']) and empty($definition['foreign'])){
-                               $this->createConstraint($name_new, $constraint, $definition);
-                       }
-        }
-
-        if (!empty($select_fields) && !empty($data)) {
-            $query = 'INSERT INTO '.$db->quoteIdentifier($name_new, true);
-            $query.= '('.implode(', ', array_slice(array_keys($fields), 0, count($select_fields))).')';
-            $query.=' VALUES (?'.str_repeat(', ?', (count($select_fields) - 1)).')';
-            $stmt =$db->prepare($query, null, MDB2_PREPARE_MANIP);
-            if (PEAR::isError($stmt)) {
-                return $stmt;
-            }
-            foreach ($data as $row) {
-                $result = $stmt->execute($row);
-                if (PEAR::isError($result)) {
-                    return $result;
-                }
-            }
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ listDatabases()
-
-    /**
-     * list all databases
-     *
-     * @return mixed array of database names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listDatabases()
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'list databases is not supported', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ listUsers()
-
-    /**
-     * list all users
-     *
-     * @return mixed array of user names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listUsers()
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'list databases is not supported', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ listViews()
-
-    /**
-     * list all views in the current database
-     *
-     * @return mixed array of view names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listViews($dummy=null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = "SELECT name FROM sqlite_master WHERE type='view' AND sql NOT NULL";
-        $result = $db->queryCol($query);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
-        }
-        return $result;
-    }
-
-    // }}}
-    // {{{ listTableViews()
-
-    /**
-     * list the views in the database that reference a given table
-     *
-     * @param string table for which all referenced views should be found
-     * @return mixed array of view names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTableViews($table)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL";
-        $views = $db->queryAll($query, array('text', 'text'), MDB2_FETCHMODE_ASSOC);
-        if (PEAR::isError($views)) {
-            return $views;
-        }
-        $result = array();
-        foreach ($views as $row) {
-            if (preg_match("/^create view .* \bfrom\b\s+\b{$table}\b /i", $row['sql'])) {
-                if (!empty($row['name'])) {
-                    $result[$row['name']] = true;
-                }
-            }
-        }
-
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_change_key_case($result, $db->options['field_case']);
-        }
-        return array_keys($result);
-    }
-
-    // }}}
-    // {{{ listTables()
-
-    /**
-     * list all tables in the current database
-     *
-     * @return mixed array of table names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTables($dummy=null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name";
-        $table_names = $db->queryCol($query);
-        if (PEAR::isError($table_names)) {
-            return $table_names;
-        }
-        $result = array();
-        foreach ($table_names as $table_name) {
-            if (!$this->_fixSequenceName($table_name, true)) {
-                $result[] = $table_name;
-            }
-        }
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
-        }
-        return $result;
-    }
-
-    // }}}
-    // {{{ listTableFields()
-
-    /**
-     * list all fields in a table in the current database
-     *
-     * @param string $table name of table that should be used in method
-     * @return mixed array of field names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTableFields($table)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $result = $db->loadModule('Reverse', null, true);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');
-        } else {
-            $query.= 'name='.$db->quote($table, 'text');
-        }
-        $sql = $db->queryOne($query);
-        if (PEAR::isError($sql)) {
-            return $sql;
-        }
-        $columns = $db->reverse->_getTableColumns($sql);
-        $fields = array();
-        foreach ($columns as $column) {
-            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-                if ($db->options['field_case'] == CASE_LOWER) {
-                    $column['name'] = strtolower($column['name']);
-                } else {
-                    $column['name'] = strtoupper($column['name']);
-                }
-            } else {
-                $column = array_change_key_case($column, $db->options['field_case']);
-            }
-            $fields[] = $column['name'];
-        }
-        return $fields;
-    }
-
-    // }}}
-    // {{{ listTableTriggers()
-
-    /**
-     * list all triggers in the database that reference a given table
-     *
-     * @param string table for which all referenced triggers should be found
-     * @return mixed array of trigger names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTableTriggers($table = null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = "SELECT name FROM sqlite_master WHERE type='trigger' AND sql NOT NULL";
-        if (!is_null($table)) {
-            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-                $query.= ' AND LOWER(tbl_name)='.$db->quote(strtolower($table), 'text');
-            } else {
-                $query.= ' AND tbl_name='.$db->quote($table, 'text');
-            }
-        }
-        $result = $db->queryCol($query);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
-        }
-        return $result;
-    }
-
-    // }}}
-    // {{{ createIndex()
-
-    /**
-     * Get the stucture of a field into an array
-     *
-     * @param string    $table         name of the table on which the index is to be created
-     * @param string    $name         name of the index to be created
-     * @param array     $definition        associative array that defines properties of the index to be created.
-     *                                 Currently, only one property named FIELDS is supported. This property
-     *                                 is also an associative with the names of the index fields as array
-     *                                 indexes. Each entry of this array is set to another type of associative
-     *                                 array that specifies properties of the index that are specific to
-     *                                 each field.
-     *
-     *                                Currently, only the sorting property is supported. It should be used
-     *                                 to define the sorting direction of the index. It may be set to either
-     *                                 ascending or descending.
-     *
-     *                                Not all DBMS support index sorting direction configuration. The DBMS
-     *                                 drivers of those that do not support it ignore this property. Use the
-     *                                 function support() to determine whether the DBMS driver can manage indexes.
-
-     *                                 Example
-     *                                    array(
-     *                                        'fields' => array(
-     *                                            'user_name' => array(
-     *                                                'sorting' => 'ascending'
-     *                                            ),
-     *                                            'last_login' => array()
-     *                                        )
-     *                                    )
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function createIndex($table, $name, $definition)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $table = $db->quoteIdentifier($table, true);
-        $name  = $db->getIndexName($name);
-        $query = "CREATE INDEX $name ON $table";
-        $fields = array();
-        foreach ($definition['fields'] as $field_name => $field) {
-            $field_string = $field_name;
-            if (!empty($field['sorting'])) {
-                switch ($field['sorting']) {
-                case 'ascending':
-                    $field_string.= ' ASC';
-                    break;
-                case 'descending':
-                    $field_string.= ' DESC';
-                    break;
-                }
-            }
-            $fields[] = $field_string;
-        }
-        $query .= ' ('.implode(', ', $fields) . ')';
-        return $db->exec($query);
-    }
-
-    // }}}
-    // {{{ dropIndex()
-
-    /**
-     * drop existing index
-     *
-     * @param string    $table         name of table that should be used in method
-     * @param string    $name         name of the index to be dropped
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function dropIndex($table, $name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $name = $db->getIndexName($name);
-        return $db->exec("DROP INDEX $name");
-    }
-
-    // }}}
-    // {{{ listTableIndexes()
-
-    /**
-     * list all indexes in a table
-     *
-     * @param string $table name of table that should be used in method
-     * @return mixed array of index names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTableIndexes($table)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $table = $db->quote($table, 'text');
-        $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $query.= 'LOWER(tbl_name)='.strtolower($table);
-        } else {
-            $query.= "tbl_name=$table";
-        }
-        $query.= " AND sql NOT NULL ORDER BY name";
-        $indexes = $db->queryCol($query, 'text');
-        if (PEAR::isError($indexes)) {
-            return $indexes;
-        }
-
-        $result = array();
-        foreach ($indexes as $sql) {
-            if (preg_match("/^create index ([^ ]+) on /i", $sql, $tmp)) {
-                $index = $this->_fixIndexName($tmp[1]);
-                if (!empty($index)) {
-                    $result[$index] = true;
-                }
-            }
-        }
-
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_change_key_case($result, $db->options['field_case']);
-        }
-        return array_keys($result);
-    }
-
-    // }}}
-    // {{{ createConstraint()
-
-    /**
-     * create a constraint on a table
-     *
-     * @param string $table      name of the table on which the constraint is to be created
-     * @param string $name       name of the constraint to be created
-     * @param array  $definition associative array that defines properties of the constraint to be created.
-     *                           Currently, only one property named FIELDS is supported. This property
-     *                           is also an associative with the names of the constraint fields as array
-     *                           constraints. Each entry of this array is set to another type of associative
-     *                           array that specifies properties of the constraint that are specific to
-     *                           each field.
-     *
-     *                           Example
-     *                              array(
-     *                                  'fields' => array(
-     *                                      'user_name' => array(),
-     *                                      'last_login' => array()
-     *                                  )
-     *                              )
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function createConstraint($table, $name, $definition)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        if (!empty($definition['primary'])) {
-            return $db->manager->alterTable($table, array(), false, array('primary' => $definition['fields']));
-        }
-        
-        if (!empty($definition['foreign'])) {
-            return $db->manager->alterTable($table, array(), false, array('foreign_keys' => array($name => $definition)));
-        }
-
-        $table = $db->quoteIdentifier($table, true);
-        $name  = $db->getIndexName($name);
-        $query = "CREATE UNIQUE INDEX $name ON $table";
-        $fields = array();
-        foreach ($definition['fields'] as $field_name => $field) {
-            $field_string = $field_name;
-            if (!empty($field['sorting'])) {
-                switch ($field['sorting']) {
-                case 'ascending':
-                    $field_string.= ' ASC';
-                    break;
-                case 'descending':
-                    $field_string.= ' DESC';
-                    break;
-                }
-            }
-            $fields[] = $field_string;
-        }
-        $query .= ' ('.implode(', ', $fields) . ')';
-        return $db->exec($query);
-    }
-
-    // }}}
-    // {{{ dropConstraint()
-
-    /**
-     * drop existing constraint
-     *
-     * @param string    $table        name of table that should be used in method
-     * @param string    $name         name of the constraint to be dropped
-     * @param string    $primary      hint if the constraint is primary
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function dropConstraint($table, $name, $primary = false)
-    {
-        if ($primary || $name == 'PRIMARY') {
-            return $this->alterTable($table, array(), false, array('primary' => null));
-        }
-
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        //is it a FK constraint? If so, also delete the associated triggers
-        $db->loadModule('Reverse', null, true);
-        $definition = $db->reverse->getTableConstraintDefinition($table, $name);
-        if (!PEAR::isError($definition) && !empty($definition['foreign'])) {
-            //first drop the FK enforcing triggers
-            $result = $this->_dropFKTriggers($table, $name, $definition['references']['table']);
-            if (PEAR::isError($result)) {
-                return $result;
-            }
-            //then drop the constraint itself
-            return $this->alterTable($table, array(), false, array('foreign_keys' => array($name => null)));
-        }
-
-        $name = $db->getIndexName($name);
-        return $db->exec("DROP INDEX $name");
-    }
-
-    // }}}
-    // {{{ _dropFKTriggers()
-    
-    /**
-     * Drop the triggers created to enforce the FOREIGN KEY constraint on the table
-     *
-     * @param string $table  table name
-     * @param string $fkname FOREIGN KEY constraint name
-     * @param string $referenced_table  referenced table name
-     *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access private
-     */
-    function _dropFKTriggers($table, $fkname, $referenced_table)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $triggers  = $this->listTableTriggers($table);
-        $triggers2 = $this->listTableTriggers($referenced_table);
-        if (!PEAR::isError($triggers2) && !PEAR::isError($triggers)) {
-            $triggers = array_merge($triggers, $triggers2);
-            $pattern = '/^'.$fkname.'(_pk)?_(insert|update|delete)_trg$/i';
-            foreach ($triggers as $trigger) {
-                if (preg_match($pattern, $trigger)) {
-                    $result = $db->exec('DROP TRIGGER '.$trigger);
-                    if (PEAR::isError($result)) {
-                        return $result;
-                    }
-                }
-            }
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ listTableConstraints()
-
-    /**
-     * list all constraints in a table
-     *
-     * @param string $table name of table that should be used in method
-     * @return mixed array of constraint names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listTableConstraints($table)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $table = $db->quote($table, 'text');
-        $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $query.= 'LOWER(tbl_name)='.strtolower($table);
-        } else {
-            $query.= "tbl_name=$table";
-        }
-        $query.= " AND sql NOT NULL ORDER BY name";
-        $indexes = $db->queryCol($query, 'text');
-        if (PEAR::isError($indexes)) {
-            return $indexes;
-        }
-
-        $result = array();
-        foreach ($indexes as $sql) {
-            if (preg_match("/^create unique index ([^ ]+) on /i", $sql, $tmp)) {
-                $index = $this->_fixIndexName($tmp[1]);
-                if (!empty($index)) {
-                    $result[$index] = true;
-                }
-            }
-        }
-        
-        // also search in table definition for PRIMARY KEYs...
-        $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $query.= 'LOWER(name)='.strtolower($table);
-        } else {
-            $query.= "name=$table";
-        }
-        $query.= " AND sql NOT NULL ORDER BY name";
-        $table_def = $db->queryOne($query, 'text');
-        if (PEAR::isError($table_def)) {
-            return $table_def;
-        }
-        if (preg_match("/\bPRIMARY\s+KEY\b/i", $table_def, $tmp)) {
-            $result['primary'] = true;
-        }
-
-        // ...and for FOREIGN KEYs
-        if (preg_match_all("/\bCONSTRAINT\b\s+([^\s]+)\s+\bFOREIGN\s+KEY/imsx", $table_def, $tmp)) {
-            foreach ($tmp[1] as $fk) {
-                $result[$fk] = true;
-            }
-        }
-
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_change_key_case($result, $db->options['field_case']);
-        }
-        return array_keys($result);
-    }
-
-    // }}}
-    // {{{ createSequence()
-
-    /**
-     * create sequence
-     *
-     * @param string    $seq_name     name of the sequence to be created
-     * @param string    $start         start value of the sequence; default is 1
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function createSequence($seq_name, $start = 1)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
-        $seqcol_name = $db->quoteIdentifier($db->options['seqcol_name'], true);
-        $query = "CREATE TABLE $sequence_name ($seqcol_name INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)";
-        $res = $db->exec($query);
-        if (PEAR::isError($res)) {
-            return $res;
-        }
-        if ($start == 1) {
-            return MDB2_OK;
-        }
-        $res = $db->exec("INSERT INTO $sequence_name ($seqcol_name) VALUES (".($start-1).')');
-        if (!PEAR::isError($res)) {
-            return MDB2_OK;
-        }
-        // Handle error
-        $result = $db->exec("DROP TABLE $sequence_name");
-        if (PEAR::isError($result)) {
-            return $db->raiseError($result, null, null,
-                'could not drop inconsistent sequence table', __FUNCTION__);
-        }
-        return $db->raiseError($res, null, null,
-            'could not create sequence table', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ dropSequence()
-
-    /**
-     * drop existing sequence
-     *
-     * @param string    $seq_name     name of the sequence to be dropped
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function dropSequence($seq_name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
-        return $db->exec("DROP TABLE $sequence_name");
-    }
-
-    // }}}
-    // {{{ listSequences()
-
-    /**
-     * list all sequences in the current database
-     *
-     * @return mixed array of sequence names on success, a MDB2 error on failure
-     * @access public
-     */
-    function listSequences($dummy=null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name";
-        $table_names = $db->queryCol($query);
-        if (PEAR::isError($table_names)) {
-            return $table_names;
-        }
-        $result = array();
-        foreach ($table_names as $table_name) {
-            if ($sqn = $this->_fixSequenceName($table_name, true)) {
-                $result[] = $sqn;
-            }
-        }
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
-        }
-        return $result;
-    }
-
-    // }}}
-}
-?>
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith, Lorenzo Alberton                       |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Authors: Lukas Smith <smith@pooteeweet.org>                          |\r
+// |          Lorenzo Alberton <l.alberton@quipo.it>                      |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: sqlite.php 295587 2010-02-28 17:16:38Z quipo $\r
+//\r
+\r
+require_once 'MDB2/Driver/Manager/Common.php';\r
+\r
+/**\r
+ * MDB2 SQLite driver for the management modules\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ * @author  Lorenzo Alberton <l.alberton@quipo.it>\r
+ */\r
+class MDB2_Driver_Manager_sqlite extends MDB2_Driver_Manager_Common\r
+{\r
+    // {{{ createDatabase()\r
+\r
+    /**\r
+     * create a new database\r
+     *\r
+     * @param string $name    name of the database that should be created\r
+     * @param array  $options array with charset info\r
+     *\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function createDatabase($name, $options = array())\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $database_file = $db->_getDatabaseFile($name);\r
+        if (file_exists($database_file)) {\r
+            return $db->raiseError(MDB2_ERROR_ALREADY_EXISTS, null, null,\r
+                'database already exists', __FUNCTION__);\r
+        }\r
+        $php_errormsg = '';\r
+        $handle = @sqlite_open($database_file, $db->dsn['mode'], $php_errormsg);\r
+        if (!$handle) {\r
+            return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,\r
+                (isset($php_errormsg) ? $php_errormsg : 'could not create the database file'), __FUNCTION__);\r
+        }\r
+        if (!empty($options['charset'])) {\r
+            $query = 'PRAGMA encoding = ' . $db->quote($options['charset'], 'text');\r
+            @sqlite_query($query, $handle);\r
+        }\r
+        @sqlite_close($handle);\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ dropDatabase()\r
+\r
+    /**\r
+     * drop an existing database\r
+     *\r
+     * @param string $name name of the database that should be dropped\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function dropDatabase($name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $database_file = $db->_getDatabaseFile($name);\r
+        if (!@file_exists($database_file)) {\r
+            return $db->raiseError(MDB2_ERROR_CANNOT_DROP, null, null,\r
+                'database does not exist', __FUNCTION__);\r
+        }\r
+        $result = @unlink($database_file);\r
+        if (!$result) {\r
+            return $db->raiseError(MDB2_ERROR_CANNOT_DROP, null, null,\r
+                (isset($php_errormsg) ? $php_errormsg : 'could not remove the database file'), __FUNCTION__);\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getAdvancedFKOptions()\r
+\r
+    /**\r
+     * Return the FOREIGN KEY query section dealing with non-standard options\r
+     * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...\r
+     *\r
+     * @param array $definition\r
+     * @return string\r
+     * @access protected\r
+     */\r
+    function _getAdvancedFKOptions($definition)\r
+    {\r
+        $query = '';\r
+        if (!empty($definition['match'])) {\r
+            $query .= ' MATCH '.$definition['match'];\r
+        }\r
+        if (!empty($definition['onupdate']) && (strtoupper($definition['onupdate']) != 'NO ACTION')) {\r
+            $query .= ' ON UPDATE '.$definition['onupdate'];\r
+        }\r
+        if (!empty($definition['ondelete']) && (strtoupper($definition['ondelete']) != 'NO ACTION')) {\r
+            $query .= ' ON DELETE '.$definition['ondelete'];\r
+        }\r
+        if (!empty($definition['deferrable'])) {\r
+            $query .= ' DEFERRABLE';\r
+        } else {\r
+            $query .= ' NOT DEFERRABLE';\r
+        }\r
+        if (!empty($definition['initiallydeferred'])) {\r
+            $query .= ' INITIALLY DEFERRED';\r
+        } else {\r
+            $query .= ' INITIALLY IMMEDIATE';\r
+        }\r
+        return $query;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getCreateTableQuery()\r
+\r
+    /**\r
+     * Create a basic SQL query for a new table creation\r
+     * @param string $name   Name of the database that should be created\r
+     * @param array $fields  Associative array that contains the definition of each field of the new table\r
+     * @param array $options  An associative array of table options\r
+     * @return mixed string (the SQL query) on success, a MDB2 error on failure\r
+     * @see createTable()\r
+     */\r
+    function _getCreateTableQuery($name, $fields, $options = array())\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        if (!$name) {\r
+            return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,\r
+                'no valid table name specified', __FUNCTION__);\r
+        }\r
+        if (empty($fields)) {\r
+            return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,\r
+                'no fields specified for table "'.$name.'"', __FUNCTION__);\r
+        }\r
+        $query_fields = $this->getFieldDeclarationList($fields);\r
+        if (PEAR::isError($query_fields)) {\r
+            return $query_fields;\r
+        }\r
+        if (!empty($options['primary'])) {\r
+            $query_fields.= ', PRIMARY KEY ('.implode(', ', array_keys($options['primary'])).')';\r
+        }\r
+        if (!empty($options['foreign_keys'])) {\r
+            foreach ($options['foreign_keys'] as $fkname => $fkdef) {\r
+                if (empty($fkdef)) {\r
+                    continue;\r
+                }\r
+                $query_fields.= ', CONSTRAINT '.$fkname.' FOREIGN KEY ('.implode(', ', array_keys($fkdef['fields'])).')';\r
+                $query_fields.= ' REFERENCES '.$fkdef['references']['table'].' ('.implode(', ', array_keys($fkdef['references']['fields'])).')';\r
+                $query_fields.= $this->_getAdvancedFKOptions($fkdef);\r
+            }\r
+        }\r
+\r
+        $name = $db->quoteIdentifier($name, true);\r
+        $result = 'CREATE ';\r
+        if (!empty($options['temporary'])) {\r
+            $result .= $this->_getTemporaryTableQuery();\r
+        }\r
+        $result .= " TABLE $name ($query_fields)";\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ createTable()\r
+\r
+    /**\r
+     * create a new table\r
+     *\r
+     * @param string $name    Name of the database that should be created\r
+     * @param array  $fields  Associative array that contains the definition\r
+     *                        of each field of the new table\r
+     * @param array  $options An associative array of table options\r
+     *\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function createTable($name, $fields, $options = array())\r
+    {\r
+        $result = parent::createTable($name, $fields, $options);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        // create triggers to enforce FOREIGN KEY constraints\r
+        if (!empty($options['foreign_keys'])) {\r
+            $db = $this->getDBInstance();\r
+            if (PEAR::isError($db)) {\r
+                return $db;\r
+            }\r
+            foreach ($options['foreign_keys'] as $fkname => $fkdef) {\r
+                if (empty($fkdef)) {\r
+                    continue;\r
+                }\r
+                //set actions to default if not set\r
+                $fkdef['onupdate'] = empty($fkdef['onupdate']) ? $db->options['default_fk_action_onupdate'] : strtoupper($fkdef['onupdate']);\r
+                $fkdef['ondelete'] = empty($fkdef['ondelete']) ? $db->options['default_fk_action_ondelete'] : strtoupper($fkdef['ondelete']);\r
+\r
+                $trigger_names = array(\r
+                    'insert'    => $fkname.'_insert_trg',\r
+                    'update'    => $fkname.'_update_trg',\r
+                    'pk_update' => $fkname.'_pk_update_trg',\r
+                    'pk_delete' => $fkname.'_pk_delete_trg',\r
+                );\r
+                \r
+                //create the [insert|update] triggers on the FK table\r
+                $table_fields = array_keys($fkdef['fields']);\r
+                $referenced_fields = array_keys($fkdef['references']['fields']);\r
+                $query = 'CREATE TRIGGER %s BEFORE %s ON '.$name\r
+                        .' FOR EACH ROW BEGIN'\r
+                        .' SELECT RAISE(ROLLBACK, \'%s on table "'.$name.'" violates FOREIGN KEY constraint "'.$fkname.'"\')'\r
+                        .' WHERE  (SELECT ';\r
+                $aliased_fields = array();\r
+                foreach ($referenced_fields as $field) {\r
+                    $aliased_fields[] = $fkdef['references']['table'] .'.'.$field .' AS '.$field;\r
+                }\r
+                $query .= implode(',', $aliased_fields)\r
+                       .' FROM '.$fkdef['references']['table']\r
+                       .' WHERE ';\r
+                $conditions = array();\r
+                for ($i=0; $i<count($table_fields); $i++) {\r
+                    $conditions[] = $referenced_fields[$i] .' = NEW.'.$table_fields[$i];\r
+                }\r
+                $query .= implode(' AND ', $conditions).') IS NULL; END;';\r
+                $result = $db->exec(sprintf($query, $trigger_names['insert'], 'INSERT', 'insert'));\r
+                if (PEAR::isError($result)) {\r
+                    return $result;\r
+                }\r
+\r
+                $result = $db->exec(sprintf($query, $trigger_names['update'], 'UPDATE', 'update'));\r
+                if (PEAR::isError($result)) {\r
+                    return $result;\r
+                }\r
+                \r
+                //create the ON [UPDATE|DELETE] triggers on the primary table\r
+                $restrict_action = 'SELECT RAISE(ROLLBACK, \'%s on table "'.$name.'" violates FOREIGN KEY constraint "'.$fkname.'"\')'\r
+                                  .' WHERE  (SELECT ';\r
+                $aliased_fields = array();\r
+                foreach ($table_fields as $field) {\r
+                    $aliased_fields[] = $name .'.'.$field .' AS '.$field;\r
+                }\r
+                $restrict_action .= implode(',', $aliased_fields)\r
+                       .' FROM '.$name\r
+                       .' WHERE ';\r
+                $conditions  = array();\r
+                $new_values  = array();\r
+                $null_values = array();\r
+                for ($i=0; $i<count($table_fields); $i++) {\r
+                    $conditions[]  = $table_fields[$i] .' = OLD.'.$referenced_fields[$i];\r
+                    $new_values[]  = $table_fields[$i] .' = NEW.'.$referenced_fields[$i];\r
+                    $null_values[] = $table_fields[$i] .' = NULL';\r
+                }\r
+                $conditions2 = array();\r
+                for ($i=0; $i<count($referenced_fields); $i++) {\r
+                    $conditions2[]  = 'NEW.'.$referenced_fields[$i] .' <> OLD.'.$referenced_fields[$i];\r
+                }\r
+                $restrict_action .= implode(' AND ', $conditions).') IS NOT NULL'\r
+                                 .' AND (' .implode(' OR ', $conditions2) .')';\r
+\r
+                $cascade_action_update = 'UPDATE '.$name.' SET '.implode(', ', $new_values) .' WHERE '.implode(' AND ', $conditions);\r
+                $cascade_action_delete = 'DELETE FROM '.$name.' WHERE '.implode(' AND ', $conditions);\r
+                $setnull_action        = 'UPDATE '.$name.' SET '.implode(', ', $null_values).' WHERE '.implode(' AND ', $conditions);\r
+\r
+                if ('SET DEFAULT' == $fkdef['onupdate'] || 'SET DEFAULT' == $fkdef['ondelete']) {\r
+                    $db->loadModule('Reverse', null, true);\r
+                    $default_values = array();\r
+                    foreach ($table_fields as $table_field) {\r
+                        $field_definition = $db->reverse->getTableFieldDefinition($name, $field);\r
+                        if (PEAR::isError($field_definition)) {\r
+                            return $field_definition;\r
+                        }\r
+                        $default_values[] = $table_field .' = '. $field_definition[0]['default'];\r
+                    }\r
+                    $setdefault_action = 'UPDATE '.$name.' SET '.implode(', ', $default_values).' WHERE '.implode(' AND ', $conditions);\r
+                }\r
+\r
+                $query = 'CREATE TRIGGER %s'\r
+                        .' %s ON '.$fkdef['references']['table']\r
+                        .' FOR EACH ROW BEGIN ';\r
+\r
+                if ('CASCADE' == $fkdef['onupdate']) {\r
+                    $sql_update = sprintf($query, $trigger_names['pk_update'], 'AFTER UPDATE',  'update') . $cascade_action_update. '; END;';\r
+                } elseif ('SET NULL' == $fkdef['onupdate']) {\r
+                    $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setnull_action. '; END;';\r
+                } elseif ('SET DEFAULT' == $fkdef['onupdate']) {\r
+                    $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setdefault_action. '; END;';\r
+                } elseif ('NO ACTION' == $fkdef['onupdate']) {\r
+                    $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'AFTER UPDATE', 'update') . '; END;';\r
+                } elseif ('RESTRICT' == $fkdef['onupdate']) {\r
+                    $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . '; END;';\r
+                }\r
+                if ('CASCADE' == $fkdef['ondelete']) {\r
+                    $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'AFTER DELETE',  'delete') . $cascade_action_delete. '; END;';\r
+                } elseif ('SET NULL' == $fkdef['ondelete']) {\r
+                    $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setnull_action. '; END;';\r
+                } elseif ('SET DEFAULT' == $fkdef['ondelete']) {\r
+                    $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setdefault_action. '; END;';\r
+                } elseif ('NO ACTION' == $fkdef['ondelete']) {\r
+                    $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete')  . '; END;';\r
+                } elseif ('RESTRICT' == $fkdef['ondelete']) {\r
+                    $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . '; END;';\r
+                }\r
+\r
+                if (PEAR::isError($result)) {\r
+                    return $result;\r
+                }\r
+                $result = $db->exec($sql_delete);\r
+                if (PEAR::isError($result)) {\r
+                    return $result;\r
+                }\r
+                $result = $db->exec($sql_update);\r
+                if (PEAR::isError($result)) {\r
+                    return $result;\r
+                }\r
+            }\r
+        }\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ dropTable()\r
+\r
+    /**\r
+     * drop an existing table\r
+     *\r
+     * @param string $name name of the table that should be dropped\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function dropTable($name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+        \r
+        //delete the triggers associated to existing FK constraints\r
+        $constraints = $this->listTableConstraints($name);\r
+        if (!PEAR::isError($constraints) && !empty($constraints)) {\r
+            $db->loadModule('Reverse', null, true);\r
+            foreach ($constraints as $constraint) {\r
+                $definition = $db->reverse->getTableConstraintDefinition($name, $constraint);\r
+                if (!PEAR::isError($definition) && !empty($definition['foreign'])) {\r
+                    $result = $this->_dropFKTriggers($name, $constraint, $definition['references']['table']);\r
+                    if (PEAR::isError($result)) {\r
+                        return $result;\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+        $name = $db->quoteIdentifier($name, true);\r
+        return $db->exec("DROP TABLE $name");\r
+    }\r
+\r
+    // }}}\r
+    // {{{ vacuum()\r
+\r
+    /**\r
+     * Optimize (vacuum) all the tables in the db (or only the specified table)\r
+     * and optionally run ANALYZE.\r
+     *\r
+     * @param string $table table name (all the tables if empty)\r
+     * @param array  $options an array with driver-specific options:\r
+     *               - timeout [int] (in seconds) [mssql-only]\r
+     *               - analyze [boolean] [pgsql and mysql]\r
+     *               - full [boolean] [pgsql-only]\r
+     *               - freeze [boolean] [pgsql-only]\r
+     *\r
+     * @return mixed MDB2_OK success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function vacuum($table = null, $options = array())\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = 'VACUUM';\r
+        if (!empty($table)) {\r
+            $query .= ' '.$db->quoteIdentifier($table, true);\r
+        }\r
+        return $db->exec($query);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ alterTable()\r
+\r
+    /**\r
+     * alter an existing table\r
+     *\r
+     * @param string $name         name of the table that is intended to be changed.\r
+     * @param array $changes     associative array that contains the details of each type\r
+     *                             of change that is intended to be performed. The types of\r
+     *                             changes that are currently supported are defined as follows:\r
+     *\r
+     *                             name\r
+     *\r
+     *                                New name for the table.\r
+     *\r
+     *                            add\r
+     *\r
+     *                                Associative array with the names of fields to be added as\r
+     *                                 indexes of the array. The value of each entry of the array\r
+     *                                 should be set to another associative array with the properties\r
+     *                                 of the fields to be added. The properties of the fields should\r
+     *                                 be the same as defined by the MDB2 parser.\r
+     *\r
+     *\r
+     *                            remove\r
+     *\r
+     *                                Associative array with the names of fields to be removed as indexes\r
+     *                                 of the array. Currently the values assigned to each entry are ignored.\r
+     *                                 An empty array should be used for future compatibility.\r
+     *\r
+     *                            rename\r
+     *\r
+     *                                Associative array with the names of fields to be renamed as indexes\r
+     *                                 of the array. The value of each entry of the array should be set to\r
+     *                                 another associative array with the entry named name with the new\r
+     *                                 field name and the entry named Declaration that is expected to contain\r
+     *                                 the portion of the field declaration already in DBMS specific SQL code\r
+     *                                 as it is used in the CREATE TABLE statement.\r
+     *\r
+     *                            change\r
+     *\r
+     *                                Associative array with the names of the fields to be changed as indexes\r
+     *                                 of the array. Keep in mind that if it is intended to change either the\r
+     *                                 name of a field and any other properties, the change array entries\r
+     *                                 should have the new names of the fields as array indexes.\r
+     *\r
+     *                                The value of each entry of the array should be set to another associative\r
+     *                                 array with the properties of the fields to that are meant to be changed as\r
+     *                                 array entries. These entries should be assigned to the new values of the\r
+     *                                 respective properties. The properties of the fields should be the same\r
+     *                                 as defined by the MDB2 parser.\r
+     *\r
+     *                            Example\r
+     *                                array(\r
+     *                                    'name' => 'userlist',\r
+     *                                    'add' => array(\r
+     *                                        'quota' => array(\r
+     *                                            'type' => 'integer',\r
+     *                                            'unsigned' => 1\r
+     *                                        )\r
+     *                                    ),\r
+     *                                    'remove' => array(\r
+     *                                        'file_limit' => array(),\r
+     *                                        'time_limit' => array()\r
+     *                                    ),\r
+     *                                    'change' => array(\r
+     *                                        'name' => array(\r
+     *                                            'length' => '20',\r
+     *                                            'definition' => array(\r
+     *                                                'type' => 'text',\r
+     *                                                'length' => 20,\r
+     *                                            ),\r
+     *                                        )\r
+     *                                    ),\r
+     *                                    'rename' => array(\r
+     *                                        'sex' => array(\r
+     *                                            'name' => 'gender',\r
+     *                                            'definition' => array(\r
+     *                                                'type' => 'text',\r
+     *                                                'length' => 1,\r
+     *                                                'default' => 'M',\r
+     *                                            ),\r
+     *                                        )\r
+     *                                    )\r
+     *                                )\r
+     *\r
+     * @param boolean $check     indicates whether the function should just check if the DBMS driver\r
+     *                             can perform the requested table alterations if the value is true or\r
+     *                             actually perform them otherwise.\r
+     * @access public\r
+     *\r
+      * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     */\r
+    function alterTable($name, $changes, $check, $options = array())\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        foreach ($changes as $change_name => $change) {\r
+            switch ($change_name) {\r
+            case 'add':\r
+            case 'remove':\r
+            case 'change':\r
+            case 'name':\r
+            case 'rename':\r
+                break;\r
+            default:\r
+                return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,\r
+                    'change type "'.$change_name.'" not yet supported', __FUNCTION__);\r
+            }\r
+        }\r
+\r
+        if ($check) {\r
+            return MDB2_OK;\r
+        }\r
+\r
+        $db->loadModule('Reverse', null, true);\r
+\r
+        // actually sqlite 2.x supports no ALTER TABLE at all .. so we emulate it\r
+        $fields = $db->manager->listTableFields($name);\r
+        if (PEAR::isError($fields)) {\r
+            return $fields;\r
+        }\r
+\r
+        $fields = array_flip($fields);\r
+        foreach ($fields as $field => $value) {\r
+            $definition = $db->reverse->getTableFieldDefinition($name, $field);\r
+            if (PEAR::isError($definition)) {\r
+                return $definition;\r
+            }\r
+            $fields[$field] = $definition[0];\r
+        }\r
+\r
+        $indexes = $db->manager->listTableIndexes($name);\r
+        if (PEAR::isError($indexes)) {\r
+            return $indexes;\r
+        }\r
+\r
+        $indexes = array_flip($indexes);\r
+        foreach ($indexes as $index => $value) {\r
+            $definition = $db->reverse->getTableIndexDefinition($name, $index);\r
+            if (PEAR::isError($definition)) {\r
+                return $definition;\r
+            }\r
+            $indexes[$index] = $definition;\r
+        }\r
+\r
+        $constraints = $db->manager->listTableConstraints($name);\r
+        if (PEAR::isError($constraints)) {\r
+            return $constraints;\r
+        }\r
+\r
+        if (!array_key_exists('foreign_keys', $options)) {\r
+            $options['foreign_keys'] = array();\r
+        }\r
+        $constraints = array_flip($constraints);\r
+        foreach ($constraints as $constraint => $value) {\r
+            if (!empty($definition['primary'])) {\r
+                if (!array_key_exists('primary', $options)) {\r
+                    $options['primary'] = $definition['fields'];\r
+                    //remove from the $constraint array, it's already handled by createTable()\r
+                    unset($constraints[$constraint]);\r
+                }\r
+            } else {\r
+                $c_definition = $db->reverse->getTableConstraintDefinition($name, $constraint);\r
+                if (PEAR::isError($c_definition)) {\r
+                    return $c_definition;\r
+                }\r
+                if (!empty($c_definition['foreign'])) {\r
+                    if (!array_key_exists($constraint, $options['foreign_keys'])) {\r
+                        $options['foreign_keys'][$constraint] = $c_definition;\r
+                    }\r
+                    //remove from the $constraint array, it's already handled by createTable()\r
+                    unset($constraints[$constraint]);\r
+                } else {\r
+                    $constraints[$constraint] = $c_definition;\r
+                }\r
+            }\r
+        }\r
+\r
+        $name_new = $name;\r
+        $create_order = $select_fields = array_keys($fields);\r
+        foreach ($changes as $change_name => $change) {\r
+            switch ($change_name) {\r
+            case 'add':\r
+                foreach ($change as $field_name => $field) {\r
+                    $fields[$field_name] = $field;\r
+                    $create_order[] = $field_name;\r
+                }\r
+                break;\r
+            case 'remove':\r
+                foreach ($change as $field_name => $field) {\r
+                    unset($fields[$field_name]);\r
+                    $select_fields = array_diff($select_fields, array($field_name));\r
+                    $create_order = array_diff($create_order, array($field_name));\r
+                }\r
+                break;\r
+            case 'change':\r
+                foreach ($change as $field_name => $field) {\r
+                    $fields[$field_name] = $field['definition'];\r
+                }\r
+                break;\r
+            case 'name':\r
+                $name_new = $change;\r
+                break;\r
+            case 'rename':\r
+                foreach ($change as $field_name => $field) {\r
+                    unset($fields[$field_name]);\r
+                    $fields[$field['name']] = $field['definition'];\r
+                    $create_order[array_search($field_name, $create_order)] = $field['name'];\r
+                }\r
+                break;\r
+            default:\r
+                return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,\r
+                    'change type "'.$change_name.'" not yet supported', __FUNCTION__);\r
+            }\r
+        }\r
+\r
+        $data = null;\r
+        if (!empty($select_fields)) {\r
+            $query = 'SELECT '.implode(', ', $select_fields).' FROM '.$db->quoteIdentifier($name, true);\r
+            $data = $db->queryAll($query, null, MDB2_FETCHMODE_ORDERED);\r
+        }\r
+\r
+        $result = $this->dropTable($name);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+\r
+        $result = $this->createTable($name_new, $fields, $options);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+\r
+        foreach ($indexes as $index => $definition) {\r
+            $this->createIndex($name_new, $index, $definition);\r
+        }\r
+\r
+        foreach ($constraints as $constraint => $definition) {\r
+            $this->createConstraint($name_new, $constraint, $definition);\r
+        }\r
+\r
+        if (!empty($select_fields) && !empty($data)) {\r
+            $query = 'INSERT INTO '.$db->quoteIdentifier($name_new, true);\r
+            $query.= '('.implode(', ', array_slice(array_keys($fields), 0, count($select_fields))).')';\r
+            $query.=' VALUES (?'.str_repeat(', ?', (count($select_fields) - 1)).')';\r
+            $stmt = $db->prepare($query, null, MDB2_PREPARE_MANIP);\r
+            if (PEAR::isError($stmt)) {\r
+                return $stmt;\r
+            }\r
+            foreach ($data as $row) {\r
+                $result = $stmt->execute($row);\r
+                if (PEAR::isError($result)) {\r
+                    return $result;\r
+                }\r
+            }\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listDatabases()\r
+\r
+    /**\r
+     * list all databases\r
+     *\r
+     * @return mixed array of database names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listDatabases()\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'list databases is not supported', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listUsers()\r
+\r
+    /**\r
+     * list all users\r
+     *\r
+     * @return mixed array of user names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listUsers()\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'list databases is not supported', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listViews()\r
+\r
+    /**\r
+     * list all views in the current database\r
+     *\r
+     * @return mixed array of view names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listViews()\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = "SELECT name FROM sqlite_master WHERE type='view' AND sql NOT NULL";\r
+        $result = $db->queryCol($query);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTableViews()\r
+\r
+    /**\r
+     * list the views in the database that reference a given table\r
+     *\r
+     * @param string table for which all referenced views should be found\r
+     * @return mixed array of view names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTableViews($table)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL";\r
+        $views = $db->queryAll($query, array('text', 'text'), MDB2_FETCHMODE_ASSOC);\r
+        if (PEAR::isError($views)) {\r
+            return $views;\r
+        }\r
+        $result = array();\r
+        foreach ($views as $row) {\r
+            if (preg_match("/^create view .* \bfrom\b\s+\b{$table}\b /i", $row['sql'])) {\r
+                if (!empty($row['name'])) {\r
+                    $result[$row['name']] = true;\r
+                }\r
+            }\r
+        }\r
+\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_change_key_case($result, $db->options['field_case']);\r
+        }\r
+        return array_keys($result);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTables()\r
+\r
+    /**\r
+     * list all tables in the current database\r
+     *\r
+     * @return mixed array of table names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTables()\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name";\r
+        $table_names = $db->queryCol($query);\r
+        if (PEAR::isError($table_names)) {\r
+            return $table_names;\r
+        }\r
+        $result = array();\r
+        foreach ($table_names as $table_name) {\r
+            if (!$this->_fixSequenceName($table_name, true)) {\r
+                $result[] = $table_name;\r
+            }\r
+        }\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTableFields()\r
+\r
+    /**\r
+     * list all fields in a table in the current database\r
+     *\r
+     * @param string $table name of table that should be used in method\r
+     * @return mixed array of field names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTableFields($table)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $result = $db->loadModule('Reverse', null, true);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');\r
+        } else {\r
+            $query.= 'name='.$db->quote($table, 'text');\r
+        }\r
+        $sql = $db->queryOne($query);\r
+        if (PEAR::isError($sql)) {\r
+            return $sql;\r
+        }\r
+        $columns = $db->reverse->_getTableColumns($sql);\r
+        $fields = array();\r
+        foreach ($columns as $column) {\r
+            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+                if ($db->options['field_case'] == CASE_LOWER) {\r
+                    $column['name'] = strtolower($column['name']);\r
+                } else {\r
+                    $column['name'] = strtoupper($column['name']);\r
+                }\r
+            } else {\r
+                $column = array_change_key_case($column, $db->options['field_case']);\r
+            }\r
+            $fields[] = $column['name'];\r
+        }\r
+        return $fields;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTableTriggers()\r
+\r
+    /**\r
+     * list all triggers in the database that reference a given table\r
+     *\r
+     * @param string table for which all referenced triggers should be found\r
+     * @return mixed array of trigger names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTableTriggers($table = null)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = "SELECT name FROM sqlite_master WHERE type='trigger' AND sql NOT NULL";\r
+        if (null !== $table) {\r
+            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+                $query.= ' AND LOWER(tbl_name)='.$db->quote(strtolower($table), 'text');\r
+            } else {\r
+                $query.= ' AND tbl_name='.$db->quote($table, 'text');\r
+            }\r
+        }\r
+        $result = $db->queryCol($query);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ createIndex()\r
+\r
+    /**\r
+     * Get the stucture of a field into an array\r
+     *\r
+     * @param string    $table         name of the table on which the index is to be created\r
+     * @param string    $name         name of the index to be created\r
+     * @param array     $definition        associative array that defines properties of the index to be created.\r
+     *                                 Currently, only one property named FIELDS is supported. This property\r
+     *                                 is also an associative with the names of the index fields as array\r
+     *                                 indexes. Each entry of this array is set to another type of associative\r
+     *                                 array that specifies properties of the index that are specific to\r
+     *                                 each field.\r
+     *\r
+     *                                Currently, only the sorting property is supported. It should be used\r
+     *                                 to define the sorting direction of the index. It may be set to either\r
+     *                                 ascending or descending.\r
+     *\r
+     *                                Not all DBMS support index sorting direction configuration. The DBMS\r
+     *                                 drivers of those that do not support it ignore this property. Use the\r
+     *                                 function support() to determine whether the DBMS driver can manage indexes.\r
+\r
+     *                                 Example\r
+     *                                    array(\r
+     *                                        'fields' => array(\r
+     *                                            'user_name' => array(\r
+     *                                                'sorting' => 'ascending'\r
+     *                                            ),\r
+     *                                            'last_login' => array()\r
+     *                                        )\r
+     *                                    )\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function createIndex($table, $name, $definition)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $table = $db->quoteIdentifier($table, true);\r
+        $name  = $db->getIndexName($name);\r
+        $query = "CREATE INDEX $name ON $table";\r
+        $fields = array();\r
+        foreach ($definition['fields'] as $field_name => $field) {\r
+            $field_string = $field_name;\r
+            if (!empty($field['sorting'])) {\r
+                switch ($field['sorting']) {\r
+                case 'ascending':\r
+                    $field_string.= ' ASC';\r
+                    break;\r
+                case 'descending':\r
+                    $field_string.= ' DESC';\r
+                    break;\r
+                }\r
+            }\r
+            $fields[] = $field_string;\r
+        }\r
+        $query .= ' ('.implode(', ', $fields) . ')';\r
+        return $db->exec($query);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ dropIndex()\r
+\r
+    /**\r
+     * drop existing index\r
+     *\r
+     * @param string    $table         name of table that should be used in method\r
+     * @param string    $name         name of the index to be dropped\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function dropIndex($table, $name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $name = $db->getIndexName($name);\r
+        return $db->exec("DROP INDEX $name");\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTableIndexes()\r
+\r
+    /**\r
+     * list all indexes in a table\r
+     *\r
+     * @param string $table name of table that should be used in method\r
+     * @return mixed array of index names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTableIndexes($table)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $table = $db->quote($table, 'text');\r
+        $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $query.= 'LOWER(tbl_name)='.strtolower($table);\r
+        } else {\r
+            $query.= "tbl_name=$table";\r
+        }\r
+        $query.= " AND sql NOT NULL ORDER BY name";\r
+        $indexes = $db->queryCol($query, 'text');\r
+        if (PEAR::isError($indexes)) {\r
+            return $indexes;\r
+        }\r
+\r
+        $result = array();\r
+        foreach ($indexes as $sql) {\r
+            if (preg_match("/^create index ([^ ]+) on /i", $sql, $tmp)) {\r
+                $index = $this->_fixIndexName($tmp[1]);\r
+                if (!empty($index)) {\r
+                    $result[$index] = true;\r
+                }\r
+            }\r
+        }\r
+\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_change_key_case($result, $db->options['field_case']);\r
+        }\r
+        return array_keys($result);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ createConstraint()\r
+\r
+    /**\r
+     * create a constraint on a table\r
+     *\r
+     * @param string $table      name of the table on which the constraint is to be created\r
+     * @param string $name       name of the constraint to be created\r
+     * @param array  $definition associative array that defines properties of the constraint to be created.\r
+     *                           Currently, only one property named FIELDS is supported. This property\r
+     *                           is also an associative with the names of the constraint fields as array\r
+     *                           constraints. Each entry of this array is set to another type of associative\r
+     *                           array that specifies properties of the constraint that are specific to\r
+     *                           each field.\r
+     *\r
+     *                           Example\r
+     *                              array(\r
+     *                                  'fields' => array(\r
+     *                                      'user_name' => array(),\r
+     *                                      'last_login' => array()\r
+     *                                  )\r
+     *                              )\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function createConstraint($table, $name, $definition)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        if (!empty($definition['primary'])) {\r
+            return $db->manager->alterTable($table, array(), false, array('primary' => $definition['fields']));\r
+        }\r
+        \r
+        if (!empty($definition['foreign'])) {\r
+            return $db->manager->alterTable($table, array(), false, array('foreign_keys' => array($name => $definition)));\r
+        }\r
+\r
+        $table = $db->quoteIdentifier($table, true);\r
+        $name  = $db->getIndexName($name);\r
+        $query = "CREATE UNIQUE INDEX $name ON $table";\r
+        $fields = array();\r
+        foreach ($definition['fields'] as $field_name => $field) {\r
+            $field_string = $field_name;\r
+            if (!empty($field['sorting'])) {\r
+                switch ($field['sorting']) {\r
+                case 'ascending':\r
+                    $field_string.= ' ASC';\r
+                    break;\r
+                case 'descending':\r
+                    $field_string.= ' DESC';\r
+                    break;\r
+                }\r
+            }\r
+            $fields[] = $field_string;\r
+        }\r
+        $query .= ' ('.implode(', ', $fields) . ')';\r
+        return $db->exec($query);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ dropConstraint()\r
+\r
+    /**\r
+     * drop existing constraint\r
+     *\r
+     * @param string    $table        name of table that should be used in method\r
+     * @param string    $name         name of the constraint to be dropped\r
+     * @param string    $primary      hint if the constraint is primary\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function dropConstraint($table, $name, $primary = false)\r
+    {\r
+        if ($primary || $name == 'PRIMARY') {\r
+            return $this->alterTable($table, array(), false, array('primary' => null));\r
+        }\r
+\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        //is it a FK constraint? If so, also delete the associated triggers\r
+        $db->loadModule('Reverse', null, true);\r
+        $definition = $db->reverse->getTableConstraintDefinition($table, $name);\r
+        if (!PEAR::isError($definition) && !empty($definition['foreign'])) {\r
+            //first drop the FK enforcing triggers\r
+            $result = $this->_dropFKTriggers($table, $name, $definition['references']['table']);\r
+            if (PEAR::isError($result)) {\r
+                return $result;\r
+            }\r
+            //then drop the constraint itself\r
+            return $this->alterTable($table, array(), false, array('foreign_keys' => array($name => null)));\r
+        }\r
+\r
+        $name = $db->getIndexName($name);\r
+        return $db->exec("DROP INDEX $name");\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _dropFKTriggers()\r
+    \r
+    /**\r
+     * Drop the triggers created to enforce the FOREIGN KEY constraint on the table\r
+     *\r
+     * @param string $table  table name\r
+     * @param string $fkname FOREIGN KEY constraint name\r
+     * @param string $referenced_table  referenced table name\r
+     *\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access private\r
+     */\r
+    function _dropFKTriggers($table, $fkname, $referenced_table)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $triggers  = $this->listTableTriggers($table);\r
+        $triggers2 = $this->listTableTriggers($referenced_table);\r
+        if (!PEAR::isError($triggers2) && !PEAR::isError($triggers)) {\r
+            $triggers = array_merge($triggers, $triggers2);\r
+            $pattern = '/^'.$fkname.'(_pk)?_(insert|update|delete)_trg$/i';\r
+            foreach ($triggers as $trigger) {\r
+                if (preg_match($pattern, $trigger)) {\r
+                    $result = $db->exec('DROP TRIGGER '.$trigger);\r
+                    if (PEAR::isError($result)) {\r
+                        return $result;\r
+                    }\r
+                }\r
+            }\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listTableConstraints()\r
+\r
+    /**\r
+     * list all constraints in a table\r
+     *\r
+     * @param string $table name of table that should be used in method\r
+     * @return mixed array of constraint names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listTableConstraints($table)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $table = $db->quote($table, 'text');\r
+        $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $query.= 'LOWER(tbl_name)='.strtolower($table);\r
+        } else {\r
+            $query.= "tbl_name=$table";\r
+        }\r
+        $query.= " AND sql NOT NULL ORDER BY name";\r
+        $indexes = $db->queryCol($query, 'text');\r
+        if (PEAR::isError($indexes)) {\r
+            return $indexes;\r
+        }\r
+\r
+        $result = array();\r
+        foreach ($indexes as $sql) {\r
+            if (preg_match("/^create unique index ([^ ]+) on /i", $sql, $tmp)) {\r
+                $index = $this->_fixIndexName($tmp[1]);\r
+                if (!empty($index)) {\r
+                    $result[$index] = true;\r
+                }\r
+            }\r
+        }\r
+        \r
+        // also search in table definition for PRIMARY KEYs...\r
+        $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $query.= 'LOWER(name)='.strtolower($table);\r
+        } else {\r
+            $query.= "name=$table";\r
+        }\r
+        $query.= " AND sql NOT NULL ORDER BY name";\r
+        $table_def = $db->queryOne($query, 'text');\r
+        if (PEAR::isError($table_def)) {\r
+            return $table_def;\r
+        }\r
+        if (preg_match("/\bPRIMARY\s+KEY\b/i", $table_def, $tmp)) {\r
+            $result['primary'] = true;\r
+        }\r
+\r
+        // ...and for FOREIGN KEYs\r
+        if (preg_match_all("/\bCONSTRAINT\b\s+([^\s]+)\s+\bFOREIGN\s+KEY/imsx", $table_def, $tmp)) {\r
+            foreach ($tmp[1] as $fk) {\r
+                $result[$fk] = true;\r
+            }\r
+        }\r
+\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_change_key_case($result, $db->options['field_case']);\r
+        }\r
+        return array_keys($result);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ createSequence()\r
+\r
+    /**\r
+     * create sequence\r
+     *\r
+     * @param string    $seq_name     name of the sequence to be created\r
+     * @param string    $start         start value of the sequence; default is 1\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function createSequence($seq_name, $start = 1)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);\r
+        $seqcol_name = $db->quoteIdentifier($db->options['seqcol_name'], true);\r
+        $query = "CREATE TABLE $sequence_name ($seqcol_name INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)";\r
+        $res = $db->exec($query);\r
+        if (PEAR::isError($res)) {\r
+            return $res;\r
+        }\r
+        if ($start == 1) {\r
+            return MDB2_OK;\r
+        }\r
+        $res = $db->exec("INSERT INTO $sequence_name ($seqcol_name) VALUES (".($start-1).')');\r
+        if (!PEAR::isError($res)) {\r
+            return MDB2_OK;\r
+        }\r
+        // Handle error\r
+        $result = $db->exec("DROP TABLE $sequence_name");\r
+        if (PEAR::isError($result)) {\r
+            return $db->raiseError($result, null, null,\r
+                'could not drop inconsistent sequence table', __FUNCTION__);\r
+        }\r
+        return $db->raiseError($res, null, null,\r
+            'could not create sequence table', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ dropSequence()\r
+\r
+    /**\r
+     * drop existing sequence\r
+     *\r
+     * @param string    $seq_name     name of the sequence to be dropped\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function dropSequence($seq_name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);\r
+        return $db->exec("DROP TABLE $sequence_name");\r
+    }\r
+\r
+    // }}}\r
+    // {{{ listSequences()\r
+\r
+    /**\r
+     * list all sequences in the current database\r
+     *\r
+     * @return mixed array of sequence names on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function listSequences()\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name";\r
+        $table_names = $db->queryCol($query);\r
+        if (PEAR::isError($table_names)) {\r
+            return $table_names;\r
+        }\r
+        $result = array();\r
+        foreach ($table_names as $table_name) {\r
+            if ($sqn = $this->_fixSequenceName($table_name, true)) {\r
+                $result[] = $sqn;\r
+            }\r
+        }\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+}\r
+?>
\ No newline at end of file
index c01caa35b716fce134664134956f8c635e3adc7a..7cd536ee566d47353903487a0844cfcc941e298d 100644 (file)
@@ -1,61 +1,61 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: Common.php,v 1.2 2007/09/09 13:47:36 quipo Exp $
-//
-
-/**
- * Base class for the natuve modules that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Native');
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Native_Common extends MDB2_Module_Common
-{
-}
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: Common.php 242348 2007-09-09 13:47:36Z quipo $\r
+//\r
+\r
+/**\r
+ * Base class for the natuve modules that is extended by each MDB2 driver\r
+ *\r
+ * To load this module in the MDB2 object:\r
+ * $mdb->loadModule('Native');\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Driver_Native_Common extends MDB2_Module_Common\r
+{\r
+}\r
 ?>
\ No newline at end of file
index 90ff068e6ffb21d26ab3b5dc7517e6614f331e61..f32e3ec3374f789879a4150e66338c782f6e3e93 100644 (file)
@@ -1,60 +1,60 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: mysql.php,v 1.9 2006/06/18 21:59:05 lsmith Exp $
-//
-
-require_once 'MDB2/Driver/Native/Common.php';
-
-/**
- * MDB2 MySQL driver for the native module
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Native_mysql extends MDB2_Driver_Native_Common
-{
-}
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: mysql.php 215004 2006-06-18 21:59:05Z lsmith $\r
+//\r
+\r
+require_once 'MDB2/Driver/Native/Common.php';\r
+\r
+/**\r
+ * MDB2 MySQL driver for the native module\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Driver_Native_mysql extends MDB2_Driver_Native_Common\r
+{\r
+}\r
 ?>
\ No newline at end of file
index acab8389c892ec0f0c95289d7be63af8cd8dff2e..7977b38d3b4d067ced68580a01dd05e9a74d3905 100644 (file)
@@ -1,88 +1,88 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Paul Cooper <pgc@ucecom.com>                                 |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.12 2006/07/15 13:07:15 lsmith Exp $
-
-require_once 'MDB2/Driver/Native/Common.php';
-
-/**
- * MDB2 PostGreSQL driver for the native module
- *
- * @package MDB2
- * @category Database
- * @author  Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_Driver_Native_pgsql extends MDB2_Driver_Native_Common
-{
-    // }}}
-    // {{{ deleteOID()
-
-    /**
-     * delete an OID
-     *
-     * @param integer    $OID
-     * @return mixed MDB2_OK on success or MDB2 Error Object on failure
-     * @access public
-     */
-    function deleteOID($OID)
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $connection = $db->getConnection();
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-
-        if (!@pg_lo_unlink($connection, $OID)) {
-            return $db->raiseError(null, null, null,
-                'Unable to unlink OID: '.$OID, __FUNCTION__);
-        }
-        return MDB2_OK;
-    }
-
-}
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Paul Cooper <pgc@ucecom.com>                                 |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: pgsql.php 295587 2010-02-28 17:16:38Z quipo $\r
+\r
+require_once 'MDB2/Driver/Native/Common.php';\r
+\r
+/**\r
+ * MDB2 PostGreSQL driver for the native module\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Paul Cooper <pgc@ucecom.com>\r
+ */\r
+class MDB2_Driver_Native_pgsql extends MDB2_Driver_Native_Common\r
+{\r
+    // }}}\r
+    // {{{ deleteOID()\r
+\r
+    /**\r
+     * delete an OID\r
+     *\r
+     * @param integer    $OID\r
+     * @return mixed MDB2_OK on success or MDB2 Error Object on failure\r
+     * @access public\r
+     */\r
+    function deleteOID($OID)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $connection = $db->getConnection();\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+\r
+        if (!@pg_lo_unlink($connection, $OID)) {\r
+            return $db->raiseError(null, null, null,\r
+                'Unable to unlink OID: '.$OID, __FUNCTION__);\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+}\r
 ?>
\ No newline at end of file
index 0213293a50a6f351a173727faab816fa7c0b2252..b4da1ce83a3f6d6fe38f131317fa86ca76fe4eb8 100644 (file)
@@ -1,60 +1,60 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: sqlite.php,v 1.9 2006/06/18 21:59:05 lsmith Exp $
-//
-
-require_once 'MDB2/Driver/Native/Common.php';
-
-/**
- * MDB2 SQLite driver for the native module
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Native_sqlite extends MDB2_Driver_Native_Common
-{
-}
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: sqlite.php 215004 2006-06-18 21:59:05Z lsmith $\r
+//\r
+\r
+require_once 'MDB2/Driver/Native/Common.php';\r
+\r
+/**\r
+ * MDB2 SQLite driver for the native module\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Driver_Native_sqlite extends MDB2_Driver_Native_Common\r
+{\r
+}\r
 ?>
\ No newline at end of file
index c78d84f760a490a62ebcb858edbfe02c9b8f6b05..153516d80d8afe9cf7cc9e4fdfd0d509457f57d1 100644 (file)
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: Common.php,v 1.43 2009/01/14 15:01:21 quipo Exp $
-//
-
-/**
- * @package MDB2
- * @category Database
- */
-
-/**
- * These are constants for the tableInfo-function
- * they are bitwised or'ed. so if there are more constants to be defined
- * in the future, adjust MDB2_TABLEINFO_FULL accordingly
- */
-
-define('MDB2_TABLEINFO_ORDER',      1);
-define('MDB2_TABLEINFO_ORDERTABLE', 2);
-define('MDB2_TABLEINFO_FULL',       3);
-
-/**
- * Base class for the schema reverse engineering module that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Reverse');
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Reverse_Common extends MDB2_Module_Common
-{
-    // {{{ splitTableSchema()
-
-    /**
-     * Split the "[owner|schema].table" notation into an array
-     *
-     * @param string $table [schema and] table name
-     *
-     * @return array array(schema, table)
-     * @access private
-     */
-    function splitTableSchema($table)
-    {
-        $ret = array();
-        if (strpos($table, '.') !== false) {
-            return explode('.', $table);
-        }
-        return array(null, $table);
-    }
-
-    // }}}
-    // {{{ getTableFieldDefinition()
-
-    /**
-     * Get the structure of a field into an array
-     *
-     * @param string    $table     name of table that should be used in method
-     * @param string    $field     name of field that should be used in method
-     * @return mixed data array on success, a MDB2 error on failure.
-     *          The returned array contains an array for each field definition,
-     *          with all or some of these indices, depending on the field data type:
-     *          [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type]
-     * @access public
-     */
-    function getTableFieldDefinition($table, $field)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ getTableIndexDefinition()
-
-    /**
-     * Get the structure of an index into an array
-     *
-     * @param string    $table      name of table that should be used in method
-     * @param string    $index      name of index that should be used in method
-     * @return mixed data array on success, a MDB2 error on failure
-     *          The returned array has this structure:
-     *          </pre>
-     *          array (
-     *              [fields] => array (
-     *                  [field1name] => array() // one entry per each field covered
-     *                  [field2name] => array() // by the index
-     *                  [field3name] => array(
-     *                      [sorting] => ascending
-     *                  )
-     *              )
-     *          );
-     *          </pre>
-     * @access public
-     */
-    function getTableIndexDefinition($table, $index)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ getTableConstraintDefinition()
-
-    /**
-     * Get the structure of an constraints into an array
-     *
-     * @param string    $table      name of table that should be used in method
-     * @param string    $index      name of index that should be used in method
-     * @return mixed data array on success, a MDB2 error on failure
-     *          The returned array has this structure:
-     *          <pre>
-     *          array (
-     *              [primary] => 0
-     *              [unique]  => 0
-     *              [foreign] => 1
-     *              [check]   => 0
-     *              [fields] => array (
-     *                  [field1name] => array() // one entry per each field covered
-     *                  [field2name] => array() // by the index
-     *                  [field3name] => array(
-     *                      [sorting]  => ascending
-     *                      [position] => 3
-     *                  )
-     *              )
-     *              [references] => array(
-     *                  [table] => name
-     *                  [fields] => array(
-     *                      [field1name] => array(  //one entry per each referenced field
-     *                           [position] => 1
-     *                      )
-     *                  )
-     *              )
-     *              [deferrable] => 0
-     *              [initiallydeferred] => 0
-     *              [onupdate] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
-     *              [ondelete] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
-     *              [match] => SIMPLE|PARTIAL|FULL
-     *          );
-     *          </pre>
-     * @access public
-     */
-    function getTableConstraintDefinition($table, $index)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ getSequenceDefinition()
-
-    /**
-     * Get the structure of a sequence into an array
-     *
-     * @param string    $sequence   name of sequence that should be used in method
-     * @return mixed data array on success, a MDB2 error on failure
-     *          The returned array has this structure:
-     *          <pre>
-     *          array (
-     *              [start] => n
-     *          );
-     *          </pre>
-     * @access public
-     */
-    function getSequenceDefinition($sequence)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $start = $db->currId($sequence);
-        if (PEAR::isError($start)) {
-            return $start;
-        }
-        if ($db->supports('current_id')) {
-            $start++;
-        } else {
-            $db->warnings[] = 'database does not support getting current
-                sequence value, the sequence value was incremented';
-        }
-        $definition = array();
-        if ($start != 1) {
-            $definition = array('start' => $start);
-        }
-        return $definition;
-    }
-
-    // }}}
-    // {{{ getTriggerDefinition()
-
-    /**
-     * Get the structure of a trigger into an array
-     *
-     * EXPERIMENTAL
-     *
-     * WARNING: this function is experimental and may change the returned value 
-     * at any time until labelled as non-experimental
-     *
-     * @param string    $trigger    name of trigger that should be used in method
-     * @return mixed data array on success, a MDB2 error on failure
-     *          The returned array has this structure:
-     *          <pre>
-     *          array (
-     *              [trigger_name]    => 'trigger name',
-     *              [table_name]      => 'table name',
-     *              [trigger_body]    => 'trigger body definition',
-     *              [trigger_type]    => 'BEFORE' | 'AFTER',
-     *              [trigger_event]   => 'INSERT' | 'UPDATE' | 'DELETE'
-     *                  //or comma separated list of multiple events, when supported
-     *              [trigger_enabled] => true|false
-     *              [trigger_comment] => 'trigger comment',
-     *          );
-     *          </pre>
-     *          The oci8 driver also returns a [when_clause] index.
-     * @access public
-     */
-    function getTriggerDefinition($trigger)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-            'method not implemented', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ tableInfo()
-
-    /**
-     * Returns information about a table or a result set
-     *
-     * The format of the resulting array depends on which <var>$mode</var>
-     * you select.  The sample output below is based on this query:
-     * <pre>
-     *    SELECT tblFoo.fldID, tblFoo.fldPhone, tblBar.fldId
-     *    FROM tblFoo
-     *    JOIN tblBar ON tblFoo.fldId = tblBar.fldId
-     * </pre>
-     *
-     * <ul>
-     * <li>
-     *
-     * <kbd>null</kbd> (default)
-     *   <pre>
-     *   [0] => Array (
-     *       [table] => tblFoo
-     *       [name] => fldId
-     *       [type] => int
-     *       [len] => 11
-     *       [flags] => primary_key not_null
-     *   )
-     *   [1] => Array (
-     *       [table] => tblFoo
-     *       [name] => fldPhone
-     *       [type] => string
-     *       [len] => 20
-     *       [flags] =>
-     *   )
-     *   [2] => Array (
-     *       [table] => tblBar
-     *       [name] => fldId
-     *       [type] => int
-     *       [len] => 11
-     *       [flags] => primary_key not_null
-     *   )
-     *   </pre>
-     *
-     * </li><li>
-     *
-     * <kbd>MDB2_TABLEINFO_ORDER</kbd>
-     *
-     *   <p>In addition to the information found in the default output,
-     *   a notation of the number of columns is provided by the
-     *   <samp>num_fields</samp> element while the <samp>order</samp>
-     *   element provides an array with the column names as the keys and
-     *   their location index number (corresponding to the keys in the
-     *   the default output) as the values.</p>
-     *
-     *   <p>If a result set has identical field names, the last one is
-     *   used.</p>
-     *
-     *   <pre>
-     *   [num_fields] => 3
-     *   [order] => Array (
-     *       [fldId] => 2
-     *       [fldTrans] => 1
-     *   )
-     *   </pre>
-     *
-     * </li><li>
-     *
-     * <kbd>MDB2_TABLEINFO_ORDERTABLE</kbd>
-     *
-     *   <p>Similar to <kbd>MDB2_TABLEINFO_ORDER</kbd> but adds more
-     *   dimensions to the array in which the table names are keys and
-     *   the field names are sub-keys.  This is helpful for queries that
-     *   join tables which have identical field names.</p>
-     *
-     *   <pre>
-     *   [num_fields] => 3
-     *   [ordertable] => Array (
-     *       [tblFoo] => Array (
-     *           [fldId] => 0
-     *           [fldPhone] => 1
-     *       )
-     *       [tblBar] => Array (
-     *           [fldId] => 2
-     *       )
-     *   )
-     *   </pre>
-     *
-     * </li>
-     * </ul>
-     *
-     * The <samp>flags</samp> element contains a space separated list
-     * of extra information about the field.  This data is inconsistent
-     * between DBMS's due to the way each DBMS works.
-     *   + <samp>primary_key</samp>
-     *   + <samp>unique_key</samp>
-     *   + <samp>multiple_key</samp>
-     *   + <samp>not_null</samp>
-     *
-     * Most DBMS's only provide the <samp>table</samp> and <samp>flags</samp>
-     * elements if <var>$result</var> is a table name.  The following DBMS's
-     * provide full information from queries:
-     *   + fbsql
-     *   + mysql
-     *
-     * If the 'portability' option has <samp>MDB2_PORTABILITY_FIX_CASE</samp>
-     * turned on, the names of tables and fields will be lower or upper cased.
-     *
-     * @param object|string  $result  MDB2_result object from a query or a
-     *                                string containing the name of a table.
-     *                                While this also accepts a query result
-     *                                resource identifier, this behavior is
-     *                                deprecated.
-     * @param int  $mode   either unused or one of the tableInfo modes:
-     *                     <kbd>MDB2_TABLEINFO_ORDERTABLE</kbd>,
-     *                     <kbd>MDB2_TABLEINFO_ORDER</kbd> or
-     *                     <kbd>MDB2_TABLEINFO_FULL</kbd> (which does both).
-     *                     These are bitwise, so the first two can be
-     *                     combined using <kbd>|</kbd>.
-     *
-     * @return array  an associative array with the information requested.
-     *                 A MDB2_Error object on failure.
-     *
-     * @see MDB2_Driver_Common::setOption()
-     */
-    function tableInfo($result, $mode = null)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        if (!is_string($result)) {
-            return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'method not implemented', __FUNCTION__);
-        }
-
-        $db->loadModule('Manager', null, true);
-        $fields = $db->manager->listTableFields($result);
-        if (PEAR::isError($fields)) {
-            return $fields;
-        }
-
-        $flags = array();
-
-        $idxname_format = $db->getOption('idxname_format');
-        $db->setOption('idxname_format', '%s');
-
-        $indexes = $db->manager->listTableIndexes($result);
-        if (PEAR::isError($indexes)) {
-            $db->setOption('idxname_format', $idxname_format);
-            return $indexes;
-        }
-
-        foreach ($indexes as $index) {
-            $definition = $this->getTableIndexDefinition($result, $index);
-            if (PEAR::isError($definition)) {
-                $db->setOption('idxname_format', $idxname_format);
-                return $definition;
-            }
-            if (count($definition['fields']) > 1) {
-                foreach ($definition['fields'] as $field => $sort) {
-                    $flags[$field] = 'multiple_key';
-                }
-            }
-        }
-
-        $constraints = $db->manager->listTableConstraints($result);
-        if (PEAR::isError($constraints)) {
-            return $constraints;
-        }
-
-        foreach ($constraints as $constraint) {
-            $definition = $this->getTableConstraintDefinition($result, $constraint);
-            if (PEAR::isError($definition)) {
-                $db->setOption('idxname_format', $idxname_format);
-                return $definition;
-            }
-            $flag = !empty($definition['primary'])
-                ? 'primary_key' : (!empty($definition['unique'])
-                    ? 'unique_key' : false);
-            if ($flag) {
-                foreach ($definition['fields'] as $field => $sort) {
-                    if (empty($flags[$field]) || $flags[$field] != 'primary_key') {
-                        $flags[$field] = $flag;
-                    }
-                }
-            }
-        }
-
-        $res = array();
-
-        if ($mode) {
-            $res['num_fields'] = count($fields);
-        }
-
-        foreach ($fields as $i => $field) {
-            $definition = $this->getTableFieldDefinition($result, $field);
-            if (PEAR::isError($definition)) {
-                $db->setOption('idxname_format', $idxname_format);
-                return $definition;
-            }
-            $res[$i] = $definition[0];
-            $res[$i]['name'] = $field;
-            $res[$i]['table'] = $result;
-            $res[$i]['type'] = preg_replace('/^([a-z]+).*$/i', '\\1', trim($definition[0]['nativetype']));
-            // 'primary_key', 'unique_key', 'multiple_key'
-            $res[$i]['flags'] = empty($flags[$field]) ? '' : $flags[$field];
-            // not_null', 'unsigned', 'auto_increment', 'default_[rawencodedvalue]'
-            if (!empty($res[$i]['notnull'])) {
-                $res[$i]['flags'].= ' not_null';
-            }
-            if (!empty($res[$i]['unsigned'])) {
-                $res[$i]['flags'].= ' unsigned';
-            }
-            if (!empty($res[$i]['auto_increment'])) {
-                $res[$i]['flags'].= ' autoincrement';
-            }
-            if (!empty($res[$i]['default'])) {
-                $res[$i]['flags'].= ' default_'.rawurlencode($res[$i]['default']);
-            }
-
-            if ($mode & MDB2_TABLEINFO_ORDER) {
-                $res['order'][$res[$i]['name']] = $i;
-            }
-            if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
-                $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
-            }
-        }
-
-        $db->setOption('idxname_format', $idxname_format);
-        return $res;
-    }
-}
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: Common.php 295587 2010-02-28 17:16:38Z quipo $\r
+//\r
+\r
+/**\r
+ * @package MDB2\r
+ * @category Database\r
+ */\r
+\r
+/**\r
+ * These are constants for the tableInfo-function\r
+ * they are bitwised or'ed. so if there are more constants to be defined\r
+ * in the future, adjust MDB2_TABLEINFO_FULL accordingly\r
+ */\r
+\r
+define('MDB2_TABLEINFO_ORDER',      1);\r
+define('MDB2_TABLEINFO_ORDERTABLE', 2);\r
+define('MDB2_TABLEINFO_FULL',       3);\r
+\r
+/**\r
+ * Base class for the schema reverse engineering module that is extended by each MDB2 driver\r
+ *\r
+ * To load this module in the MDB2 object:\r
+ * $mdb->loadModule('Reverse');\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Driver_Reverse_Common extends MDB2_Module_Common\r
+{\r
+    // {{{ splitTableSchema()\r
+\r
+    /**\r
+     * Split the "[owner|schema].table" notation into an array\r
+     *\r
+     * @param string $table [schema and] table name\r
+     *\r
+     * @return array array(schema, table)\r
+     * @access private\r
+     */\r
+    function splitTableSchema($table)\r
+    {\r
+        $ret = array();\r
+        if (strpos($table, '.') !== false) {\r
+            return explode('.', $table);\r
+        }\r
+        return array(null, $table);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getTableFieldDefinition()\r
+\r
+    /**\r
+     * Get the structure of a field into an array\r
+     *\r
+     * @param string    $table     name of table that should be used in method\r
+     * @param string    $field     name of field that should be used in method\r
+     * @return mixed data array on success, a MDB2 error on failure.\r
+     *          The returned array contains an array for each field definition,\r
+     *          with all or some of these indices, depending on the field data type:\r
+     *          [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type]\r
+     * @access public\r
+     */\r
+    function getTableFieldDefinition($table, $field)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getTableIndexDefinition()\r
+\r
+    /**\r
+     * Get the structure of an index into an array\r
+     *\r
+     * @param string    $table      name of table that should be used in method\r
+     * @param string    $index      name of index that should be used in method\r
+     * @return mixed data array on success, a MDB2 error on failure\r
+     *          The returned array has this structure:\r
+     *          </pre>\r
+     *          array (\r
+     *              [fields] => array (\r
+     *                  [field1name] => array() // one entry per each field covered\r
+     *                  [field2name] => array() // by the index\r
+     *                  [field3name] => array(\r
+     *                      [sorting] => ascending\r
+     *                  )\r
+     *              )\r
+     *          );\r
+     *          </pre>\r
+     * @access public\r
+     */\r
+    function getTableIndexDefinition($table, $index)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getTableConstraintDefinition()\r
+\r
+    /**\r
+     * Get the structure of an constraints into an array\r
+     *\r
+     * @param string    $table      name of table that should be used in method\r
+     * @param string    $index      name of index that should be used in method\r
+     * @return mixed data array on success, a MDB2 error on failure\r
+     *          The returned array has this structure:\r
+     *          <pre>\r
+     *          array (\r
+     *              [primary] => 0\r
+     *              [unique]  => 0\r
+     *              [foreign] => 1\r
+     *              [check]   => 0\r
+     *              [fields] => array (\r
+     *                  [field1name] => array() // one entry per each field covered\r
+     *                  [field2name] => array() // by the index\r
+     *                  [field3name] => array(\r
+     *                      [sorting]  => ascending\r
+     *                      [position] => 3\r
+     *                  )\r
+     *              )\r
+     *              [references] => array(\r
+     *                  [table] => name\r
+     *                  [fields] => array(\r
+     *                      [field1name] => array(  //one entry per each referenced field\r
+     *                           [position] => 1\r
+     *                      )\r
+     *                  )\r
+     *              )\r
+     *              [deferrable] => 0\r
+     *              [initiallydeferred] => 0\r
+     *              [onupdate] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION\r
+     *              [ondelete] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION\r
+     *              [match] => SIMPLE|PARTIAL|FULL\r
+     *          );\r
+     *          </pre>\r
+     * @access public\r
+     */\r
+    function getTableConstraintDefinition($table, $index)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getSequenceDefinition()\r
+\r
+    /**\r
+     * Get the structure of a sequence into an array\r
+     *\r
+     * @param string    $sequence   name of sequence that should be used in method\r
+     * @return mixed data array on success, a MDB2 error on failure\r
+     *          The returned array has this structure:\r
+     *          <pre>\r
+     *          array (\r
+     *              [start] => n\r
+     *          );\r
+     *          </pre>\r
+     * @access public\r
+     */\r
+    function getSequenceDefinition($sequence)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $start = $db->currId($sequence);\r
+        if (PEAR::isError($start)) {\r
+            return $start;\r
+        }\r
+        if ($db->supports('current_id')) {\r
+            $start++;\r
+        } else {\r
+            $db->warnings[] = 'database does not support getting current\r
+                sequence value, the sequence value was incremented';\r
+        }\r
+        $definition = array();\r
+        if ($start != 1) {\r
+            $definition = array('start' => $start);\r
+        }\r
+        return $definition;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getTriggerDefinition()\r
+\r
+    /**\r
+     * Get the structure of a trigger into an array\r
+     *\r
+     * EXPERIMENTAL\r
+     *\r
+     * WARNING: this function is experimental and may change the returned value \r
+     * at any time until labelled as non-experimental\r
+     *\r
+     * @param string    $trigger    name of trigger that should be used in method\r
+     * @return mixed data array on success, a MDB2 error on failure\r
+     *          The returned array has this structure:\r
+     *          <pre>\r
+     *          array (\r
+     *              [trigger_name]    => 'trigger name',\r
+     *              [table_name]      => 'table name',\r
+     *              [trigger_body]    => 'trigger body definition',\r
+     *              [trigger_type]    => 'BEFORE' | 'AFTER',\r
+     *              [trigger_event]   => 'INSERT' | 'UPDATE' | 'DELETE'\r
+     *                  //or comma separated list of multiple events, when supported\r
+     *              [trigger_enabled] => true|false\r
+     *              [trigger_comment] => 'trigger comment',\r
+     *          );\r
+     *          </pre>\r
+     *          The oci8 driver also returns a [when_clause] index.\r
+     * @access public\r
+     */\r
+    function getTriggerDefinition($trigger)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+            'method not implemented', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ tableInfo()\r
+\r
+    /**\r
+     * Returns information about a table or a result set\r
+     *\r
+     * The format of the resulting array depends on which <var>$mode</var>\r
+     * you select.  The sample output below is based on this query:\r
+     * <pre>\r
+     *    SELECT tblFoo.fldID, tblFoo.fldPhone, tblBar.fldId\r
+     *    FROM tblFoo\r
+     *    JOIN tblBar ON tblFoo.fldId = tblBar.fldId\r
+     * </pre>\r
+     *\r
+     * <ul>\r
+     * <li>\r
+     *\r
+     * <kbd>null</kbd> (default)\r
+     *   <pre>\r
+     *   [0] => Array (\r
+     *       [table] => tblFoo\r
+     *       [name] => fldId\r
+     *       [type] => int\r
+     *       [len] => 11\r
+     *       [flags] => primary_key not_null\r
+     *   )\r
+     *   [1] => Array (\r
+     *       [table] => tblFoo\r
+     *       [name] => fldPhone\r
+     *       [type] => string\r
+     *       [len] => 20\r
+     *       [flags] =>\r
+     *   )\r
+     *   [2] => Array (\r
+     *       [table] => tblBar\r
+     *       [name] => fldId\r
+     *       [type] => int\r
+     *       [len] => 11\r
+     *       [flags] => primary_key not_null\r
+     *   )\r
+     *   </pre>\r
+     *\r
+     * </li><li>\r
+     *\r
+     * <kbd>MDB2_TABLEINFO_ORDER</kbd>\r
+     *\r
+     *   <p>In addition to the information found in the default output,\r
+     *   a notation of the number of columns is provided by the\r
+     *   <samp>num_fields</samp> element while the <samp>order</samp>\r
+     *   element provides an array with the column names as the keys and\r
+     *   their location index number (corresponding to the keys in the\r
+     *   the default output) as the values.</p>\r
+     *\r
+     *   <p>If a result set has identical field names, the last one is\r
+     *   used.</p>\r
+     *\r
+     *   <pre>\r
+     *   [num_fields] => 3\r
+     *   [order] => Array (\r
+     *       [fldId] => 2\r
+     *       [fldTrans] => 1\r
+     *   )\r
+     *   </pre>\r
+     *\r
+     * </li><li>\r
+     *\r
+     * <kbd>MDB2_TABLEINFO_ORDERTABLE</kbd>\r
+     *\r
+     *   <p>Similar to <kbd>MDB2_TABLEINFO_ORDER</kbd> but adds more\r
+     *   dimensions to the array in which the table names are keys and\r
+     *   the field names are sub-keys.  This is helpful for queries that\r
+     *   join tables which have identical field names.</p>\r
+     *\r
+     *   <pre>\r
+     *   [num_fields] => 3\r
+     *   [ordertable] => Array (\r
+     *       [tblFoo] => Array (\r
+     *           [fldId] => 0\r
+     *           [fldPhone] => 1\r
+     *       )\r
+     *       [tblBar] => Array (\r
+     *           [fldId] => 2\r
+     *       )\r
+     *   )\r
+     *   </pre>\r
+     *\r
+     * </li>\r
+     * </ul>\r
+     *\r
+     * The <samp>flags</samp> element contains a space separated list\r
+     * of extra information about the field.  This data is inconsistent\r
+     * between DBMS's due to the way each DBMS works.\r
+     *   + <samp>primary_key</samp>\r
+     *   + <samp>unique_key</samp>\r
+     *   + <samp>multiple_key</samp>\r
+     *   + <samp>not_null</samp>\r
+     *\r
+     * Most DBMS's only provide the <samp>table</samp> and <samp>flags</samp>\r
+     * elements if <var>$result</var> is a table name.  The following DBMS's\r
+     * provide full information from queries:\r
+     *   + fbsql\r
+     *   + mysql\r
+     *\r
+     * If the 'portability' option has <samp>MDB2_PORTABILITY_FIX_CASE</samp>\r
+     * turned on, the names of tables and fields will be lower or upper cased.\r
+     *\r
+     * @param object|string  $result  MDB2_result object from a query or a\r
+     *                                string containing the name of a table.\r
+     *                                While this also accepts a query result\r
+     *                                resource identifier, this behavior is\r
+     *                                deprecated.\r
+     * @param int  $mode   either unused or one of the tableInfo modes:\r
+     *                     <kbd>MDB2_TABLEINFO_ORDERTABLE</kbd>,\r
+     *                     <kbd>MDB2_TABLEINFO_ORDER</kbd> or\r
+     *                     <kbd>MDB2_TABLEINFO_FULL</kbd> (which does both).\r
+     *                     These are bitwise, so the first two can be\r
+     *                     combined using <kbd>|</kbd>.\r
+     *\r
+     * @return array  an associative array with the information requested.\r
+     *                 A MDB2_Error object on failure.\r
+     *\r
+     * @see MDB2_Driver_Common::setOption()\r
+     */\r
+    function tableInfo($result, $mode = null)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        if (!is_string($result)) {\r
+            return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'method not implemented', __FUNCTION__);\r
+        }\r
+\r
+        $db->loadModule('Manager', null, true);\r
+        $fields = $db->manager->listTableFields($result);\r
+        if (PEAR::isError($fields)) {\r
+            return $fields;\r
+        }\r
+\r
+        $flags = array();\r
+\r
+        $idxname_format = $db->getOption('idxname_format');\r
+        $db->setOption('idxname_format', '%s');\r
+\r
+        $indexes = $db->manager->listTableIndexes($result);\r
+        if (PEAR::isError($indexes)) {\r
+            $db->setOption('idxname_format', $idxname_format);\r
+            return $indexes;\r
+        }\r
+\r
+        foreach ($indexes as $index) {\r
+            $definition = $this->getTableIndexDefinition($result, $index);\r
+            if (PEAR::isError($definition)) {\r
+                $db->setOption('idxname_format', $idxname_format);\r
+                return $definition;\r
+            }\r
+            if (count($definition['fields']) > 1) {\r
+                foreach ($definition['fields'] as $field => $sort) {\r
+                    $flags[$field] = 'multiple_key';\r
+                }\r
+            }\r
+        }\r
+\r
+        $constraints = $db->manager->listTableConstraints($result);\r
+        if (PEAR::isError($constraints)) {\r
+            return $constraints;\r
+        }\r
+\r
+        foreach ($constraints as $constraint) {\r
+            $definition = $this->getTableConstraintDefinition($result, $constraint);\r
+            if (PEAR::isError($definition)) {\r
+                $db->setOption('idxname_format', $idxname_format);\r
+                return $definition;\r
+            }\r
+            $flag = !empty($definition['primary'])\r
+                ? 'primary_key' : (!empty($definition['unique'])\r
+                    ? 'unique_key' : false);\r
+            if ($flag) {\r
+                foreach ($definition['fields'] as $field => $sort) {\r
+                    if (empty($flags[$field]) || $flags[$field] != 'primary_key') {\r
+                        $flags[$field] = $flag;\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+        $res = array();\r
+\r
+        if ($mode) {\r
+            $res['num_fields'] = count($fields);\r
+        }\r
+\r
+        foreach ($fields as $i => $field) {\r
+            $definition = $this->getTableFieldDefinition($result, $field);\r
+            if (PEAR::isError($definition)) {\r
+                $db->setOption('idxname_format', $idxname_format);\r
+                return $definition;\r
+            }\r
+            $res[$i] = $definition[0];\r
+            $res[$i]['name'] = $field;\r
+            $res[$i]['table'] = $result;\r
+            $res[$i]['type'] = preg_replace('/^([a-z]+).*$/i', '\\1', trim($definition[0]['nativetype']));\r
+            // 'primary_key', 'unique_key', 'multiple_key'\r
+            $res[$i]['flags'] = empty($flags[$field]) ? '' : $flags[$field];\r
+            // not_null', 'unsigned', 'auto_increment', 'default_[rawencodedvalue]'\r
+            if (!empty($res[$i]['notnull'])) {\r
+                $res[$i]['flags'].= ' not_null';\r
+            }\r
+            if (!empty($res[$i]['unsigned'])) {\r
+                $res[$i]['flags'].= ' unsigned';\r
+            }\r
+            if (!empty($res[$i]['auto_increment'])) {\r
+                $res[$i]['flags'].= ' autoincrement';\r
+            }\r
+            if (!empty($res[$i]['default'])) {\r
+                $res[$i]['flags'].= ' default_'.rawurlencode($res[$i]['default']);\r
+            }\r
+\r
+            if ($mode & MDB2_TABLEINFO_ORDER) {\r
+                $res['order'][$res[$i]['name']] = $i;\r
+            }\r
+            if ($mode & MDB2_TABLEINFO_ORDERTABLE) {\r
+                $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;\r
+            }\r
+        }\r
+\r
+        $db->setOption('idxname_format', $idxname_format);\r
+        return $res;\r
+    }\r
+}\r
 ?>
\ No newline at end of file
index 6e366c22a5e09b78cbd351a3fd37e9953f8be290..7b9b4e0019cc44a34b6e2cd34e826186f10144ab 100644 (file)
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: mysql.php,v 1.80 2008/03/26 21:15:37 quipo Exp $
-//
-
-require_once('MDB2/Driver/Reverse/Common.php');
-
-/**
- * MDB2 MySQL driver for the schema reverse engineering module
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- * @author  Lorenzo Alberton <l.alberton@quipo.it>
- */
-class MDB2_Driver_Reverse_mysql extends MDB2_Driver_Reverse_Common
-{
-    // {{{ getTableFieldDefinition()
-
-    /**
-     * Get the structure of a field into an array
-     *
-     * @param string $table_name name of table that should be used in method
-     * @param string $field_name name of field that should be used in method
-     * @return mixed data array on success, a MDB2 error on failure
-     * @access public
-     */
-    function getTableFieldDefinition($table_name, $field_name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $result = $db->loadModule('Datatype', null, true);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-
-        list($schema, $table) = $this->splitTableSchema($table_name);
-
-        $table = $db->quoteIdentifier($table, true);
-        $query = "SHOW FULL COLUMNS FROM $table LIKE ".$db->quote($field_name);
-        $columns = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);
-        if (PEAR::isError($columns)) {
-            return $columns;
-        }
-        foreach ($columns as $column) {
-            $column = array_change_key_case($column, CASE_LOWER);
-            $column['name'] = $column['field'];
-            unset($column['field']);
-            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-                if ($db->options['field_case'] == CASE_LOWER) {
-                    $column['name'] = strtolower($column['name']);
-                } else {
-                    $column['name'] = strtoupper($column['name']);
-                }
-            } else {
-                $column = array_change_key_case($column, $db->options['field_case']);
-            }
-            if ($field_name == $column['name']) {
-                $mapped_datatype = $db->datatype->mapNativeDatatype($column);
-                if (PEAR::isError($mapped_datatype)) {
-                    return $mapped_datatype;
-                }
-                list($types, $length, $unsigned, $fixed) = $mapped_datatype;
-                $notnull = false;
-                if (empty($column['null']) || $column['null'] !== 'YES') {
-                    $notnull = true;
-                }
-                $default = false;
-                if (array_key_exists('default', $column)) {
-                    $default = $column['default'];
-                    if (is_null($default) && $notnull) {
-                        $default = '';
-                    }
-                }
-                $autoincrement = false;
-                if (!empty($column['extra']) && $column['extra'] == 'auto_increment') {
-                    $autoincrement = true;
-                }
-                $collate = null;
-                if (!empty($column['collation'])) {
-                    $collate = $column['collation'];
-                    $charset = preg_replace('/(.+?)(_.+)?/', '$1', $collate);
-                }
-
-                $definition[0] = array(
-                    'notnull' => $notnull,
-                    'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type'])
-                );
-                if (!is_null($length)) {
-                    $definition[0]['length'] = $length;
-                }
-                if (!is_null($unsigned)) {
-                    $definition[0]['unsigned'] = $unsigned;
-                }
-                if (!is_null($fixed)) {
-                    $definition[0]['fixed'] = $fixed;
-                }
-                if ($default !== false) {
-                    $definition[0]['default'] = $default;
-                }
-                if ($autoincrement !== false) {
-                    $definition[0]['autoincrement'] = $autoincrement;
-                }
-                if (!is_null($collate)) {
-                    $definition[0]['collate'] = $collate;
-                    $definition[0]['charset'] = $charset;
-                }
-                foreach ($types as $key => $type) {
-                    $definition[$key] = $definition[0];
-                    if ($type == 'clob' || $type == 'blob') {
-                        unset($definition[$key]['default']);
-                    } elseif ($type == 'timestamp' && $notnull && empty($definition[$key]['default'])) {
-                        $definition[$key]['default'] = '0000-00-00 00:00:00';
-                    }
-                    $definition[$key]['type'] = $type;
-                    $definition[$key]['mdb2type'] = $type;
-                }
-                return $definition;
-            }
-        }
-
-        return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-            'it was not specified an existing table column', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ getTableIndexDefinition()
-
-    /**
-     * Get the structure of an index into an array
-     *
-     * @param string $table_name name of table that should be used in method
-     * @param string $index_name name of index that should be used in method
-     * @return mixed data array on success, a MDB2 error on failure
-     * @access public
-     */
-    function getTableIndexDefinition($table_name, $index_name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        list($schema, $table) = $this->splitTableSchema($table_name);
-
-        $table = $db->quoteIdentifier($table, true);
-        $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */";
-        $index_name_mdb2 = $db->getIndexName($index_name);
-        $result = $db->queryRow(sprintf($query, $db->quote($index_name_mdb2)));
-        if (!PEAR::isError($result) && !is_null($result)) {
-            // apply 'idxname_format' only if the query succeeded, otherwise
-            // fallback to the given $index_name, without transformation
-            $index_name = $index_name_mdb2;
-        }
-        $result = $db->query(sprintf($query, $db->quote($index_name)));
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        $colpos = 1;
-        $definition = array();
-        while (is_array($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC))) {
-            $row = array_change_key_case($row, CASE_LOWER);
-            $key_name = $row['key_name'];
-            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-                if ($db->options['field_case'] == CASE_LOWER) {
-                    $key_name = strtolower($key_name);
-                } else {
-                    $key_name = strtoupper($key_name);
-                }
-            }
-            if ($index_name == $key_name) {
-                if (!$row['non_unique']) {
-                    return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                        $index_name . ' is not an existing table index', __FUNCTION__);
-                }
-                $column_name = $row['column_name'];
-                if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-                    if ($db->options['field_case'] == CASE_LOWER) {
-                        $column_name = strtolower($column_name);
-                    } else {
-                        $column_name = strtoupper($column_name);
-                    }
-                }
-                $definition['fields'][$column_name] = array(
-                    'position' => $colpos++
-                );
-                if (!empty($row['collation'])) {
-                    $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A'
-                        ? 'ascending' : 'descending');
-                }
-            }
-        }
-        $result->free();
-        if (empty($definition['fields'])) {
-            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                $index_name . ' is not an existing table index', __FUNCTION__);
-        }
-        return $definition;
-    }
-
-    // }}}
-    // {{{ getTableConstraintDefinition()
-
-    /**
-     * Get the structure of a constraint into an array
-     *
-     * @param string $table_name      name of table that should be used in method
-     * @param string $constraint_name name of constraint that should be used in method
-     * @return mixed data array on success, a MDB2 error on failure
-     * @access public
-     */
-    function getTableConstraintDefinition($table_name, $constraint_name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        list($schema, $table) = $this->splitTableSchema($table_name);
-        $constraint_name_original = $constraint_name;
-
-        $table = $db->quoteIdentifier($table, true);
-        $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */";
-        if (strtolower($constraint_name) != 'primary') {
-            $constraint_name_mdb2 = $db->getIndexName($constraint_name);
-            $result = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2)));
-            if (!PEAR::isError($result) && !is_null($result)) {
-                // apply 'idxname_format' only if the query succeeded, otherwise
-                // fallback to the given $index_name, without transformation
-                $constraint_name = $constraint_name_mdb2;
-            }
-        }
-        $result = $db->query(sprintf($query, $db->quote($constraint_name)));
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        $colpos = 1;
-        //default values, eventually overridden
-        $definition = array(
-            'primary' => false,
-            'unique'  => false,
-            'foreign' => false,
-            'check'   => false,
-            'fields'  => array(),
-            'references' => array(
-                'table'  => '',
-                'fields' => array(),
-            ),
-            'onupdate'  => '',
-            'ondelete'  => '',
-            'match'     => '',
-            'deferrable'        => false,
-            'initiallydeferred' => false,
-        );
-        while (is_array($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC))) {
-            $row = array_change_key_case($row, CASE_LOWER);
-            $key_name = $row['key_name'];
-            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-                if ($db->options['field_case'] == CASE_LOWER) {
-                    $key_name = strtolower($key_name);
-                } else {
-                    $key_name = strtoupper($key_name);
-                }
-            }
-            if ($constraint_name == $key_name) {
-                if ($row['non_unique']) {
-                    //FOREIGN KEY?
-                    return $this->_getTableFKConstraintDefinition($table, $constraint_name_original, $definition);
-                }
-                if ($row['key_name'] == 'PRIMARY') {
-                    $definition['primary'] = true;
-                } elseif (!$row['non_unique']) {
-                    $definition['unique'] = true;
-                }
-                $column_name = $row['column_name'];
-                if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-                    if ($db->options['field_case'] == CASE_LOWER) {
-                        $column_name = strtolower($column_name);
-                    } else {
-                        $column_name = strtoupper($column_name);
-                    }
-                }
-                $definition['fields'][$column_name] = array(
-                    'position' => $colpos++
-                );
-                if (!empty($row['collation'])) {
-                    $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A'
-                        ? 'ascending' : 'descending');
-                }
-            }
-        }
-        $result->free();
-        if (empty($definition['fields'])) {
-            return $this->_getTableFKConstraintDefinition($table, $constraint_name_original, $definition);
-        }
-        return $definition;
-    }
-
-    // }}}
-    // {{{ _getTableFKConstraintDefinition()
-    
-    /**
-     * Get the FK definition from the CREATE TABLE statement
-     *
-     * @param string $table           table name
-     * @param string $constraint_name constraint name
-     * @param array  $definition      default values for constraint definition
-     *
-     * @return array|PEAR_Error
-     * @access private
-     */
-    function _getTableFKConstraintDefinition($table, $constraint_name, $definition)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-        $query = 'SHOW CREATE TABLE '. $db->escape($table);
-        $constraint = $db->queryOne($query, 'text', 1);
-        if (!PEAR::isError($constraint) && !empty($constraint)) {
-            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-                if ($db->options['field_case'] == CASE_LOWER) {
-                    $constraint = strtolower($constraint);
-                } else {
-                    $constraint = strtoupper($constraint);
-                }
-            }
-            $constraint_name_original = $constraint_name;
-            $constraint_name = $db->getIndexName($constraint_name);
-            $pattern = '/\bCONSTRAINT\s+'.$constraint_name.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^ ]+) \(([^\)]+)\)/i';
-            if (!preg_match($pattern, str_replace('`', '', $constraint), $matches)) {
-                //fallback to original constraint name
-                $pattern = '/\bCONSTRAINT\s+'.$constraint_name_original.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^ ]+) \(([^\)]+)\)/i';
-            }
-            if (preg_match($pattern, str_replace('`', '', $constraint), $matches)) {
-                $definition['foreign'] = true;
-                $column_names = explode(',', $matches[1]);
-                $referenced_cols = explode(',', $matches[3]);
-                $definition['references'] = array(
-                    'table'  => $matches[2],
-                    'fields' => array(),
-                );
-                $colpos = 1;
-                foreach ($column_names as $column_name) {
-                    $definition['fields'][trim($column_name)] = array(
-                        'position' => $colpos++
-                    );
-                }
-                $colpos = 1;
-                foreach ($referenced_cols as $column_name) {
-                    $definition['references']['fields'][trim($column_name)] = array(
-                        'position' => $colpos++
-                    );
-                }
-                $definition['onupdate'] = 'NO ACTION';
-                $definition['ondelete'] = 'NO ACTION';
-                $definition['match']    = 'SIMPLE';
-                return $definition;
-            }
-        }
-        return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                $constraint_name . ' is not an existing table constraint', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ getTriggerDefinition()
-
-    /**
-     * Get the structure of a trigger into an array
-     *
-     * EXPERIMENTAL
-     *
-     * WARNING: this function is experimental and may change the returned value
-     * at any time until labelled as non-experimental
-     *
-     * @param string    $trigger    name of trigger that should be used in method
-     * @return mixed data array on success, a MDB2 error on failure
-     * @access public
-     */
-    function getTriggerDefinition($trigger)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = 'SELECT trigger_name,
-                         event_object_table AS table_name,
-                         action_statement AS trigger_body,
-                         action_timing AS trigger_type,
-                         event_manipulation AS trigger_event
-                    FROM information_schema.triggers
-                   WHERE trigger_name = '. $db->quote($trigger, 'text');
-        $types = array(
-            'trigger_name'    => 'text',
-            'table_name'      => 'text',
-            'trigger_body'    => 'text',
-            'trigger_type'    => 'text',
-            'trigger_event'   => 'text',
-        );
-        $def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
-        if (PEAR::isError($def)) {
-            return $def;
-        }
-        $def['trigger_comment'] = '';
-        $def['trigger_enabled'] = true;
-        return $def;
-    }
-
-    // }}}
-    // {{{ tableInfo()
-
-    /**
-     * Returns information about a table or a result set
-     *
-     * @param object|string  $result  MDB2_result object from a query or a
-     *                                 string containing the name of a table.
-     *                                 While this also accepts a query result
-     *                                 resource identifier, this behavior is
-     *                                 deprecated.
-     * @param int            $mode    a valid tableInfo mode
-     *
-     * @return array  an associative array with the information requested.
-     *                 A MDB2_Error object on failure.
-     *
-     * @see MDB2_Driver_Common::setOption()
-     */
-    function tableInfo($result, $mode = null)
-    {
-        if (is_string($result)) {
-           return parent::tableInfo($result, $mode);
-        }
-
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result;
-        if (!is_resource($resource)) {
-            return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                'Could not generate result resource', __FUNCTION__);
-        }
-
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            if ($db->options['field_case'] == CASE_LOWER) {
-                $case_func = 'strtolower';
-            } else {
-                $case_func = 'strtoupper';
-            }
-        } else {
-            $case_func = 'strval';
-        }
-
-        $count = @mysql_num_fields($resource);
-        $res   = array();
-        if ($mode) {
-            $res['num_fields'] = $count;
-        }
-
-        $db->loadModule('Datatype', null, true);
-        for ($i = 0; $i < $count; $i++) {
-            $res[$i] = array(
-                'table' => $case_func(@mysql_field_table($resource, $i)),
-                'name'  => $case_func(@mysql_field_name($resource, $i)),
-                'type'  => @mysql_field_type($resource, $i),
-                'length'   => @mysql_field_len($resource, $i),
-                'flags' => @mysql_field_flags($resource, $i),
-            );
-            if ($res[$i]['type'] == 'string') {
-                $res[$i]['type'] = 'char';
-            } elseif ($res[$i]['type'] == 'unknown') {
-                $res[$i]['type'] = 'decimal';
-            }
-            $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]);
-            if (PEAR::isError($mdb2type_info)) {
-               return $mdb2type_info;
-            }
-            $res[$i]['mdb2type'] = $mdb2type_info[0][0];
-            if ($mode & MDB2_TABLEINFO_ORDER) {
-                $res['order'][$res[$i]['name']] = $i;
-            }
-            if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
-                $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
-            }
-        }
-
-        return $res;
-    }
-}
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: mysql.php 295587 2010-02-28 17:16:38Z quipo $\r
+//\r
+\r
+require_once 'MDB2/Driver/Reverse/Common.php';\r
+\r
+/**\r
+ * MDB2 MySQL driver for the schema reverse engineering module\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ * @author  Lorenzo Alberton <l.alberton@quipo.it>\r
+ */\r
+class MDB2_Driver_Reverse_mysql extends MDB2_Driver_Reverse_Common\r
+{\r
+    // {{{ getTableFieldDefinition()\r
+\r
+    /**\r
+     * Get the structure of a field into an array\r
+     *\r
+     * @param string $table_name name of table that should be used in method\r
+     * @param string $field_name name of field that should be used in method\r
+     * @return mixed data array on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function getTableFieldDefinition($table_name, $field_name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $result = $db->loadModule('Datatype', null, true);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+\r
+        list($schema, $table) = $this->splitTableSchema($table_name);\r
+\r
+        $table = $db->quoteIdentifier($table, true);\r
+        $query = "SHOW FULL COLUMNS FROM $table LIKE ".$db->quote($field_name);\r
+        $columns = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);\r
+        if (PEAR::isError($columns)) {\r
+            return $columns;\r
+        }\r
+        foreach ($columns as $column) {\r
+            $column = array_change_key_case($column, CASE_LOWER);\r
+            $column['name'] = $column['field'];\r
+            unset($column['field']);\r
+            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+                if ($db->options['field_case'] == CASE_LOWER) {\r
+                    $column['name'] = strtolower($column['name']);\r
+                } else {\r
+                    $column['name'] = strtoupper($column['name']);\r
+                }\r
+            } else {\r
+                $column = array_change_key_case($column, $db->options['field_case']);\r
+            }\r
+            if ($field_name == $column['name']) {\r
+                $mapped_datatype = $db->datatype->mapNativeDatatype($column);\r
+                if (PEAR::isError($mapped_datatype)) {\r
+                    return $mapped_datatype;\r
+                }\r
+                list($types, $length, $unsigned, $fixed) = $mapped_datatype;\r
+                $notnull = false;\r
+                if (empty($column['null']) || $column['null'] !== 'YES') {\r
+                    $notnull = true;\r
+                }\r
+                $default = false;\r
+                if (array_key_exists('default', $column)) {\r
+                    $default = $column['default'];\r
+                    if ((null === $default) && $notnull) {\r
+                        $default = '';\r
+                    }\r
+                }\r
+                $definition[0] = array(\r
+                    'notnull' => $notnull,\r
+                    'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type'])\r
+                );\r
+                $autoincrement = false;\r
+                if (!empty($column['extra'])) {\r
+                    if ($column['extra'] == 'auto_increment') {\r
+                        $autoincrement = true;\r
+                    } else {\r
+                        $definition[0]['extra'] = $column['extra'];\r
+                    }\r
+                }\r
+                $collate = null;\r
+                if (!empty($column['collation'])) {\r
+                    $collate = $column['collation'];\r
+                    $charset = preg_replace('/(.+?)(_.+)?/', '$1', $collate);\r
+                }\r
+\r
+                if (null !== $length) {\r
+                    $definition[0]['length'] = $length;\r
+                }\r
+                if (null !== $unsigned) {\r
+                    $definition[0]['unsigned'] = $unsigned;\r
+                }\r
+                if (null !== $fixed) {\r
+                    $definition[0]['fixed'] = $fixed;\r
+                }\r
+                if ($default !== false) {\r
+                    $definition[0]['default'] = $default;\r
+                }\r
+                if ($autoincrement !== false) {\r
+                    $definition[0]['autoincrement'] = $autoincrement;\r
+                }\r
+                if (null !== $collate) {\r
+                    $definition[0]['collate'] = $collate;\r
+                    $definition[0]['charset'] = $charset;\r
+                }\r
+                foreach ($types as $key => $type) {\r
+                    $definition[$key] = $definition[0];\r
+                    if ($type == 'clob' || $type == 'blob') {\r
+                        unset($definition[$key]['default']);\r
+                    } elseif ($type == 'timestamp' && $notnull && empty($definition[$key]['default'])) {\r
+                        $definition[$key]['default'] = '0000-00-00 00:00:00';\r
+                    }\r
+                    $definition[$key]['type'] = $type;\r
+                    $definition[$key]['mdb2type'] = $type;\r
+                }\r
+                return $definition;\r
+            }\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+            'it was not specified an existing table column', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getTableIndexDefinition()\r
+\r
+    /**\r
+     * Get the structure of an index into an array\r
+     *\r
+     * @param string $table_name name of table that should be used in method\r
+     * @param string $index_name name of index that should be used in method\r
+     * @return mixed data array on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function getTableIndexDefinition($table_name, $index_name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        list($schema, $table) = $this->splitTableSchema($table_name);\r
+\r
+        $table = $db->quoteIdentifier($table, true);\r
+        $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */";\r
+        $index_name_mdb2 = $db->getIndexName($index_name);\r
+        $result = $db->queryRow(sprintf($query, $db->quote($index_name_mdb2)));\r
+        if (!PEAR::isError($result) && (null !== $result)) {\r
+            // apply 'idxname_format' only if the query succeeded, otherwise\r
+            // fallback to the given $index_name, without transformation\r
+            $index_name = $index_name_mdb2;\r
+        }\r
+        $result = $db->query(sprintf($query, $db->quote($index_name)));\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        $colpos = 1;\r
+        $definition = array();\r
+        while (is_array($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC))) {\r
+            $row = array_change_key_case($row, CASE_LOWER);\r
+            $key_name = $row['key_name'];\r
+            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+                if ($db->options['field_case'] == CASE_LOWER) {\r
+                    $key_name = strtolower($key_name);\r
+                } else {\r
+                    $key_name = strtoupper($key_name);\r
+                }\r
+            }\r
+            if ($index_name == $key_name) {\r
+                if (!$row['non_unique']) {\r
+                    return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                        $index_name . ' is not an existing table index', __FUNCTION__);\r
+                }\r
+                $column_name = $row['column_name'];\r
+                if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+                    if ($db->options['field_case'] == CASE_LOWER) {\r
+                        $column_name = strtolower($column_name);\r
+                    } else {\r
+                        $column_name = strtoupper($column_name);\r
+                    }\r
+                }\r
+                $definition['fields'][$column_name] = array(\r
+                    'position' => $colpos++\r
+                );\r
+                if (!empty($row['collation'])) {\r
+                    $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A'\r
+                        ? 'ascending' : 'descending');\r
+                }\r
+            }\r
+        }\r
+        $result->free();\r
+        if (empty($definition['fields'])) {\r
+            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                $index_name . ' is not an existing table index', __FUNCTION__);\r
+        }\r
+        return $definition;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getTableConstraintDefinition()\r
+\r
+    /**\r
+     * Get the structure of a constraint into an array\r
+     *\r
+     * @param string $table_name      name of table that should be used in method\r
+     * @param string $constraint_name name of constraint that should be used in method\r
+     * @return mixed data array on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function getTableConstraintDefinition($table_name, $constraint_name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        list($schema, $table) = $this->splitTableSchema($table_name);\r
+        $constraint_name_original = $constraint_name;\r
+\r
+        $table = $db->quoteIdentifier($table, true);\r
+        $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */";\r
+        if (strtolower($constraint_name) != 'primary') {\r
+            $constraint_name_mdb2 = $db->getIndexName($constraint_name);\r
+            $result = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2)));\r
+            if (!PEAR::isError($result) && (null !== $result)) {\r
+                // apply 'idxname_format' only if the query succeeded, otherwise\r
+                // fallback to the given $index_name, without transformation\r
+                $constraint_name = $constraint_name_mdb2;\r
+            }\r
+        }\r
+        $result = $db->query(sprintf($query, $db->quote($constraint_name)));\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        $colpos = 1;\r
+        //default values, eventually overridden\r
+        $definition = array(\r
+            'primary' => false,\r
+            'unique'  => false,\r
+            'foreign' => false,\r
+            'check'   => false,\r
+            'fields'  => array(),\r
+            'references' => array(\r
+                'table'  => '',\r
+                'fields' => array(),\r
+            ),\r
+            'onupdate'  => '',\r
+            'ondelete'  => '',\r
+            'match'     => '',\r
+            'deferrable'        => false,\r
+            'initiallydeferred' => false,\r
+        );\r
+        while (is_array($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC))) {\r
+            $row = array_change_key_case($row, CASE_LOWER);\r
+            $key_name = $row['key_name'];\r
+            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+                if ($db->options['field_case'] == CASE_LOWER) {\r
+                    $key_name = strtolower($key_name);\r
+                } else {\r
+                    $key_name = strtoupper($key_name);\r
+                }\r
+            }\r
+            if ($constraint_name == $key_name) {\r
+                if ($row['non_unique']) {\r
+                    //FOREIGN KEY?\r
+                    return $this->_getTableFKConstraintDefinition($table, $constraint_name_original, $definition);\r
+                }\r
+                if ($row['key_name'] == 'PRIMARY') {\r
+                    $definition['primary'] = true;\r
+                } elseif (!$row['non_unique']) {\r
+                    $definition['unique'] = true;\r
+                }\r
+                $column_name = $row['column_name'];\r
+                if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+                    if ($db->options['field_case'] == CASE_LOWER) {\r
+                        $column_name = strtolower($column_name);\r
+                    } else {\r
+                        $column_name = strtoupper($column_name);\r
+                    }\r
+                }\r
+                $definition['fields'][$column_name] = array(\r
+                    'position' => $colpos++\r
+                );\r
+                if (!empty($row['collation'])) {\r
+                    $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A'\r
+                        ? 'ascending' : 'descending');\r
+                }\r
+            }\r
+        }\r
+        $result->free();\r
+        if (empty($definition['fields'])) {\r
+            return $this->_getTableFKConstraintDefinition($table, $constraint_name_original, $definition);\r
+        }\r
+        return $definition;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getTableFKConstraintDefinition()\r
+    \r
+    /**\r
+     * Get the FK definition from the CREATE TABLE statement\r
+     *\r
+     * @param string $table           table name\r
+     * @param string $constraint_name constraint name\r
+     * @param array  $definition      default values for constraint definition\r
+     *\r
+     * @return array|PEAR_Error\r
+     * @access private\r
+     */\r
+    function _getTableFKConstraintDefinition($table, $constraint_name, $definition)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+        //Use INFORMATION_SCHEMA instead?\r
+        //SELECT *\r
+        //  FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS\r
+        // WHERE CONSTRAINT_SCHEMA = '$dbname'\r
+        //   AND TABLE_NAME = '$table'\r
+        //   AND CONSTRAINT_NAME = '$constraint_name';\r
+        $query = 'SHOW CREATE TABLE '. $db->escape($table);\r
+        $constraint = $db->queryOne($query, 'text', 1);\r
+        if (!PEAR::isError($constraint) && !empty($constraint)) {\r
+            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+                if ($db->options['field_case'] == CASE_LOWER) {\r
+                    $constraint = strtolower($constraint);\r
+                } else {\r
+                    $constraint = strtoupper($constraint);\r
+                }\r
+            }\r
+            $constraint_name_original = $constraint_name;\r
+            $constraint_name = $db->getIndexName($constraint_name);\r
+            $pattern = '/\bCONSTRAINT\s+'.$constraint_name.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^\s]+) \(([^\)]+)\)(?: ON DELETE ([^\s]+))?(?: ON UPDATE ([^\s]+))?/i';\r
+            if (!preg_match($pattern, str_replace('`', '', $constraint), $matches)) {\r
+                //fallback to original constraint name\r
+                $pattern = '/\bCONSTRAINT\s+'.$constraint_name_original.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^\s]+) \(([^\)]+)\)(?: ON DELETE ([^\s]+))?(?: ON UPDATE ([^\s]+))?/i';\r
+            }\r
+            if (preg_match($pattern, str_replace('`', '', $constraint), $matches)) {\r
+                $definition['foreign'] = true;\r
+                $column_names = explode(',', $matches[1]);\r
+                $referenced_cols = explode(',', $matches[3]);\r
+                $definition['references'] = array(\r
+                    'table'  => $matches[2],\r
+                    'fields' => array(),\r
+                );\r
+                $colpos = 1;\r
+                foreach ($column_names as $column_name) {\r
+                    $definition['fields'][trim($column_name)] = array(\r
+                        'position' => $colpos++\r
+                    );\r
+                }\r
+                $colpos = 1;\r
+                foreach ($referenced_cols as $column_name) {\r
+                    $definition['references']['fields'][trim($column_name)] = array(\r
+                        'position' => $colpos++\r
+                    );\r
+                }\r
+                $definition['ondelete'] = empty($matches[4]) ? 'RESTRICT' : strtoupper($matches[4]);\r
+                $definition['onupdate'] = empty($matches[5]) ? 'RESTRICT' : strtoupper($matches[5]);\r
+                $definition['match']    = 'SIMPLE';\r
+                return $definition;\r
+            }\r
+        }\r
+        return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                $constraint_name . ' is not an existing table constraint', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getTriggerDefinition()\r
+\r
+    /**\r
+     * Get the structure of a trigger into an array\r
+     *\r
+     * EXPERIMENTAL\r
+     *\r
+     * WARNING: this function is experimental and may change the returned value\r
+     * at any time until labelled as non-experimental\r
+     *\r
+     * @param string    $trigger    name of trigger that should be used in method\r
+     * @return mixed data array on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function getTriggerDefinition($trigger)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = 'SELECT trigger_name,\r
+                         event_object_table AS table_name,\r
+                         action_statement AS trigger_body,\r
+                         action_timing AS trigger_type,\r
+                         event_manipulation AS trigger_event\r
+                    FROM information_schema.triggers\r
+                   WHERE trigger_name = '. $db->quote($trigger, 'text');\r
+        $types = array(\r
+            'trigger_name'    => 'text',\r
+            'table_name'      => 'text',\r
+            'trigger_body'    => 'text',\r
+            'trigger_type'    => 'text',\r
+            'trigger_event'   => 'text',\r
+        );\r
+        $def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);\r
+        if (PEAR::isError($def)) {\r
+            return $def;\r
+        }\r
+        $def['trigger_comment'] = '';\r
+        $def['trigger_enabled'] = true;\r
+        return $def;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ tableInfo()\r
+\r
+    /**\r
+     * Returns information about a table or a result set\r
+     *\r
+     * @param object|string  $result  MDB2_result object from a query or a\r
+     *                                 string containing the name of a table.\r
+     *                                 While this also accepts a query result\r
+     *                                 resource identifier, this behavior is\r
+     *                                 deprecated.\r
+     * @param int            $mode    a valid tableInfo mode\r
+     *\r
+     * @return array  an associative array with the information requested.\r
+     *                 A MDB2_Error object on failure.\r
+     *\r
+     * @see MDB2_Driver_Common::setOption()\r
+     */\r
+    function tableInfo($result, $mode = null)\r
+    {\r
+        if (is_string($result)) {\r
+           return parent::tableInfo($result, $mode);\r
+        }\r
+\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result;\r
+        if (!is_resource($resource)) {\r
+            return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,\r
+                'Could not generate result resource', __FUNCTION__);\r
+        }\r
+\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            if ($db->options['field_case'] == CASE_LOWER) {\r
+                $case_func = 'strtolower';\r
+            } else {\r
+                $case_func = 'strtoupper';\r
+            }\r
+        } else {\r
+            $case_func = 'strval';\r
+        }\r
+\r
+        $count = @mysql_num_fields($resource);\r
+        $res   = array();\r
+        if ($mode) {\r
+            $res['num_fields'] = $count;\r
+        }\r
+\r
+        $db->loadModule('Datatype', null, true);\r
+        for ($i = 0; $i < $count; $i++) {\r
+            $res[$i] = array(\r
+                'table'  => $case_func(@mysql_field_table($resource, $i)),\r
+                'name'   => $case_func(@mysql_field_name($resource, $i)),\r
+                'type'   => @mysql_field_type($resource, $i),\r
+                'length' => @mysql_field_len($resource, $i),\r
+                'flags'  => @mysql_field_flags($resource, $i),\r
+            );\r
+            if ($res[$i]['type'] == 'string') {\r
+                $res[$i]['type'] = 'char';\r
+            } elseif ($res[$i]['type'] == 'unknown') {\r
+                $res[$i]['type'] = 'decimal';\r
+            }\r
+            $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]);\r
+            if (PEAR::isError($mdb2type_info)) {\r
+               return $mdb2type_info;\r
+            }\r
+            $res[$i]['mdb2type'] = $mdb2type_info[0][0];\r
+            if ($mode & MDB2_TABLEINFO_ORDER) {\r
+                $res['order'][$res[$i]['name']] = $i;\r
+            }\r
+            if ($mode & MDB2_TABLEINFO_ORDERTABLE) {\r
+                $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;\r
+            }\r
+        }\r
+\r
+        return $res;\r
+    }\r
+}\r
 ?>
\ No newline at end of file
index 8669c2b919b176b0c2ab465ad436e2cbccf178e1..45aa5a1503bc99ce9f6c96f948bc08589679ef0a 100644 (file)
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Authors: Paul Cooper <pgc@ucecom.com>                                |
-// |          Lorenzo Alberton <l.alberton@quipo.it>                      |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.75 2008/08/22 16:36:20 quipo Exp $
-
-require_once('MDB2/Driver/Reverse/Common.php');
-
-/**
- * MDB2 PostGreSQL driver for the schema reverse engineering module
- *
- * @package  MDB2
- * @category Database
- * @author   Paul Cooper <pgc@ucecom.com>
- * @author   Lorenzo Alberton <l.alberton@quipo.it>
- */
-class MDB2_Driver_Reverse_pgsql extends MDB2_Driver_Reverse_Common
-{
-    // {{{ getTableFieldDefinition()
-
-    /**
-     * Get the structure of a field into an array
-     *
-     * @param string $table_name name of table that should be used in method
-     * @param string $field_name name of field that should be used in method
-     * @return mixed data array on success, a MDB2 error on failure
-     * @access public
-     */
-    function getTableFieldDefinition($table_name, $field_name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $result = $db->loadModule('Datatype', null, true);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-
-        list($schema, $table) = $this->splitTableSchema($table_name);
-
-        $query = "SELECT a.attname AS name,
-                         t.typname AS type,
-                         CASE a.attlen
-                           WHEN -1 THEN
-                                CASE t.typname
-                                  WHEN 'numeric' THEN (a.atttypmod / 65536)
-                                  WHEN 'decimal' THEN (a.atttypmod / 65536)
-                                  WHEN 'money'   THEN (a.atttypmod / 65536)
-                                  ELSE CASE a.atttypmod
-                                 WHEN -1 THEN NULL
-                                    ELSE a.atttypmod - 4
-                                  END
-                             END
-                              ELSE a.attlen
-                         END AS length,
-                            CASE t.typname
-                              WHEN 'numeric' THEN (a.atttypmod % 65536) - 4
-                              WHEN 'decimal' THEN (a.atttypmod % 65536) - 4
-                              WHEN 'money'   THEN (a.atttypmod % 65536) - 4
-                              ELSE 0
-                         END AS scale,
-                         a.attnotnull,
-                         a.atttypmod,
-                         a.atthasdef,
-                         (SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)
-                            FROM pg_attrdef d
-                           WHERE d.adrelid = a.attrelid
-                             AND d.adnum = a.attnum
-                             AND a.atthasdef
-                         ) as default
-                    FROM pg_attribute a,
-                         pg_class c,
-                         pg_type t
-                   WHERE c.relname = ".$db->quote($table, 'text')."
-                     AND a.atttypid = t.oid
-                     AND c.oid = a.attrelid
-                     AND NOT a.attisdropped
-                     AND a.attnum > 0
-                     AND a.attname = ".$db->quote($field_name, 'text')."
-                ORDER BY a.attnum";
-        $column = $db->queryRow($query, null, MDB2_FETCHMODE_ASSOC);
-        if (PEAR::isError($column)) {
-            return $column;
-        }
-
-        if (empty($column)) {
-            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                'it was not specified an existing table column', __FUNCTION__);
-        }
-
-        $column = array_change_key_case($column, CASE_LOWER);
-        $mapped_datatype = $db->datatype->mapNativeDatatype($column);
-        if (PEAR::isError($mapped_datatype)) {
-            return $mapped_datatype;
-        }
-        list($types, $length, $unsigned, $fixed) = $mapped_datatype;
-        $notnull = false;
-        if (!empty($column['attnotnull']) && $column['attnotnull'] == 't') {
-            $notnull = true;
-        }
-        $default = null;
-        if ($column['atthasdef'] === 't'
-            && !preg_match("/nextval\('([^']+)'/", $column['default'])
-        ) {
-            $pattern = '/^\'(.*)\'::[\w ]+$/i';
-            $default = $column['default'];#substr($column['adsrc'], 1, -1);
-            if (is_null($default) && $notnull) {
-                $default = '';
-            } elseif (!empty($default) && preg_match($pattern, $default)) {
-                //remove data type cast
-                $default = preg_replace ($pattern, '\\1', $default);
-            }
-        }
-        $autoincrement = false;
-        if (preg_match("/nextval\('([^']+)'/", $column['default'], $nextvals)) {
-            $autoincrement = true;
-        }
-        $definition[0] = array('notnull' => $notnull, 'nativetype' => $column['type']);
-        if (!is_null($length)) {
-            $definition[0]['length'] = $length;
-        }
-        if (!is_null($unsigned)) {
-            $definition[0]['unsigned'] = $unsigned;
-        }
-        if (!is_null($fixed)) {
-            $definition[0]['fixed'] = $fixed;
-        }
-        if ($default !== false) {
-            $definition[0]['default'] = $default;
-        }
-        if ($autoincrement !== false) {
-            $definition[0]['autoincrement'] = $autoincrement;
-        }
-        foreach ($types as $key => $type) {
-            $definition[$key] = $definition[0];
-            if ($type == 'clob' || $type == 'blob') {
-                unset($definition[$key]['default']);
-            }
-            $definition[$key]['type'] = $type;
-            $definition[$key]['mdb2type'] = $type;
-        }
-        return $definition;
-    }
-
-    // }}}
-    // {{{ getTableIndexDefinition()
-
-    /**
-     * Get the structure of an index into an array
-     *
-     * @param string $table_name name of table that should be used in method
-     * @param string $index_name name of index that should be used in method
-     * @return mixed data array on success, a MDB2 error on failure
-     * @access public
-     */
-    function getTableIndexDefinition($table_name, $index_name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-        
-        list($schema, $table) = $this->splitTableSchema($table_name);
-
-        $query = 'SELECT relname, indkey FROM pg_index, pg_class';
-        $query.= ' WHERE pg_class.oid = pg_index.indexrelid';
-        $query.= " AND indisunique != 't' AND indisprimary != 't'";
-        $query.= ' AND pg_class.relname = %s';
-        $index_name_mdb2 = $db->getIndexName($index_name);
-        $row = $db->queryRow(sprintf($query, $db->quote($index_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
-        if (PEAR::isError($row) || empty($row)) {
-            // fallback to the given $index_name, without transformation
-            $row = $db->queryRow(sprintf($query, $db->quote($index_name, 'text')), null, MDB2_FETCHMODE_ASSOC);
-        }
-        if (PEAR::isError($row)) {
-            return $row;
-        }
-
-        if (empty($row)) {
-            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                'it was not specified an existing table index', __FUNCTION__);
-        }
-
-        $row = array_change_key_case($row, CASE_LOWER);
-
-        $db->loadModule('Manager', null, true);
-        $columns = $db->manager->listTableFields($table_name);
-
-        $definition = array();
-
-        $index_column_numbers = explode(' ', $row['indkey']);
-
-        $colpos = 1;
-        foreach ($index_column_numbers as $number) {
-            $definition['fields'][$columns[($number - 1)]] = array(
-                'position' => $colpos++,
-                'sorting' => 'ascending',
-            );
-        }
-        return $definition;
-    }
-
-    // }}}
-    // {{{ getTableConstraintDefinition()
-
-    /**
-     * Get the structure of a constraint into an array
-     *
-     * @param string $table_name      name of table that should be used in method
-     * @param string $constraint_name name of constraint that should be used in method
-     * @return mixed data array on success, a MDB2 error on failure
-     * @access public
-     */
-    function getTableConstraintDefinition($table_name, $constraint_name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-        
-        list($schema, $table) = $this->splitTableSchema($table_name);
-
-        $query = "SELECT c.oid,
-                         c.conname AS constraint_name,
-                         CASE WHEN c.contype = 'c' THEN 1 ELSE 0 END AS \"check\",
-                         CASE WHEN c.contype = 'f' THEN 1 ELSE 0 END AS \"foreign\",
-                         CASE WHEN c.contype = 'p' THEN 1 ELSE 0 END AS \"primary\",
-                         CASE WHEN c.contype = 'u' THEN 1 ELSE 0 END AS \"unique\",
-                         CASE WHEN c.condeferrable = 'f' THEN 0 ELSE 1 END AS deferrable,
-                         CASE WHEN c.condeferred = 'f' THEN 0 ELSE 1 END AS initiallydeferred,
-                         --array_to_string(c.conkey, ' ') AS constraint_key,
-                         t.relname AS table_name,
-                         t2.relname AS references_table,
-                         CASE confupdtype
-                           WHEN 'a' THEN 'NO ACTION'
-                           WHEN 'r' THEN 'RESTRICT'
-                           WHEN 'c' THEN 'CASCADE'
-                           WHEN 'n' THEN 'SET NULL'
-                           WHEN 'd' THEN 'SET DEFAULT'
-                         END AS onupdate,
-                         CASE confdeltype
-                           WHEN 'a' THEN 'NO ACTION'
-                           WHEN 'r' THEN 'RESTRICT'
-                           WHEN 'c' THEN 'CASCADE'
-                           WHEN 'n' THEN 'SET NULL'
-                           WHEN 'd' THEN 'SET DEFAULT'
-                         END AS ondelete,
-                         CASE confmatchtype
-                           WHEN 'u' THEN 'UNSPECIFIED'
-                           WHEN 'f' THEN 'FULL'
-                           WHEN 'p' THEN 'PARTIAL'
-                         END AS match,
-                         --array_to_string(c.confkey, ' ') AS fk_constraint_key,
-                         consrc
-                    FROM pg_constraint c
-               LEFT JOIN pg_class t  ON c.conrelid  = t.oid
-               LEFT JOIN pg_class t2 ON c.confrelid = t2.oid
-                   WHERE c.conname = %s
-                     AND t.relname = " . $db->quote($table, 'text');
-        $constraint_name_mdb2 = $db->getIndexName($constraint_name);
-        $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
-        if (PEAR::isError($row) || empty($row)) {
-            // fallback to the given $index_name, without transformation
-            $constraint_name_mdb2 = $constraint_name;
-            $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
-        }
-        if (PEAR::isError($row)) {
-            return $row;
-        }
-        $uniqueIndex = false;
-        if (empty($row)) {
-            // We might be looking for a UNIQUE index that was not created
-            // as a constraint but should be treated as such.
-            $query = 'SELECT relname AS constraint_name,
-                             indkey,
-                             0 AS "check",
-                             0 AS "foreign",
-                             0 AS "primary",
-                             1 AS "unique",
-                             0 AS deferrable,
-                             0 AS initiallydeferred,
-                             NULL AS references_table,
-                             NULL AS onupdate,
-                             NULL AS ondelete,
-                             NULL AS match
-                        FROM pg_index, pg_class
-                       WHERE pg_class.oid = pg_index.indexrelid
-                         AND indisunique = \'t\'
-                         AND pg_class.relname = %s';
-            $constraint_name_mdb2 = $db->getIndexName($constraint_name);
-            $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
-            if (PEAR::isError($row) || empty($row)) {
-                // fallback to the given $index_name, without transformation
-                $constraint_name_mdb2 = $constraint_name;
-                $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
-            }
-            if (PEAR::isError($row)) {
-                return $row;
-            }
-            if (empty($row)) {
-                return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                    $constraint_name . ' is not an existing table constraint', __FUNCTION__);
-            }
-            $uniqueIndex = true;
-        }
-
-        $row = array_change_key_case($row, CASE_LOWER);
-
-        $definition = array(
-            'primary' => (boolean)$row['primary'],
-            'unique'  => (boolean)$row['unique'],
-            'foreign' => (boolean)$row['foreign'],
-            'check'   => (boolean)$row['check'],
-            'fields'  => array(),
-            'references' => array(
-                'table'  => $row['references_table'],
-                'fields' => array(),
-            ),
-            'deferrable' => (boolean)$row['deferrable'],
-            'initiallydeferred' => (boolean)$row['initiallydeferred'],
-            'onupdate' => $row['onupdate'],
-            'ondelete' => $row['ondelete'],
-            'match'    => $row['match'],
-        );
-
-        if ($uniqueIndex) {
-            $db->loadModule('Manager', null, true);
-            $columns = $db->manager->listTableFields($table_name);
-            $index_column_numbers = explode(' ', $row['indkey']);
-            $colpos = 1;
-            foreach ($index_column_numbers as $number) {
-                $definition['fields'][$columns[($number - 1)]] = array(
-                    'position' => $colpos++,
-                    'sorting'  => 'ascending',
-                );
-            }
-            return $definition;
-        }
-
-        $query = 'SELECT a.attname
-                    FROM pg_constraint c
-               LEFT JOIN pg_class t  ON c.conrelid  = t.oid
-               LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.conkey)
-                   WHERE c.conname = %s
-                     AND t.relname = ' . $db->quote($table, 'text');
-        $fields = $db->queryCol(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null);
-        if (PEAR::isError($fields)) {
-            return $fields;
-        }
-        $colpos = 1;
-        foreach ($fields as $field) {
-            $definition['fields'][$field] = array(
-                'position' => $colpos++,
-                'sorting' => 'ascending',
-            );
-        }
-        
-        if ($definition['foreign']) {
-            $query = 'SELECT a.attname
-                        FROM pg_constraint c
-                   LEFT JOIN pg_class t  ON c.confrelid  = t.oid
-                   LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.confkey)
-                       WHERE c.conname = %s
-                         AND t.relname = ' . $db->quote($definition['references']['table'], 'text');
-            $foreign_fields = $db->queryCol(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null);
-            if (PEAR::isError($foreign_fields)) {
-                return $foreign_fields;
-            }
-            $colpos = 1;
-            foreach ($foreign_fields as $foreign_field) {
-                $definition['references']['fields'][$foreign_field] = array(
-                    'position' => $colpos++,
-                );
-            }
-        }
-        
-        if ($definition['check']) {
-            $check_def = $db->queryOne("SELECT pg_get_constraintdef(" . $row['oid'] . ", 't')");
-            // ...
-        }
-        return $definition;
-    }
-
-    // }}}
-    // {{{ getTriggerDefinition()
-
-    /**
-     * Get the structure of a trigger into an array
-     *
-     * EXPERIMENTAL
-     *
-     * WARNING: this function is experimental and may change the returned value
-     * at any time until labelled as non-experimental
-     *
-     * @param string $trigger name of trigger that should be used in method
-     * @return mixed data array on success, a MDB2 error on failure
-     * @access public
-     *
-     * @TODO: add support for plsql functions and functions with args
-     */
-    function getTriggerDefinition($trigger)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = "SELECT trg.tgname AS trigger_name,
-                         tbl.relname AS table_name,
-                         CASE
-                            WHEN p.proname IS NOT NULL THEN 'EXECUTE PROCEDURE ' || p.proname || '();'
-                            ELSE ''
-                         END AS trigger_body,
-                         CASE trg.tgtype & cast(2 as int2)
-                            WHEN 0 THEN 'AFTER'
-                            ELSE 'BEFORE'
-                         END AS trigger_type,
-                         CASE trg.tgtype & cast(28 as int2)
-                            WHEN 16 THEN 'UPDATE'
-                            WHEN 8 THEN 'DELETE'
-                            WHEN 4 THEN 'INSERT'
-                            WHEN 20 THEN 'INSERT, UPDATE'
-                            WHEN 28 THEN 'INSERT, UPDATE, DELETE'
-                            WHEN 24 THEN 'UPDATE, DELETE'
-                            WHEN 12 THEN 'INSERT, DELETE'
-                         END AS trigger_event,
-                         CASE trg.tgenabled
-                            WHEN 'O' THEN 't'
-                            ELSE trg.tgenabled
-                         END AS trigger_enabled,
-                         obj_description(trg.oid, 'pg_trigger') AS trigger_comment
-                    FROM pg_trigger trg,
-                         pg_class tbl,
-                         pg_proc p
-                   WHERE trg.tgrelid = tbl.oid
-                     AND trg.tgfoid = p.oid
-                     AND trg.tgname = ". $db->quote($trigger, 'text');
-        $types = array(
-            'trigger_name'    => 'text',
-            'table_name'      => 'text',
-            'trigger_body'    => 'text',
-            'trigger_type'    => 'text',
-            'trigger_event'   => 'text',
-            'trigger_comment' => 'text',
-            'trigger_enabled' => 'boolean',
-        );
-        return $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
-    }
-    
-    // }}}
-    // {{{ tableInfo()
-
-    /**
-     * Returns information about a table or a result set
-     *
-     * NOTE: only supports 'table' and 'flags' if <var>$result</var>
-     * is a table name.
-     *
-     * @param object|string  $result  MDB2_result object from a query or a
-     *                                 string containing the name of a table.
-     *                                 While this also accepts a query result
-     *                                 resource identifier, this behavior is
-     *                                 deprecated.
-     * @param int            $mode    a valid tableInfo mode
-     *
-     * @return array  an associative array with the information requested.
-     *                 A MDB2_Error object on failure.
-     *
-     * @see MDB2_Driver_Common::tableInfo()
-     */
-    function tableInfo($result, $mode = null)
-    {
-        if (is_string($result)) {
-           return parent::tableInfo($result, $mode);
-        }
-
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result;
-        if (!is_resource($resource)) {
-            return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                'Could not generate result resource', __FUNCTION__);
-        }
-
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            if ($db->options['field_case'] == CASE_LOWER) {
-                $case_func = 'strtolower';
-            } else {
-                $case_func = 'strtoupper';
-            }
-        } else {
-            $case_func = 'strval';
-        }
-
-        $count = @pg_num_fields($resource);
-        $res   = array();
-
-        if ($mode) {
-            $res['num_fields'] = $count;
-        }
-
-        $db->loadModule('Datatype', null, true);
-        for ($i = 0; $i < $count; $i++) {
-            $res[$i] = array(
-                'table' => function_exists('pg_field_table') ? @pg_field_table($resource, $i) : '',
-                'name'  => $case_func(@pg_field_name($resource, $i)),
-                'type'  => @pg_field_type($resource, $i),
-                'length' => @pg_field_size($resource, $i),
-                'flags' => '',
-            );
-            $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]);
-            if (PEAR::isError($mdb2type_info)) {
-               return $mdb2type_info;
-            }
-            $res[$i]['mdb2type'] = $mdb2type_info[0][0];
-            if ($mode & MDB2_TABLEINFO_ORDER) {
-                $res['order'][$res[$i]['name']] = $i;
-            }
-            if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
-                $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
-            }
-        }
-
-        return $res;
-    }
-}
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Authors: Paul Cooper <pgc@ucecom.com>                                |\r
+// |          Lorenzo Alberton <l.alberton@quipo.it>                      |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: pgsql.php 295587 2010-02-28 17:16:38Z quipo $\r
+\r
+require_once 'MDB2/Driver/Reverse/Common.php';\r
+\r
+/**\r
+ * MDB2 PostGreSQL driver for the schema reverse engineering module\r
+ *\r
+ * @package  MDB2\r
+ * @category Database\r
+ * @author   Paul Cooper <pgc@ucecom.com>\r
+ * @author   Lorenzo Alberton <l.alberton@quipo.it>\r
+ */\r
+class MDB2_Driver_Reverse_pgsql extends MDB2_Driver_Reverse_Common\r
+{\r
+    // {{{ getTableFieldDefinition()\r
+\r
+    /**\r
+     * Get the structure of a field into an array\r
+     *\r
+     * @param string $table_name name of table that should be used in method\r
+     * @param string $field_name name of field that should be used in method\r
+     * @return mixed data array on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function getTableFieldDefinition($table_name, $field_name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $result = $db->loadModule('Datatype', null, true);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+\r
+        list($schema, $table) = $this->splitTableSchema($table_name);\r
+\r
+        $query = "SELECT a.attname AS name,\r
+                         t.typname AS type,\r
+                         CASE a.attlen\r
+                           WHEN -1 THEN\r
+                                CASE t.typname\r
+                                  WHEN 'numeric' THEN (a.atttypmod / 65536)\r
+                                  WHEN 'decimal' THEN (a.atttypmod / 65536)\r
+                                  WHEN 'money'   THEN (a.atttypmod / 65536)\r
+                                  ELSE CASE a.atttypmod\r
+                                 WHEN -1 THEN NULL\r
+                                    ELSE a.atttypmod - 4\r
+                                  END\r
+                             END\r
+                              ELSE a.attlen\r
+                         END AS length,\r
+                            CASE t.typname\r
+                              WHEN 'numeric' THEN (a.atttypmod % 65536) - 4\r
+                              WHEN 'decimal' THEN (a.atttypmod % 65536) - 4\r
+                              WHEN 'money'   THEN (a.atttypmod % 65536) - 4\r
+                              ELSE 0\r
+                         END AS scale,\r
+                         a.attnotnull,\r
+                         a.atttypmod,\r
+                         a.atthasdef,\r
+                         (SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)\r
+                            FROM pg_attrdef d\r
+                           WHERE d.adrelid = a.attrelid\r
+                             AND d.adnum = a.attnum\r
+                             AND a.atthasdef\r
+                         ) as default\r
+                    FROM pg_attribute a,\r
+                         pg_class c,\r
+                         pg_type t\r
+                   WHERE c.relname = ".$db->quote($table, 'text')."\r
+                     AND a.atttypid = t.oid\r
+                     AND c.oid = a.attrelid\r
+                     AND NOT a.attisdropped\r
+                     AND a.attnum > 0\r
+                     AND a.attname = ".$db->quote($field_name, 'text')."\r
+                ORDER BY a.attnum";\r
+        $column = $db->queryRow($query, null, MDB2_FETCHMODE_ASSOC);\r
+        if (PEAR::isError($column)) {\r
+            return $column;\r
+        }\r
+\r
+        if (empty($column)) {\r
+            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                'it was not specified an existing table column', __FUNCTION__);\r
+        }\r
+\r
+        $column = array_change_key_case($column, CASE_LOWER);\r
+        $mapped_datatype = $db->datatype->mapNativeDatatype($column);\r
+        if (PEAR::isError($mapped_datatype)) {\r
+            return $mapped_datatype;\r
+        }\r
+        list($types, $length, $unsigned, $fixed) = $mapped_datatype;\r
+        $notnull = false;\r
+        if (!empty($column['attnotnull']) && $column['attnotnull'] == 't') {\r
+            $notnull = true;\r
+        }\r
+        $default = null;\r
+        if ($column['atthasdef'] === 't'\r
+            && strpos($column['default'], 'NULL') !== 0\r
+            && !preg_match("/nextval\('([^']+)'/", $column['default'])\r
+        ) {\r
+            $pattern = '/^\'(.*)\'::[\w ]+$/i';\r
+            $default = $column['default'];#substr($column['adsrc'], 1, -1);\r
+            if ((null === $default) && $notnull) {\r
+                $default = '';\r
+            } elseif (!empty($default) && preg_match($pattern, $default)) {\r
+                //remove data type cast\r
+                $default = preg_replace ($pattern, '\\1', $default);\r
+            }\r
+        }\r
+        $autoincrement = false;\r
+        if (preg_match("/nextval\('([^']+)'/", $column['default'], $nextvals)) {\r
+            $autoincrement = true;\r
+        }\r
+        $definition[0] = array('notnull' => $notnull, 'nativetype' => $column['type']);\r
+        if (null !== $length) {\r
+            $definition[0]['length'] = $length;\r
+        }\r
+        if (null !== $unsigned) {\r
+            $definition[0]['unsigned'] = $unsigned;\r
+        }\r
+        if (null !== $fixed) {\r
+            $definition[0]['fixed'] = $fixed;\r
+        }\r
+        if ($default !== false) {\r
+            $definition[0]['default'] = $default;\r
+        }\r
+        if ($autoincrement !== false) {\r
+            $definition[0]['autoincrement'] = $autoincrement;\r
+        }\r
+        foreach ($types as $key => $type) {\r
+            $definition[$key] = $definition[0];\r
+            if ($type == 'clob' || $type == 'blob') {\r
+                unset($definition[$key]['default']);\r
+            }\r
+            $definition[$key]['type'] = $type;\r
+            $definition[$key]['mdb2type'] = $type;\r
+        }\r
+        return $definition;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getTableIndexDefinition()\r
+\r
+    /**\r
+     * Get the structure of an index into an array\r
+     *\r
+     * @param string $table_name name of table that should be used in method\r
+     * @param string $index_name name of index that should be used in method\r
+     * @return mixed data array on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function getTableIndexDefinition($table_name, $index_name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+        \r
+        list($schema, $table) = $this->splitTableSchema($table_name);\r
+\r
+        $query = 'SELECT relname, indkey FROM pg_index, pg_class';\r
+        $query.= ' WHERE pg_class.oid = pg_index.indexrelid';\r
+        $query.= " AND indisunique != 't' AND indisprimary != 't'";\r
+        $query.= ' AND pg_class.relname = %s';\r
+        $index_name_mdb2 = $db->getIndexName($index_name);\r
+        $row = $db->queryRow(sprintf($query, $db->quote($index_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);\r
+        if (PEAR::isError($row) || empty($row)) {\r
+            // fallback to the given $index_name, without transformation\r
+            $row = $db->queryRow(sprintf($query, $db->quote($index_name, 'text')), null, MDB2_FETCHMODE_ASSOC);\r
+        }\r
+        if (PEAR::isError($row)) {\r
+            return $row;\r
+        }\r
+\r
+        if (empty($row)) {\r
+            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                'it was not specified an existing table index', __FUNCTION__);\r
+        }\r
+\r
+        $row = array_change_key_case($row, CASE_LOWER);\r
+\r
+        $db->loadModule('Manager', null, true);\r
+        $columns = $db->manager->listTableFields($table_name);\r
+\r
+        $definition = array();\r
+\r
+        $index_column_numbers = explode(' ', $row['indkey']);\r
+\r
+        $colpos = 1;\r
+        foreach ($index_column_numbers as $number) {\r
+            $definition['fields'][$columns[($number - 1)]] = array(\r
+                'position' => $colpos++,\r
+                'sorting' => 'ascending',\r
+            );\r
+        }\r
+        return $definition;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getTableConstraintDefinition()\r
+\r
+    /**\r
+     * Get the structure of a constraint into an array\r
+     *\r
+     * @param string $table_name      name of table that should be used in method\r
+     * @param string $constraint_name name of constraint that should be used in method\r
+     * @return mixed data array on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function getTableConstraintDefinition($table_name, $constraint_name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+        \r
+        list($schema, $table) = $this->splitTableSchema($table_name);\r
+\r
+        $query = "SELECT c.oid,\r
+                         c.conname AS constraint_name,\r
+                         CASE WHEN c.contype = 'c' THEN 1 ELSE 0 END AS \"check\",\r
+                         CASE WHEN c.contype = 'f' THEN 1 ELSE 0 END AS \"foreign\",\r
+                         CASE WHEN c.contype = 'p' THEN 1 ELSE 0 END AS \"primary\",\r
+                         CASE WHEN c.contype = 'u' THEN 1 ELSE 0 END AS \"unique\",\r
+                         CASE WHEN c.condeferrable = 'f' THEN 0 ELSE 1 END AS deferrable,\r
+                         CASE WHEN c.condeferred = 'f' THEN 0 ELSE 1 END AS initiallydeferred,\r
+                         --array_to_string(c.conkey, ' ') AS constraint_key,\r
+                         t.relname AS table_name,\r
+                         t2.relname AS references_table,\r
+                         CASE confupdtype\r
+                           WHEN 'a' THEN 'NO ACTION'\r
+                           WHEN 'r' THEN 'RESTRICT'\r
+                           WHEN 'c' THEN 'CASCADE'\r
+                           WHEN 'n' THEN 'SET NULL'\r
+                           WHEN 'd' THEN 'SET DEFAULT'\r
+                         END AS onupdate,\r
+                         CASE confdeltype\r
+                           WHEN 'a' THEN 'NO ACTION'\r
+                           WHEN 'r' THEN 'RESTRICT'\r
+                           WHEN 'c' THEN 'CASCADE'\r
+                           WHEN 'n' THEN 'SET NULL'\r
+                           WHEN 'd' THEN 'SET DEFAULT'\r
+                         END AS ondelete,\r
+                         CASE confmatchtype\r
+                           WHEN 'u' THEN 'UNSPECIFIED'\r
+                           WHEN 'f' THEN 'FULL'\r
+                           WHEN 'p' THEN 'PARTIAL'\r
+                         END AS match,\r
+                         --array_to_string(c.confkey, ' ') AS fk_constraint_key,\r
+                         consrc\r
+                    FROM pg_constraint c\r
+               LEFT JOIN pg_class t  ON c.conrelid  = t.oid\r
+               LEFT JOIN pg_class t2 ON c.confrelid = t2.oid\r
+                   WHERE c.conname = %s\r
+                     AND t.relname = " . $db->quote($table, 'text');\r
+        $constraint_name_mdb2 = $db->getIndexName($constraint_name);\r
+        $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);\r
+        if (PEAR::isError($row) || empty($row)) {\r
+            // fallback to the given $index_name, without transformation\r
+            $constraint_name_mdb2 = $constraint_name;\r
+            $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);\r
+        }\r
+        if (PEAR::isError($row)) {\r
+            return $row;\r
+        }\r
+        $uniqueIndex = false;\r
+        if (empty($row)) {\r
+            // We might be looking for a UNIQUE index that was not created\r
+            // as a constraint but should be treated as such.\r
+            $query = 'SELECT relname AS constraint_name,\r
+                             indkey,\r
+                             0 AS "check",\r
+                             0 AS "foreign",\r
+                             0 AS "primary",\r
+                             1 AS "unique",\r
+                             0 AS deferrable,\r
+                             0 AS initiallydeferred,\r
+                             NULL AS references_table,\r
+                             NULL AS onupdate,\r
+                             NULL AS ondelete,\r
+                             NULL AS match\r
+                        FROM pg_index, pg_class\r
+                       WHERE pg_class.oid = pg_index.indexrelid\r
+                         AND indisunique = \'t\'\r
+                         AND pg_class.relname = %s';\r
+            $constraint_name_mdb2 = $db->getIndexName($constraint_name);\r
+            $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);\r
+            if (PEAR::isError($row) || empty($row)) {\r
+                // fallback to the given $index_name, without transformation\r
+                $constraint_name_mdb2 = $constraint_name;\r
+                $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);\r
+            }\r
+            if (PEAR::isError($row)) {\r
+                return $row;\r
+            }\r
+            if (empty($row)) {\r
+                return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                    $constraint_name . ' is not an existing table constraint', __FUNCTION__);\r
+            }\r
+            $uniqueIndex = true;\r
+        }\r
+\r
+        $row = array_change_key_case($row, CASE_LOWER);\r
+\r
+        $definition = array(\r
+            'primary' => (boolean)$row['primary'],\r
+            'unique'  => (boolean)$row['unique'],\r
+            'foreign' => (boolean)$row['foreign'],\r
+            'check'   => (boolean)$row['check'],\r
+            'fields'  => array(),\r
+            'references' => array(\r
+                'table'  => $row['references_table'],\r
+                'fields' => array(),\r
+            ),\r
+            'deferrable' => (boolean)$row['deferrable'],\r
+            'initiallydeferred' => (boolean)$row['initiallydeferred'],\r
+            'onupdate' => $row['onupdate'],\r
+            'ondelete' => $row['ondelete'],\r
+            'match'    => $row['match'],\r
+        );\r
+\r
+        if ($uniqueIndex) {\r
+            $db->loadModule('Manager', null, true);\r
+            $columns = $db->manager->listTableFields($table_name);\r
+            $index_column_numbers = explode(' ', $row['indkey']);\r
+            $colpos = 1;\r
+            foreach ($index_column_numbers as $number) {\r
+                $definition['fields'][$columns[($number - 1)]] = array(\r
+                    'position' => $colpos++,\r
+                    'sorting'  => 'ascending',\r
+                );\r
+            }\r
+            return $definition;\r
+        }\r
+\r
+        $query = 'SELECT a.attname\r
+                    FROM pg_constraint c\r
+               LEFT JOIN pg_class t  ON c.conrelid  = t.oid\r
+               LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.conkey)\r
+                   WHERE c.conname = %s\r
+                     AND t.relname = ' . $db->quote($table, 'text');\r
+        $fields = $db->queryCol(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null);\r
+        if (PEAR::isError($fields)) {\r
+            return $fields;\r
+        }\r
+        $colpos = 1;\r
+        foreach ($fields as $field) {\r
+            $definition['fields'][$field] = array(\r
+                'position' => $colpos++,\r
+                'sorting' => 'ascending',\r
+            );\r
+        }\r
+        \r
+        if ($definition['foreign']) {\r
+            $query = 'SELECT a.attname\r
+                        FROM pg_constraint c\r
+                   LEFT JOIN pg_class t  ON c.confrelid  = t.oid\r
+                   LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.confkey)\r
+                       WHERE c.conname = %s\r
+                         AND t.relname = ' . $db->quote($definition['references']['table'], 'text');\r
+            $foreign_fields = $db->queryCol(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null);\r
+            if (PEAR::isError($foreign_fields)) {\r
+                return $foreign_fields;\r
+            }\r
+            $colpos = 1;\r
+            foreach ($foreign_fields as $foreign_field) {\r
+                $definition['references']['fields'][$foreign_field] = array(\r
+                    'position' => $colpos++,\r
+                );\r
+            }\r
+        }\r
+        \r
+        if ($definition['check']) {\r
+            $check_def = $db->queryOne("SELECT pg_get_constraintdef(" . $row['oid'] . ", 't')");\r
+            // ...\r
+        }\r
+        return $definition;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getTriggerDefinition()\r
+\r
+    /**\r
+     * Get the structure of a trigger into an array\r
+     *\r
+     * EXPERIMENTAL\r
+     *\r
+     * WARNING: this function is experimental and may change the returned value\r
+     * at any time until labelled as non-experimental\r
+     *\r
+     * @param string $trigger name of trigger that should be used in method\r
+     * @return mixed data array on success, a MDB2 error on failure\r
+     * @access public\r
+     *\r
+     * @TODO: add support for plsql functions and functions with args\r
+     */\r
+    function getTriggerDefinition($trigger)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = "SELECT trg.tgname AS trigger_name,\r
+                         tbl.relname AS table_name,\r
+                         CASE\r
+                            WHEN p.proname IS NOT NULL THEN 'EXECUTE PROCEDURE ' || p.proname || '();'\r
+                            ELSE ''\r
+                         END AS trigger_body,\r
+                         CASE trg.tgtype & cast(2 as int2)\r
+                            WHEN 0 THEN 'AFTER'\r
+                            ELSE 'BEFORE'\r
+                         END AS trigger_type,\r
+                         CASE trg.tgtype & cast(28 as int2)\r
+                            WHEN 16 THEN 'UPDATE'\r
+                            WHEN 8 THEN 'DELETE'\r
+                            WHEN 4 THEN 'INSERT'\r
+                            WHEN 20 THEN 'INSERT, UPDATE'\r
+                            WHEN 28 THEN 'INSERT, UPDATE, DELETE'\r
+                            WHEN 24 THEN 'UPDATE, DELETE'\r
+                            WHEN 12 THEN 'INSERT, DELETE'\r
+                         END AS trigger_event,\r
+                         CASE trg.tgenabled\r
+                            WHEN 'O' THEN 't'\r
+                            ELSE trg.tgenabled\r
+                         END AS trigger_enabled,\r
+                         obj_description(trg.oid, 'pg_trigger') AS trigger_comment\r
+                    FROM pg_trigger trg,\r
+                         pg_class tbl,\r
+                         pg_proc p\r
+                   WHERE trg.tgrelid = tbl.oid\r
+                     AND trg.tgfoid = p.oid\r
+                     AND trg.tgname = ". $db->quote($trigger, 'text');\r
+        $types = array(\r
+            'trigger_name'    => 'text',\r
+            'table_name'      => 'text',\r
+            'trigger_body'    => 'text',\r
+            'trigger_type'    => 'text',\r
+            'trigger_event'   => 'text',\r
+            'trigger_comment' => 'text',\r
+            'trigger_enabled' => 'boolean',\r
+        );\r
+        return $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);\r
+    }\r
+    \r
+    // }}}\r
+    // {{{ tableInfo()\r
+\r
+    /**\r
+     * Returns information about a table or a result set\r
+     *\r
+     * NOTE: only supports 'table' and 'flags' if <var>$result</var>\r
+     * is a table name.\r
+     *\r
+     * @param object|string  $result  MDB2_result object from a query or a\r
+     *                                 string containing the name of a table.\r
+     *                                 While this also accepts a query result\r
+     *                                 resource identifier, this behavior is\r
+     *                                 deprecated.\r
+     * @param int            $mode    a valid tableInfo mode\r
+     *\r
+     * @return array  an associative array with the information requested.\r
+     *                 A MDB2_Error object on failure.\r
+     *\r
+     * @see MDB2_Driver_Common::tableInfo()\r
+     */\r
+    function tableInfo($result, $mode = null)\r
+    {\r
+        if (is_string($result)) {\r
+           return parent::tableInfo($result, $mode);\r
+        }\r
+\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result;\r
+        if (!is_resource($resource)) {\r
+            return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,\r
+                'Could not generate result resource', __FUNCTION__);\r
+        }\r
+\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            if ($db->options['field_case'] == CASE_LOWER) {\r
+                $case_func = 'strtolower';\r
+            } else {\r
+                $case_func = 'strtoupper';\r
+            }\r
+        } else {\r
+            $case_func = 'strval';\r
+        }\r
+\r
+        $count = @pg_num_fields($resource);\r
+        $res   = array();\r
+\r
+        if ($mode) {\r
+            $res['num_fields'] = $count;\r
+        }\r
+\r
+        $db->loadModule('Datatype', null, true);\r
+        for ($i = 0; $i < $count; $i++) {\r
+            $res[$i] = array(\r
+                'table' => function_exists('pg_field_table') ? @pg_field_table($resource, $i) : '',\r
+                'name'  => $case_func(@pg_field_name($resource, $i)),\r
+                'type'  => @pg_field_type($resource, $i),\r
+                'length' => @pg_field_size($resource, $i),\r
+                'flags' => '',\r
+            );\r
+            $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]);\r
+            if (PEAR::isError($mdb2type_info)) {\r
+               return $mdb2type_info;\r
+            }\r
+            $res[$i]['mdb2type'] = $mdb2type_info[0][0];\r
+            if ($mode & MDB2_TABLEINFO_ORDER) {\r
+                $res['order'][$res[$i]['name']] = $i;\r
+            }\r
+            if ($mode & MDB2_TABLEINFO_ORDERTABLE) {\r
+                $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;\r
+            }\r
+        }\r
+\r
+        return $res;\r
+    }\r
+}\r
 ?>
\ No newline at end of file
index 60c686c418a1d54339897b08e101ea9f2e122889..b98ccdb62cd60cb083f10e11cf20e9becb472685 100644 (file)
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith, Lorenzo Alberton                       |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Authors: Lukas Smith <smith@pooteeweet.org>                          |
-// |          Lorenzo Alberton <l.alberton@quipo.it>                      |
-// +----------------------------------------------------------------------+
-//
-// $Id: sqlite.php,v 1.80 2008/05/03 10:30:14 quipo Exp $
-//
-
-require_once('MDB2/Driver/Reverse/Common.php');
-
-/**
- * MDB2 SQlite driver for the schema reverse engineering module
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Reverse_sqlite extends MDB2_Driver_Reverse_Common
-{
-    /**
-     * Remove SQL comments from the field definition
-     *
-     * @access private
-     */
-    function _removeComments($sql) {
-        $lines = explode("\n", $sql);
-        foreach ($lines as $k => $line) {
-            $pieces = explode('--', $line);
-            if (count($pieces) > 1 && (substr_count($pieces[0], '\'') % 2) == 0) {
-                $lines[$k] = substr($line, 0, strpos($line, '--'));
-            }
-        }
-        return implode("\n", $lines);
-    }
-
-    /**
-     *
-     */
-    function _getTableColumns($sql)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-        $start_pos  = strpos($sql, '(');
-        $end_pos    = strrpos($sql, ')');
-        $column_def = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
-        // replace the decimal length-places-separator with a colon
-        $column_def = preg_replace('/(\d),(\d)/', '\1:\2', $column_def);
-        $column_def = $this->_removeComments($column_def);
-        $column_sql = explode(',', $column_def);
-        $columns    = array();
-        $count      = count($column_sql);
-        if ($count == 0) {
-            return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'unexpected empty table column definition list', __FUNCTION__);
-        }
-        $regexp = '/^\s*([^\s]+) +(CHAR|VARCHAR|VARCHAR2|TEXT|BOOLEAN|SMALLINT|INT|INTEGER|DECIMAL|BIGINT|DOUBLE|FLOAT|DATETIME|DATE|TIME|LONGTEXT|LONGBLOB)( ?\(([1-9][0-9]*)(:([1-9][0-9]*))?\))?( NULL| NOT NULL)?( UNSIGNED)?( NULL| NOT NULL)?( PRIMARY KEY)?( DEFAULT (\'[^\']*\'|[^ ]+))?( NULL| NOT NULL)?( PRIMARY KEY)?(\s*\-\-.*)?$/i';
-        $regexp2 = '/^\s*([^ ]+) +(PRIMARY|UNIQUE|CHECK)$/i';
-        for ($i=0, $j=0; $i<$count; ++$i) {
-            if (!preg_match($regexp, trim($column_sql[$i]), $matches)) {
-                if (!preg_match($regexp2, trim($column_sql[$i]))) {
-                    continue;
-                }
-                return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                    'unexpected table column SQL definition: "'.$column_sql[$i].'"', __FUNCTION__);
-            }
-            $columns[$j]['name'] = trim($matches[1], implode('', $db->identifier_quoting));
-            $columns[$j]['type'] = strtolower($matches[2]);
-            if (isset($matches[4]) && strlen($matches[4])) {
-                $columns[$j]['length'] = $matches[4];
-            }
-            if (isset($matches[6]) && strlen($matches[6])) {
-                $columns[$j]['decimal'] = $matches[6];
-            }
-            if (isset($matches[8]) && strlen($matches[8])) {
-                $columns[$j]['unsigned'] = true;
-            }
-            if (isset($matches[9]) && strlen($matches[9])) {
-                $columns[$j]['autoincrement'] = true;
-            }
-            if (isset($matches[12]) && strlen($matches[12])) {
-                $default = $matches[12];
-                if (strlen($default) && $default[0]=="'") {
-                    $default = str_replace("''", "'", substr($default, 1, strlen($default)-2));
-                }
-                if ($default === 'NULL') {
-                    $default = null;
-                }
-                $columns[$j]['default'] = $default;
-            }
-            if (isset($matches[7]) && strlen($matches[7])) {
-                $columns[$j]['notnull'] = ($matches[7] === ' NOT NULL');
-            } else if (isset($matches[9]) && strlen($matches[9])) {
-                $columns[$j]['notnull'] = ($matches[9] === ' NOT NULL');
-            } else if (isset($matches[13]) && strlen($matches[13])) {
-                $columns[$j]['notnull'] = ($matches[13] === ' NOT NULL');
-            }
-            ++$j;
-        }
-        return $columns;
-    }
-
-    // {{{ getTableFieldDefinition()
-
-    /**
-     * Get the stucture of a field into an array
-     *
-     * @param string $table_name name of table that should be used in method
-     * @param string $field_name name of field that should be used in method
-     * @return mixed data array on success, a MDB2 error on failure.
-     *          The returned array contains an array for each field definition,
-     *          with (some of) these indices:
-     *          [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type]
-     * @access public
-     */
-    function getTableFieldDefinition($table_name, $field_name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-        
-        list($schema, $table) = $this->splitTableSchema($table_name);
-
-        $result = $db->loadModule('Datatype', null, true);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');
-        } else {
-            $query.= 'name='.$db->quote($table, 'text');
-        }
-        $sql = $db->queryOne($query);
-        if (PEAR::isError($sql)) {
-            return $sql;
-        }
-        $columns = $this->_getTableColumns($sql);
-        foreach ($columns as $column) {
-            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-                if ($db->options['field_case'] == CASE_LOWER) {
-                    $column['name'] = strtolower($column['name']);
-                } else {
-                    $column['name'] = strtoupper($column['name']);
-                }
-            } else {
-                $column = array_change_key_case($column, $db->options['field_case']);
-            }
-            if ($field_name == $column['name']) {
-                $mapped_datatype = $db->datatype->mapNativeDatatype($column);
-                if (PEAR::isError($mapped_datatype)) {
-                    return $mapped_datatype;
-                }
-                list($types, $length, $unsigned, $fixed) = $mapped_datatype;
-                $notnull = false;
-                if (!empty($column['notnull'])) {
-                    $notnull = $column['notnull'];
-                }
-                $default = false;
-                if (array_key_exists('default', $column)) {
-                    $default = $column['default'];
-                    if (is_null($default) && $notnull) {
-                        $default = '';
-                    }
-                }
-                $autoincrement = false;
-                if (!empty($column['autoincrement'])) {
-                    $autoincrement = true;
-                }
-
-                $definition[0] = array(
-                    'notnull' => $notnull,
-                    'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type'])
-                );
-                if (!is_null($length)) {
-                    $definition[0]['length'] = $length;
-                }
-                if (!is_null($unsigned)) {
-                    $definition[0]['unsigned'] = $unsigned;
-                }
-                if (!is_null($fixed)) {
-                    $definition[0]['fixed'] = $fixed;
-                }
-                if ($default !== false) {
-                    $definition[0]['default'] = $default;
-                }
-                if ($autoincrement !== false) {
-                    $definition[0]['autoincrement'] = $autoincrement;
-                }
-                foreach ($types as $key => $type) {
-                    $definition[$key] = $definition[0];
-                    if ($type == 'clob' || $type == 'blob') {
-                        unset($definition[$key]['default']);
-                    }
-                    $definition[$key]['type'] = $type;
-                    $definition[$key]['mdb2type'] = $type;
-                }
-                return $definition;
-            }
-        }
-
-        return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-            'it was not specified an existing table column', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ getTableIndexDefinition()
-
-    /**
-     * Get the stucture of an index into an array
-     *
-     * @param string $table_name name of table that should be used in method
-     * @param string $index_name name of index that should be used in method
-     * @return mixed data array on success, a MDB2 error on failure
-     * @access public
-     */
-    function getTableIndexDefinition($table_name, $index_name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-        
-        list($schema, $table) = $this->splitTableSchema($table_name);
-
-        $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text');
-        } else {
-            $query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text');
-        }
-        $query.= ' AND sql NOT NULL ORDER BY name';
-        $index_name_mdb2 = $db->getIndexName($index_name);
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $qry = sprintf($query, $db->quote(strtolower($index_name_mdb2), 'text'));
-        } else {
-            $qry = sprintf($query, $db->quote($index_name_mdb2, 'text'));
-        }
-        $sql = $db->queryOne($qry, 'text');
-        if (PEAR::isError($sql) || empty($sql)) {
-            // fallback to the given $index_name, without transformation
-            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-                $qry = sprintf($query, $db->quote(strtolower($index_name), 'text'));
-            } else {
-                $qry = sprintf($query, $db->quote($index_name, 'text'));
-            }
-            $sql = $db->queryOne($qry, 'text');
-        }
-        if (PEAR::isError($sql)) {
-            return $sql;
-        }
-        if (!$sql) {
-            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                'it was not specified an existing table index', __FUNCTION__);
-        }
-
-        $sql = strtolower($sql);
-        $start_pos = strpos($sql, '(');
-        $end_pos = strrpos($sql, ')');
-        $column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
-        $column_names = explode(',', $column_names);
-
-        if (preg_match("/^create unique/", $sql)) {
-            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                'it was not specified an existing table index', __FUNCTION__);
-        }
-
-        $definition = array();
-        $count = count($column_names);
-        for ($i=0; $i<$count; ++$i) {
-            $column_name = strtok($column_names[$i], ' ');
-            $collation = strtok(' ');
-            $definition['fields'][$column_name] = array(
-                'position' => $i+1
-            );
-            if (!empty($collation)) {
-                $definition['fields'][$column_name]['sorting'] =
-                    ($collation=='ASC' ? 'ascending' : 'descending');
-            }
-        }
-
-        if (empty($definition['fields'])) {
-            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                'it was not specified an existing table index', __FUNCTION__);
-        }
-        return $definition;
-    }
-
-    // }}}
-    // {{{ getTableConstraintDefinition()
-
-    /**
-     * Get the stucture of a constraint into an array
-     *
-     * @param string $table_name      name of table that should be used in method
-     * @param string $constraint_name name of constraint that should be used in method
-     * @return mixed data array on success, a MDB2 error on failure
-     * @access public
-     */
-    function getTableConstraintDefinition($table_name, $constraint_name)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-        
-        list($schema, $table) = $this->splitTableSchema($table_name);
-
-        $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text');
-        } else {
-            $query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text');
-        }
-        $query.= ' AND sql NOT NULL ORDER BY name';
-        $constraint_name_mdb2 = $db->getIndexName($constraint_name);
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $qry = sprintf($query, $db->quote(strtolower($constraint_name_mdb2), 'text'));
-        } else {
-            $qry = sprintf($query, $db->quote($constraint_name_mdb2, 'text'));
-        }
-        $sql = $db->queryOne($qry, 'text');
-        if (PEAR::isError($sql) || empty($sql)) {
-            // fallback to the given $index_name, without transformation
-            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-                $qry = sprintf($query, $db->quote(strtolower($constraint_name), 'text'));
-            } else {
-                $qry = sprintf($query, $db->quote($constraint_name, 'text'));
-            }
-            $sql = $db->queryOne($qry, 'text');
-        }
-        if (PEAR::isError($sql)) {
-            return $sql;
-        }
-        //default values, eventually overridden
-        $definition = array(
-            'primary' => false,
-            'unique'  => false,
-            'foreign' => false,
-            'check'   => false,
-            'fields'  => array(),
-            'references' => array(
-                'table'  => '',
-                'fields' => array(),
-            ),
-            'onupdate'  => '',
-            'ondelete'  => '',
-            'match'     => '',
-            'deferrable'        => false,
-            'initiallydeferred' => false,
-        );
-        if (!$sql) {
-            $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
-            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-                $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');
-            } else {
-                $query.= 'name='.$db->quote($table, 'text');
-            }
-            $query.= " AND sql NOT NULL ORDER BY name";
-            $sql = $db->queryOne($query, 'text');
-            if (PEAR::isError($sql)) {
-                return $sql;
-            }
-            if ($constraint_name == 'primary') {
-                // search in table definition for PRIMARY KEYs
-                if (preg_match("/\bPRIMARY\s+KEY\b\s*\(([^)]+)/i", $sql, $tmp)) {
-                    $definition['primary'] = true;
-                    $definition['fields'] = array();
-                    $column_names = explode(',', $tmp[1]);
-                    $colpos = 1;
-                    foreach ($column_names as $column_name) {
-                        $definition['fields'][trim($column_name)] = array(
-                            'position' => $colpos++
-                        );
-                    }
-                    return $definition;
-                }
-                if (preg_match("/\"([^\"]+)\"[^\,\"]+\bPRIMARY\s+KEY\b[^\,\)]*/i", $sql, $tmp)) {
-                    $definition['primary'] = true;
-                    $definition['fields'] = array();
-                    $column_names = explode(',', $tmp[1]);
-                    $colpos = 1;
-                    foreach ($column_names as $column_name) {
-                        $definition['fields'][trim($column_name)] = array(
-                            'position' => $colpos++
-                        );
-                    }
-                    return $definition;
-                }
-            } else {
-                // search in table definition for FOREIGN KEYs
-                $pattern = "/\bCONSTRAINT\b\s+%s\s+
-                    \bFOREIGN\s+KEY\b\s*\(([^\)]+)\)\s*
-                    \bREFERENCES\b\s+([^\s]+)\s*\(([^\)]+)\)\s*
-                    (?:\bMATCH\s*([^\s]+))?\s*
-                    (?:\bON\s+UPDATE\s+([^\s,\)]+))?\s*
-                    (?:\bON\s+DELETE\s+([^\s,\)]+))?\s*
-                    /imsx";
-                $found_fk = false;
-                if (preg_match(sprintf($pattern, $constraint_name_mdb2), $sql, $tmp)) {
-                    $found_fk = true;
-                } elseif (preg_match(sprintf($pattern, $constraint_name), $sql, $tmp)) {
-                    $found_fk = true;
-                }
-                if ($found_fk) {
-                    $definition['foreign'] = true;
-                    $definition['match'] = 'SIMPLE';
-                    $definition['onupdate'] = 'NO ACTION';
-                    $definition['ondelete'] = 'NO ACTION';
-                    $definition['references']['table'] = $tmp[2];
-                    $column_names = explode(',', $tmp[1]);
-                    $colpos = 1;
-                    foreach ($column_names as $column_name) {
-                        $definition['fields'][trim($column_name)] = array(
-                            'position' => $colpos++
-                        );
-                    }
-                    $referenced_cols = explode(',', $tmp[3]);
-                    $colpos = 1;
-                    foreach ($referenced_cols as $column_name) {
-                        $definition['references']['fields'][trim($column_name)] = array(
-                            'position' => $colpos++
-                        );
-                    }
-                    if (isset($tmp[4])) {
-                        $definition['match']    = $tmp[4];
-                    }
-                    if (isset($tmp[5])) {
-                        $definition['onupdate'] = $tmp[5];
-                    }
-                    if (isset($tmp[6])) {
-                        $definition['ondelete'] = $tmp[6];
-                    }
-                    return $definition;
-                }
-            }
-            $sql = false;
-        }
-        if (!$sql) {
-            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                $constraint_name . ' is not an existing table constraint', __FUNCTION__);
-        }
-
-        $sql = strtolower($sql);
-        $start_pos = strpos($sql, '(');
-        $end_pos   = strrpos($sql, ')');
-        $column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
-        $column_names = explode(',', $column_names);
-
-        if (!preg_match("/^create unique/", $sql)) {
-            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                $constraint_name . ' is not an existing table constraint', __FUNCTION__);
-        }
-
-        $definition['unique'] = true;
-        $count = count($column_names);
-        for ($i=0; $i<$count; ++$i) {
-            $column_name = strtok($column_names[$i]," ");
-            $collation = strtok(" ");
-            $definition['fields'][$column_name] = array(
-                'position' => $i+1
-            );
-            if (!empty($collation)) {
-                $definition['fields'][$column_name]['sorting'] =
-                    ($collation=='ASC' ? 'ascending' : 'descending');
-            }
-        }
-
-        if (empty($definition['fields'])) {
-            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                $constraint_name . ' is not an existing table constraint', __FUNCTION__);
-        }
-        return $definition;
-    }
-
-    // }}}
-    // {{{ getTriggerDefinition()
-
-    /**
-     * Get the structure of a trigger into an array
-     *
-     * EXPERIMENTAL
-     *
-     * WARNING: this function is experimental and may change the returned value
-     * at any time until labelled as non-experimental
-     *
-     * @param string    $trigger    name of trigger that should be used in method
-     * @return mixed data array on success, a MDB2 error on failure
-     * @access public
-     */
-    function getTriggerDefinition($trigger)
-    {
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $query = "SELECT name as trigger_name,
-                         tbl_name AS table_name,
-                         sql AS trigger_body,
-                         NULL AS trigger_type,
-                         NULL AS trigger_event,
-                         NULL AS trigger_comment,
-                         1 AS trigger_enabled
-                    FROM sqlite_master
-                   WHERE type='trigger'";
-        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $query.= ' AND LOWER(name)='.$db->quote(strtolower($trigger), 'text');
-        } else {
-            $query.= ' AND name='.$db->quote($trigger, 'text');
-        }
-        $types = array(
-            'trigger_name'    => 'text',
-            'table_name'      => 'text',
-            'trigger_body'    => 'text',
-            'trigger_type'    => 'text',
-            'trigger_event'   => 'text',
-            'trigger_comment' => 'text',
-            'trigger_enabled' => 'boolean',
-        );
-        $def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
-        if (PEAR::isError($def)) {
-            return $def;
-        }
-        if (empty($def)) {
-            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                'it was not specified an existing trigger', __FUNCTION__);
-        }
-        if (preg_match("/^create\s+(?:temp|temporary)?trigger\s+(?:if\s+not\s+exists\s+)?.*(before|after)?\s+(insert|update|delete)/Uims", $def['trigger_body'], $tmp)) {
-            $def['trigger_type'] = strtoupper($tmp[1]);
-            $def['trigger_event'] = strtoupper($tmp[2]);
-        }
-        return $def;
-    }
-
-    // }}}
-    // {{{ tableInfo()
-
-    /**
-     * Returns information about a table
-     *
-     * @param string         $result  a string containing the name of a table
-     * @param int            $mode    a valid tableInfo mode
-     *
-     * @return array  an associative array with the information requested.
-     *                 A MDB2_Error object on failure.
-     *
-     * @see MDB2_Driver_Common::tableInfo()
-     * @since Method available since Release 1.7.0
-     */
-    function tableInfo($result, $mode = null)
-    {
-        if (is_string($result)) {
-           return parent::tableInfo($result, $mode);
-        }
-
-        $db =$this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        return $db->raiseError(MDB2_ERROR_NOT_CAPABLE, null, null,
-           'This DBMS can not obtain tableInfo from result sets', __FUNCTION__);
-    }
-}
-
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith, Lorenzo Alberton                       |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Authors: Lukas Smith <smith@pooteeweet.org>                          |\r
+// |          Lorenzo Alberton <l.alberton@quipo.it>                      |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: sqlite.php 295587 2010-02-28 17:16:38Z quipo $\r
+//\r
+\r
+require_once 'MDB2/Driver/Reverse/Common.php';\r
+\r
+/**\r
+ * MDB2 SQlite driver for the schema reverse engineering module\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Driver_Reverse_sqlite extends MDB2_Driver_Reverse_Common\r
+{\r
+    /**\r
+     * Remove SQL comments from the field definition\r
+     *\r
+     * @access private\r
+     */\r
+    function _removeComments($sql) {\r
+        $lines = explode("\n", $sql);\r
+        foreach ($lines as $k => $line) {\r
+            $pieces = explode('--', $line);\r
+            if (count($pieces) > 1 && (substr_count($pieces[0], '\'') % 2) == 0) {\r
+                $lines[$k] = substr($line, 0, strpos($line, '--'));\r
+            }\r
+        }\r
+        return implode("\n", $lines);\r
+    }\r
+\r
+    /**\r
+     *\r
+     */\r
+    function _getTableColumns($sql)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+        $start_pos  = strpos($sql, '(');\r
+        $end_pos    = strrpos($sql, ')');\r
+        $column_def = substr($sql, $start_pos+1, $end_pos-$start_pos-1);\r
+        // replace the decimal length-places-separator with a colon\r
+        $column_def = preg_replace('/(\d),(\d)/', '\1:\2', $column_def);\r
+        $column_def = $this->_removeComments($column_def);\r
+        $column_sql = explode(',', $column_def);\r
+        $columns    = array();\r
+        $count      = count($column_sql);\r
+        if ($count == 0) {\r
+            return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'unexpected empty table column definition list', __FUNCTION__);\r
+        }\r
+        $regexp = '/^\s*([^\s]+) +(CHAR|VARCHAR|VARCHAR2|TEXT|BOOLEAN|SMALLINT|INT|INTEGER|DECIMAL|BIGINT|DOUBLE|FLOAT|DATETIME|DATE|TIME|LONGTEXT|LONGBLOB)( ?\(([1-9][0-9]*)(:([1-9][0-9]*))?\))?( NULL| NOT NULL)?( UNSIGNED)?( NULL| NOT NULL)?( PRIMARY KEY)?( DEFAULT (\'[^\']*\'|[^ ]+))?( NULL| NOT NULL)?( PRIMARY KEY)?(\s*\-\-.*)?$/i';\r
+        $regexp2 = '/^\s*([^ ]+) +(PRIMARY|UNIQUE|CHECK)$/i';\r
+        for ($i=0, $j=0; $i<$count; ++$i) {\r
+            if (!preg_match($regexp, trim($column_sql[$i]), $matches)) {\r
+                if (!preg_match($regexp2, trim($column_sql[$i]))) {\r
+                    continue;\r
+                }\r
+                return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                    'unexpected table column SQL definition: "'.$column_sql[$i].'"', __FUNCTION__);\r
+            }\r
+            $columns[$j]['name'] = trim($matches[1], implode('', $db->identifier_quoting));\r
+            $columns[$j]['type'] = strtolower($matches[2]);\r
+            if (isset($matches[4]) && strlen($matches[4])) {\r
+                $columns[$j]['length'] = $matches[4];\r
+            }\r
+            if (isset($matches[6]) && strlen($matches[6])) {\r
+                $columns[$j]['decimal'] = $matches[6];\r
+            }\r
+            if (isset($matches[8]) && strlen($matches[8])) {\r
+                $columns[$j]['unsigned'] = true;\r
+            }\r
+            if (isset($matches[9]) && strlen($matches[9])) {\r
+                $columns[$j]['autoincrement'] = true;\r
+            }\r
+            if (isset($matches[12]) && strlen($matches[12])) {\r
+                $default = $matches[12];\r
+                if (strlen($default) && $default[0]=="'") {\r
+                    $default = str_replace("''", "'", substr($default, 1, strlen($default)-2));\r
+                }\r
+                if ($default === 'NULL') {\r
+                    $default = null;\r
+                }\r
+                $columns[$j]['default'] = $default;\r
+            }\r
+            if (isset($matches[7]) && strlen($matches[7])) {\r
+                $columns[$j]['notnull'] = ($matches[7] === ' NOT NULL');\r
+            } else if (isset($matches[9]) && strlen($matches[9])) {\r
+                $columns[$j]['notnull'] = ($matches[9] === ' NOT NULL');\r
+            } else if (isset($matches[13]) && strlen($matches[13])) {\r
+                $columns[$j]['notnull'] = ($matches[13] === ' NOT NULL');\r
+            }\r
+            ++$j;\r
+        }\r
+        return $columns;\r
+    }\r
+\r
+    // {{{ getTableFieldDefinition()\r
+\r
+    /**\r
+     * Get the stucture of a field into an array\r
+     *\r
+     * @param string $table_name name of table that should be used in method\r
+     * @param string $field_name name of field that should be used in method\r
+     * @return mixed data array on success, a MDB2 error on failure.\r
+     *          The returned array contains an array for each field definition,\r
+     *          with (some of) these indices:\r
+     *          [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type]\r
+     * @access public\r
+     */\r
+    function getTableFieldDefinition($table_name, $field_name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+        \r
+        list($schema, $table) = $this->splitTableSchema($table_name);\r
+\r
+        $result = $db->loadModule('Datatype', null, true);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');\r
+        } else {\r
+            $query.= 'name='.$db->quote($table, 'text');\r
+        }\r
+        $sql = $db->queryOne($query);\r
+        if (PEAR::isError($sql)) {\r
+            return $sql;\r
+        }\r
+        $columns = $this->_getTableColumns($sql);\r
+        foreach ($columns as $column) {\r
+            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+                if ($db->options['field_case'] == CASE_LOWER) {\r
+                    $column['name'] = strtolower($column['name']);\r
+                } else {\r
+                    $column['name'] = strtoupper($column['name']);\r
+                }\r
+            } else {\r
+                $column = array_change_key_case($column, $db->options['field_case']);\r
+            }\r
+            if ($field_name == $column['name']) {\r
+                $mapped_datatype = $db->datatype->mapNativeDatatype($column);\r
+                if (PEAR::isError($mapped_datatype)) {\r
+                    return $mapped_datatype;\r
+                }\r
+                list($types, $length, $unsigned, $fixed) = $mapped_datatype;\r
+                $notnull = false;\r
+                if (!empty($column['notnull'])) {\r
+                    $notnull = $column['notnull'];\r
+                }\r
+                $default = false;\r
+                if (array_key_exists('default', $column)) {\r
+                    $default = $column['default'];\r
+                    if ((null === $default) && $notnull) {\r
+                        $default = '';\r
+                    }\r
+                }\r
+                $autoincrement = false;\r
+                if (!empty($column['autoincrement'])) {\r
+                    $autoincrement = true;\r
+                }\r
+\r
+                $definition[0] = array(\r
+                    'notnull' => $notnull,\r
+                    'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type'])\r
+                );\r
+                if (null !== $length) {\r
+                    $definition[0]['length'] = $length;\r
+                }\r
+                if (null !== $unsigned) {\r
+                    $definition[0]['unsigned'] = $unsigned;\r
+                }\r
+                if (null !== $fixed) {\r
+                    $definition[0]['fixed'] = $fixed;\r
+                }\r
+                if ($default !== false) {\r
+                    $definition[0]['default'] = $default;\r
+                }\r
+                if ($autoincrement !== false) {\r
+                    $definition[0]['autoincrement'] = $autoincrement;\r
+                }\r
+                foreach ($types as $key => $type) {\r
+                    $definition[$key] = $definition[0];\r
+                    if ($type == 'clob' || $type == 'blob') {\r
+                        unset($definition[$key]['default']);\r
+                    }\r
+                    $definition[$key]['type'] = $type;\r
+                    $definition[$key]['mdb2type'] = $type;\r
+                }\r
+                return $definition;\r
+            }\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+            'it was not specified an existing table column', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getTableIndexDefinition()\r
+\r
+    /**\r
+     * Get the stucture of an index into an array\r
+     *\r
+     * @param string $table_name name of table that should be used in method\r
+     * @param string $index_name name of index that should be used in method\r
+     * @return mixed data array on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function getTableIndexDefinition($table_name, $index_name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+        \r
+        list($schema, $table) = $this->splitTableSchema($table_name);\r
+\r
+        $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text');\r
+        } else {\r
+            $query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text');\r
+        }\r
+        $query.= ' AND sql NOT NULL ORDER BY name';\r
+        $index_name_mdb2 = $db->getIndexName($index_name);\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $qry = sprintf($query, $db->quote(strtolower($index_name_mdb2), 'text'));\r
+        } else {\r
+            $qry = sprintf($query, $db->quote($index_name_mdb2, 'text'));\r
+        }\r
+        $sql = $db->queryOne($qry, 'text');\r
+        if (PEAR::isError($sql) || empty($sql)) {\r
+            // fallback to the given $index_name, without transformation\r
+            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+                $qry = sprintf($query, $db->quote(strtolower($index_name), 'text'));\r
+            } else {\r
+                $qry = sprintf($query, $db->quote($index_name, 'text'));\r
+            }\r
+            $sql = $db->queryOne($qry, 'text');\r
+        }\r
+        if (PEAR::isError($sql)) {\r
+            return $sql;\r
+        }\r
+        if (!$sql) {\r
+            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                'it was not specified an existing table index', __FUNCTION__);\r
+        }\r
+\r
+        $sql = strtolower($sql);\r
+        $start_pos = strpos($sql, '(');\r
+        $end_pos = strrpos($sql, ')');\r
+        $column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1);\r
+        $column_names = explode(',', $column_names);\r
+\r
+        if (preg_match("/^create unique/", $sql)) {\r
+            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                'it was not specified an existing table index', __FUNCTION__);\r
+        }\r
+\r
+        $definition = array();\r
+        $count = count($column_names);\r
+        for ($i=0; $i<$count; ++$i) {\r
+            $column_name = strtok($column_names[$i], ' ');\r
+            $collation = strtok(' ');\r
+            $definition['fields'][$column_name] = array(\r
+                'position' => $i+1\r
+            );\r
+            if (!empty($collation)) {\r
+                $definition['fields'][$column_name]['sorting'] =\r
+                    ($collation=='ASC' ? 'ascending' : 'descending');\r
+            }\r
+        }\r
+\r
+        if (empty($definition['fields'])) {\r
+            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                'it was not specified an existing table index', __FUNCTION__);\r
+        }\r
+        return $definition;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getTableConstraintDefinition()\r
+\r
+    /**\r
+     * Get the stucture of a constraint into an array\r
+     *\r
+     * @param string $table_name      name of table that should be used in method\r
+     * @param string $constraint_name name of constraint that should be used in method\r
+     * @return mixed data array on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function getTableConstraintDefinition($table_name, $constraint_name)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+        \r
+        list($schema, $table) = $this->splitTableSchema($table_name);\r
+\r
+        $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text');\r
+        } else {\r
+            $query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text');\r
+        }\r
+        $query.= ' AND sql NOT NULL ORDER BY name';\r
+        $constraint_name_mdb2 = $db->getIndexName($constraint_name);\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $qry = sprintf($query, $db->quote(strtolower($constraint_name_mdb2), 'text'));\r
+        } else {\r
+            $qry = sprintf($query, $db->quote($constraint_name_mdb2, 'text'));\r
+        }\r
+        $sql = $db->queryOne($qry, 'text');\r
+        if (PEAR::isError($sql) || empty($sql)) {\r
+            // fallback to the given $index_name, without transformation\r
+            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+                $qry = sprintf($query, $db->quote(strtolower($constraint_name), 'text'));\r
+            } else {\r
+                $qry = sprintf($query, $db->quote($constraint_name, 'text'));\r
+            }\r
+            $sql = $db->queryOne($qry, 'text');\r
+        }\r
+        if (PEAR::isError($sql)) {\r
+            return $sql;\r
+        }\r
+        //default values, eventually overridden\r
+        $definition = array(\r
+            'primary' => false,\r
+            'unique'  => false,\r
+            'foreign' => false,\r
+            'check'   => false,\r
+            'fields'  => array(),\r
+            'references' => array(\r
+                'table'  => '',\r
+                'fields' => array(),\r
+            ),\r
+            'onupdate'  => '',\r
+            'ondelete'  => '',\r
+            'match'     => '',\r
+            'deferrable'        => false,\r
+            'initiallydeferred' => false,\r
+        );\r
+        if (!$sql) {\r
+            $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";\r
+            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+                $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');\r
+            } else {\r
+                $query.= 'name='.$db->quote($table, 'text');\r
+            }\r
+            $query.= " AND sql NOT NULL ORDER BY name";\r
+            $sql = $db->queryOne($query, 'text');\r
+            if (PEAR::isError($sql)) {\r
+                return $sql;\r
+            }\r
+            if ($constraint_name == 'primary') {\r
+                // search in table definition for PRIMARY KEYs\r
+                if (preg_match("/\bPRIMARY\s+KEY\b\s*\(([^)]+)/i", $sql, $tmp)) {\r
+                    $definition['primary'] = true;\r
+                    $definition['fields'] = array();\r
+                    $column_names = explode(',', $tmp[1]);\r
+                    $colpos = 1;\r
+                    foreach ($column_names as $column_name) {\r
+                        $definition['fields'][trim($column_name)] = array(\r
+                            'position' => $colpos++\r
+                        );\r
+                    }\r
+                    return $definition;\r
+                }\r
+                if (preg_match("/\"([^\"]+)\"[^\,\"]+\bPRIMARY\s+KEY\b[^\,\)]*/i", $sql, $tmp)) {\r
+                    $definition['primary'] = true;\r
+                    $definition['fields'] = array();\r
+                    $column_names = explode(',', $tmp[1]);\r
+                    $colpos = 1;\r
+                    foreach ($column_names as $column_name) {\r
+                        $definition['fields'][trim($column_name)] = array(\r
+                            'position' => $colpos++\r
+                        );\r
+                    }\r
+                    return $definition;\r
+                }\r
+            } else {\r
+                // search in table definition for FOREIGN KEYs\r
+                $pattern = "/\bCONSTRAINT\b\s+%s\s+\r
+                    \bFOREIGN\s+KEY\b\s*\(([^\)]+)\)\s*\r
+                    \bREFERENCES\b\s+([^\s]+)\s*\(([^\)]+)\)\s*\r
+                    (?:\bMATCH\s*([^\s]+))?\s*\r
+                    (?:\bON\s+UPDATE\s+([^\s,\)]+))?\s*\r
+                    (?:\bON\s+DELETE\s+([^\s,\)]+))?\s*\r
+                    /imsx";\r
+                $found_fk = false;\r
+                if (preg_match(sprintf($pattern, $constraint_name_mdb2), $sql, $tmp)) {\r
+                    $found_fk = true;\r
+                } elseif (preg_match(sprintf($pattern, $constraint_name), $sql, $tmp)) {\r
+                    $found_fk = true;\r
+                }\r
+                if ($found_fk) {\r
+                    $definition['foreign'] = true;\r
+                    $definition['match'] = 'SIMPLE';\r
+                    $definition['onupdate'] = 'NO ACTION';\r
+                    $definition['ondelete'] = 'NO ACTION';\r
+                    $definition['references']['table'] = $tmp[2];\r
+                    $column_names = explode(',', $tmp[1]);\r
+                    $colpos = 1;\r
+                    foreach ($column_names as $column_name) {\r
+                        $definition['fields'][trim($column_name)] = array(\r
+                            'position' => $colpos++\r
+                        );\r
+                    }\r
+                    $referenced_cols = explode(',', $tmp[3]);\r
+                    $colpos = 1;\r
+                    foreach ($referenced_cols as $column_name) {\r
+                        $definition['references']['fields'][trim($column_name)] = array(\r
+                            'position' => $colpos++\r
+                        );\r
+                    }\r
+                    if (isset($tmp[4])) {\r
+                        $definition['match']    = $tmp[4];\r
+                    }\r
+                    if (isset($tmp[5])) {\r
+                        $definition['onupdate'] = $tmp[5];\r
+                    }\r
+                    if (isset($tmp[6])) {\r
+                        $definition['ondelete'] = $tmp[6];\r
+                    }\r
+                    return $definition;\r
+                }\r
+            }\r
+            $sql = false;\r
+        }\r
+        if (!$sql) {\r
+            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                $constraint_name . ' is not an existing table constraint', __FUNCTION__);\r
+        }\r
+\r
+        $sql = strtolower($sql);\r
+        $start_pos = strpos($sql, '(');\r
+        $end_pos   = strrpos($sql, ')');\r
+        $column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1);\r
+        $column_names = explode(',', $column_names);\r
+\r
+        if (!preg_match("/^create unique/", $sql)) {\r
+            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                $constraint_name . ' is not an existing table constraint', __FUNCTION__);\r
+        }\r
+\r
+        $definition['unique'] = true;\r
+        $count = count($column_names);\r
+        for ($i=0; $i<$count; ++$i) {\r
+            $column_name = strtok($column_names[$i]," ");\r
+            $collation = strtok(" ");\r
+            $definition['fields'][$column_name] = array(\r
+                'position' => $i+1\r
+            );\r
+            if (!empty($collation)) {\r
+                $definition['fields'][$column_name]['sorting'] =\r
+                    ($collation=='ASC' ? 'ascending' : 'descending');\r
+            }\r
+        }\r
+\r
+        if (empty($definition['fields'])) {\r
+            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                $constraint_name . ' is not an existing table constraint', __FUNCTION__);\r
+        }\r
+        return $definition;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getTriggerDefinition()\r
+\r
+    /**\r
+     * Get the structure of a trigger into an array\r
+     *\r
+     * EXPERIMENTAL\r
+     *\r
+     * WARNING: this function is experimental and may change the returned value\r
+     * at any time until labelled as non-experimental\r
+     *\r
+     * @param string    $trigger    name of trigger that should be used in method\r
+     * @return mixed data array on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function getTriggerDefinition($trigger)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $query = "SELECT name as trigger_name,\r
+                         tbl_name AS table_name,\r
+                         sql AS trigger_body,\r
+                         NULL AS trigger_type,\r
+                         NULL AS trigger_event,\r
+                         NULL AS trigger_comment,\r
+                         1 AS trigger_enabled\r
+                    FROM sqlite_master\r
+                   WHERE type='trigger'";\r
+        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $query.= ' AND LOWER(name)='.$db->quote(strtolower($trigger), 'text');\r
+        } else {\r
+            $query.= ' AND name='.$db->quote($trigger, 'text');\r
+        }\r
+        $types = array(\r
+            'trigger_name'    => 'text',\r
+            'table_name'      => 'text',\r
+            'trigger_body'    => 'text',\r
+            'trigger_type'    => 'text',\r
+            'trigger_event'   => 'text',\r
+            'trigger_comment' => 'text',\r
+            'trigger_enabled' => 'boolean',\r
+        );\r
+        $def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);\r
+        if (PEAR::isError($def)) {\r
+            return $def;\r
+        }\r
+        if (empty($def)) {\r
+            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                'it was not specified an existing trigger', __FUNCTION__);\r
+        }\r
+        if (preg_match("/^create\s+(?:temp|temporary)?trigger\s+(?:if\s+not\s+exists\s+)?.*(before|after)?\s+(insert|update|delete)/Uims", $def['trigger_body'], $tmp)) {\r
+            $def['trigger_type'] = strtoupper($tmp[1]);\r
+            $def['trigger_event'] = strtoupper($tmp[2]);\r
+        }\r
+        return $def;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ tableInfo()\r
+\r
+    /**\r
+     * Returns information about a table\r
+     *\r
+     * @param string         $result  a string containing the name of a table\r
+     * @param int            $mode    a valid tableInfo mode\r
+     *\r
+     * @return array  an associative array with the information requested.\r
+     *                 A MDB2_Error object on failure.\r
+     *\r
+     * @see MDB2_Driver_Common::tableInfo()\r
+     * @since Method available since Release 1.7.0\r
+     */\r
+    function tableInfo($result, $mode = null)\r
+    {\r
+        if (is_string($result)) {\r
+           return parent::tableInfo($result, $mode);\r
+        }\r
+\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        return $db->raiseError(MDB2_ERROR_NOT_CAPABLE, null, null,\r
+           'This DBMS can not obtain tableInfo from result sets', __FUNCTION__);\r
+    }\r
+}\r
+\r
 ?>
\ No newline at end of file
index 2cec1e9c033b0fb36ef8b269bc6234d853053923..eda3310deeb0b0ce24db76ba61b7e29bdb7b3517 100644 (file)
-<?php
-// vim: set et ts=4 sw=4 fdm=marker:
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: mysql.php,v 1.214 2008/11/16 21:45:08 quipo Exp $
-//
-
-/**
- * MDB2 MySQL driver
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_mysql extends MDB2_Driver_Common
-{
-    // {{{ properties
-
-    var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => '\\', 'escape_pattern' => '\\');
-
-    var $identifier_quoting = array('start' => '`', 'end' => '`', 'escape' => '`');
-
-    var $sql_comments = array(
-        array('start' => '-- ', 'end' => "\n", 'escape' => false),
-        array('start' => '#', 'end' => "\n", 'escape' => false),
-        array('start' => '/*', 'end' => '*/', 'escape' => false),
-    );
-
-    var $server_capabilities_checked = false;
-
-    var $start_transaction = false;
-
-    var $varchar_max_length = 255;
-
-    // }}}
-    // {{{ constructor
-
-    /**
-     * Constructor
-     */
-    function __construct()
-    {
-        parent::__construct();
-
-        $this->phptype = 'mysql';
-        $this->dbsyntax = 'mysql';
-
-        $this->supported['sequences'] = 'emulated';
-        $this->supported['indexes'] = true;
-        $this->supported['affected_rows'] = true;
-        $this->supported['transactions'] = false;
-        $this->supported['savepoints'] = false;
-        $this->supported['summary_functions'] = true;
-        $this->supported['order_by_text'] = true;
-        $this->supported['current_id'] = 'emulated';
-        $this->supported['limit_queries'] = true;
-        $this->supported['LOBs'] = true;
-        $this->supported['replace'] = true;
-        $this->supported['sub_selects'] = 'emulated';
-        $this->supported['triggers'] = false;
-        $this->supported['auto_increment'] = true;
-        $this->supported['primary_key'] = true;
-        $this->supported['result_introspection'] = true;
-        $this->supported['prepared_statements'] = 'emulated';
-        $this->supported['identifier_quoting'] = true;
-        $this->supported['pattern_escaping'] = true;
-        $this->supported['new_link'] = true;
-
-        $this->options['DBA_username'] = false;
-        $this->options['DBA_password'] = false;
-        $this->options['default_table_type'] = '';
-        $this->options['max_identifiers_length'] = 64;
-
-        $this->_reCheckSupportedOptions();
-    }
-
-    // }}}
-    // {{{ _reCheckSupportedOptions()
-    
-    /**
-     * If the user changes certain options, other capabilities may depend
-     * on the new settings, so we need to check them (again).
-     *
-     * @access private
-     */
-    function _reCheckSupportedOptions()
-    {
-        $this->supported['transactions'] = $this->options['use_transactions'];
-        $this->supported['savepoints']   = $this->options['use_transactions'];
-        if ($this->options['default_table_type']) {
-            switch (strtoupper($this->options['default_table_type'])) {
-            case 'BLACKHOLE':
-            case 'MEMORY':
-            case 'ARCHIVE':
-            case 'CSV':
-            case 'HEAP':
-            case 'ISAM':
-            case 'MERGE':
-            case 'MRG_ISAM':
-            case 'ISAM':
-            case 'MRG_MYISAM':
-            case 'MYISAM':
-                $this->supported['savepoints']   = false;
-                $this->supported['transactions'] = false;
-                $this->warnings[] = $this->options['default_table_type'] .
-                    ' is not a supported default table type';
-                break;
-            }
-        }
-    }
-
-    // }}}
-    // {{{ function setOption($option, $value)
-
-    /**
-     * set the option for the db class
-     *
-     * @param   string  option name
-     * @param   mixed   value for the option
-     *
-     * @return  mixed   MDB2_OK or MDB2 Error Object
-     *
-     * @access  public
-     */
-    function setOption($option, $value)
-    {
-        $res = parent::setOption($option, $value);
-        $this->_reCheckSupportedOptions();
-    }
-
-    // }}}
-    // {{{ errorInfo()
-
-    /**
-     * This method is used to collect information about an error
-     *
-     * @param integer $error
-     * @return array
-     * @access public
-     */
-    function errorInfo($error = null)
-    {
-        if ($this->connection) {
-            $native_code = @mysql_errno($this->connection);
-            $native_msg  = @mysql_error($this->connection);
-        } else {
-            $native_code = @mysql_errno();
-            $native_msg  = @mysql_error();
-        }
-        if (is_null($error)) {
-            static $ecode_map;
-            if (empty($ecode_map)) {
-                $ecode_map = array(
-                    1000 => MDB2_ERROR_INVALID, //hashchk
-                    1001 => MDB2_ERROR_INVALID, //isamchk
-                    1004 => MDB2_ERROR_CANNOT_CREATE,
-                    1005 => MDB2_ERROR_CANNOT_CREATE,
-                    1006 => MDB2_ERROR_CANNOT_CREATE,
-                    1007 => MDB2_ERROR_ALREADY_EXISTS,
-                    1008 => MDB2_ERROR_CANNOT_DROP,
-                    1009 => MDB2_ERROR_CANNOT_DROP,
-                    1010 => MDB2_ERROR_CANNOT_DROP,
-                    1011 => MDB2_ERROR_CANNOT_DELETE,
-                    1022 => MDB2_ERROR_ALREADY_EXISTS,
-                    1029 => MDB2_ERROR_NOT_FOUND,
-                    1032 => MDB2_ERROR_NOT_FOUND,
-                    1044 => MDB2_ERROR_ACCESS_VIOLATION,
-                    1045 => MDB2_ERROR_ACCESS_VIOLATION,
-                    1046 => MDB2_ERROR_NODBSELECTED,
-                    1048 => MDB2_ERROR_CONSTRAINT,
-                    1049 => MDB2_ERROR_NOSUCHDB,
-                    1050 => MDB2_ERROR_ALREADY_EXISTS,
-                    1051 => MDB2_ERROR_NOSUCHTABLE,
-                    1054 => MDB2_ERROR_NOSUCHFIELD,
-                    1060 => MDB2_ERROR_ALREADY_EXISTS,
-                    1061 => MDB2_ERROR_ALREADY_EXISTS,
-                    1062 => MDB2_ERROR_ALREADY_EXISTS,
-                    1064 => MDB2_ERROR_SYNTAX,
-                    1067 => MDB2_ERROR_INVALID,
-                    1072 => MDB2_ERROR_NOT_FOUND,
-                    1086 => MDB2_ERROR_ALREADY_EXISTS,
-                    1091 => MDB2_ERROR_NOT_FOUND,
-                    1100 => MDB2_ERROR_NOT_LOCKED,
-                    1109 => MDB2_ERROR_NOT_FOUND,
-                    1125 => MDB2_ERROR_ALREADY_EXISTS,
-                    1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
-                    1138 => MDB2_ERROR_INVALID,
-                    1142 => MDB2_ERROR_ACCESS_VIOLATION,
-                    1143 => MDB2_ERROR_ACCESS_VIOLATION,
-                    1146 => MDB2_ERROR_NOSUCHTABLE,
-                    1149 => MDB2_ERROR_SYNTAX,
-                    1169 => MDB2_ERROR_CONSTRAINT,
-                    1176 => MDB2_ERROR_NOT_FOUND,
-                    1177 => MDB2_ERROR_NOSUCHTABLE,
-                    1213 => MDB2_ERROR_DEADLOCK,
-                    1216 => MDB2_ERROR_CONSTRAINT,
-                    1217 => MDB2_ERROR_CONSTRAINT,
-                    1227 => MDB2_ERROR_ACCESS_VIOLATION,
-                    1235 => MDB2_ERROR_CANNOT_CREATE,
-                    1299 => MDB2_ERROR_INVALID_DATE,
-                    1300 => MDB2_ERROR_INVALID,
-                    1304 => MDB2_ERROR_ALREADY_EXISTS,
-                    1305 => MDB2_ERROR_NOT_FOUND,
-                    1306 => MDB2_ERROR_CANNOT_DROP,
-                    1307 => MDB2_ERROR_CANNOT_CREATE,
-                    1334 => MDB2_ERROR_CANNOT_ALTER,
-                    1339 => MDB2_ERROR_NOT_FOUND,
-                    1356 => MDB2_ERROR_INVALID,
-                    1359 => MDB2_ERROR_ALREADY_EXISTS,
-                    1360 => MDB2_ERROR_NOT_FOUND,
-                    1363 => MDB2_ERROR_NOT_FOUND,
-                    1365 => MDB2_ERROR_DIVZERO,
-                    1451 => MDB2_ERROR_CONSTRAINT,
-                    1452 => MDB2_ERROR_CONSTRAINT,
-                    1542 => MDB2_ERROR_CANNOT_DROP,
-                    1546 => MDB2_ERROR_CONSTRAINT,
-                    1582 => MDB2_ERROR_CONSTRAINT,
-                    2003 => MDB2_ERROR_CONNECT_FAILED,
-                    2019 => MDB2_ERROR_INVALID,
-                );
-            }
-            if ($this->options['portability'] & MDB2_PORTABILITY_ERRORS) {
-                $ecode_map[1022] = MDB2_ERROR_CONSTRAINT;
-                $ecode_map[1048] = MDB2_ERROR_CONSTRAINT_NOT_NULL;
-                $ecode_map[1062] = MDB2_ERROR_CONSTRAINT;
-            } else {
-                // Doing this in case mode changes during runtime.
-                $ecode_map[1022] = MDB2_ERROR_ALREADY_EXISTS;
-                $ecode_map[1048] = MDB2_ERROR_CONSTRAINT;
-                $ecode_map[1062] = MDB2_ERROR_ALREADY_EXISTS;
-            }
-            if (isset($ecode_map[$native_code])) {
-                $error = $ecode_map[$native_code];
-            }
-        }
-        return array($error, $native_code, $native_msg);
-    }
-
-    // }}}
-    // {{{ escape()
-
-    /**
-     * Quotes a string so it can be safely used in a query. It will quote
-     * the text so it can safely be used within a query.
-     *
-     * @param   string  the input string to quote
-     * @param   bool    escape wildcards
-     *
-     * @return  string  quoted string
-     *
-     * @access  public
-     */
-    function escape($text, $escape_wildcards = false)
-    {
-        if ($escape_wildcards) {
-            $text = $this->escapePattern($text);
-        }
-        $connection = $this->getConnection();
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-        $text = @mysql_real_escape_string($text, $connection);
-        return $text;
-    }
-
-    // }}}
-    // {{{ beginTransaction()
-
-    /**
-     * Start a transaction or set a savepoint.
-     *
-     * @param   string  name of a savepoint to set
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function beginTransaction($savepoint = null)
-    {
-        $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
-        $this->_getServerCapabilities();
-        if (!is_null($savepoint)) {
-            if (!$this->supports('savepoints')) {
-                return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                    'savepoints are not supported', __FUNCTION__);
-            }
-            if (!$this->in_transaction) {
-                return $this->raiseError(MDB2_ERROR_INVALID, null, null,
-                    'savepoint cannot be released when changes are auto committed', __FUNCTION__);
-            }
-            $query = 'SAVEPOINT '.$savepoint;
-            return $this->_doQuery($query, true);
-        } elseif ($this->in_transaction) {
-            return MDB2_OK;  //nothing to do
-        }
-        if (!$this->destructor_registered && $this->opened_persistent) {
-            $this->destructor_registered = true;
-            register_shutdown_function('MDB2_closeOpenTransactions');
-        }
-        $query = $this->start_transaction ? 'START TRANSACTION' : 'SET AUTOCOMMIT = 0';
-        $result =& $this->_doQuery($query, true);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        $this->in_transaction = true;
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ commit()
-
-    /**
-     * Commit the database changes done during a transaction that is in
-     * progress or release a savepoint. This function may only be called when
-     * auto-committing is disabled, otherwise it will fail. Therefore, a new
-     * transaction is implicitly started after committing the pending changes.
-     *
-     * @param   string  name of a savepoint to release
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function commit($savepoint = null)
-    {
-        $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
-        if (!$this->in_transaction) {
-            return $this->raiseError(MDB2_ERROR_INVALID, null, null,
-                'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
-        }
-        if (!is_null($savepoint)) {
-            if (!$this->supports('savepoints')) {
-                return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                    'savepoints are not supported', __FUNCTION__);
-            }
-            $server_info = $this->getServerVersion();
-            if (version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '5.0.3', '<')) {
-                return MDB2_OK;
-            }
-            $query = 'RELEASE SAVEPOINT '.$savepoint;
-            return $this->_doQuery($query, true);
-        }
-
-        if (!$this->supports('transactions')) {
-            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'transactions are not supported', __FUNCTION__);
-        }
-
-        $result =& $this->_doQuery('COMMIT', true);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        if (!$this->start_transaction) {
-            $query = 'SET AUTOCOMMIT = 1';
-            $result =& $this->_doQuery($query, true);
-            if (PEAR::isError($result)) {
-                return $result;
-            }
-        }
-        $this->in_transaction = false;
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ rollback()
-
-    /**
-     * Cancel any database changes done during a transaction or since a specific
-     * savepoint that is in progress. This function may only be called when
-     * auto-committing is disabled, otherwise it will fail. Therefore, a new
-     * transaction is implicitly started after canceling the pending changes.
-     *
-     * @param   string  name of a savepoint to rollback to
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function rollback($savepoint = null)
-    {
-        $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
-        if (!$this->in_transaction) {
-            return $this->raiseError(MDB2_ERROR_INVALID, null, null,
-                'rollback cannot be done changes are auto committed', __FUNCTION__);
-        }
-        if (!is_null($savepoint)) {
-            if (!$this->supports('savepoints')) {
-                return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                    'savepoints are not supported', __FUNCTION__);
-            }
-            $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
-            return $this->_doQuery($query, true);
-        }
-
-        $query = 'ROLLBACK';
-        $result =& $this->_doQuery($query, true);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        if (!$this->start_transaction) {
-            $query = 'SET AUTOCOMMIT = 1';
-            $result =& $this->_doQuery($query, true);
-            if (PEAR::isError($result)) {
-                return $result;
-            }
-        }
-        $this->in_transaction = false;
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ function setTransactionIsolation()
-
-    /**
-     * Set the transacton isolation level.
-     *
-     * @param   string  standard isolation level
-     *                  READ UNCOMMITTED (allows dirty reads)
-     *                  READ COMMITTED (prevents dirty reads)
-     *                  REPEATABLE READ (prevents nonrepeatable reads)
-     *                  SERIALIZABLE (prevents phantom reads)
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     * @since   2.1.1
-     */
-    static function setTransactionIsolation($isolation, $options = array())
-    {
-        $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
-        if (!$this->supports('transactions')) {
-            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'transactions are not supported', __FUNCTION__);
-        }
-        switch ($isolation) {
-        case 'READ UNCOMMITTED':
-        case 'READ COMMITTED':
-        case 'REPEATABLE READ':
-        case 'SERIALIZABLE':
-            break;
-        default:
-            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'isolation level is not supported: '.$isolation, __FUNCTION__);
-        }
-
-        $query = "SET SESSION TRANSACTION ISOLATION LEVEL $isolation";
-        return $this->_doQuery($query, true);
-    }
-
-    // }}}
-    // {{{ _doConnect()
-
-    /**
-     * do the grunt work of the connect
-     *
-     * @return connection on success or MDB2 Error Object on failure
-     * @access protected
-     */
-    function _doConnect($username, $password, $persistent = false)
-    {
-        if (!PEAR::loadExtension($this->phptype)) {
-            return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
-        }
-
-        $params = array();
-        if ($this->dsn['protocol'] && $this->dsn['protocol'] == 'unix') {
-            $params[0] = ':' . $this->dsn['socket'];
-        } else {
-            $params[0] = $this->dsn['hostspec'] ? $this->dsn['hostspec']
-                         : 'localhost';
-            if ($this->dsn['port']) {
-                $params[0].= ':' . $this->dsn['port'];
-            }
-        }
-        $params[] = $username ? $username : null;
-        $params[] = $password ? $password : null;
-        if (!$persistent) {
-            if ($this->_isNewLinkSet()) {
-                $params[] = true;
-            } else {
-                $params[] = false;
-            }
-        }
-        if (version_compare(phpversion(), '4.3.0', '>=')) {
-            $params[] = isset($this->dsn['client_flags'])
-                ? $this->dsn['client_flags'] : null;
-        }
-        $connect_function = $persistent ? 'mysql_pconnect' : 'mysql_connect';
-
-        $connection = @call_user_func_array($connect_function, $params);
-        if (!$connection) {
-            if (($err = @mysql_error()) != '') {
-                return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
-                    $err, __FUNCTION__);
-            } else {
-                return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
-                    'unable to establish a connection', __FUNCTION__);
-            }
-        }
-
-        if (!empty($this->dsn['charset'])) {
-            $result = $this->setCharset($this->dsn['charset'], $connection);
-            if (PEAR::isError($result)) {
-                $this->disconnect(false);
-                return $result;
-            }
-        }
-
-        return $connection;
-    }
-
-    // }}}
-    // {{{ connect()
-
-    /**
-     * Connect to the database
-     *
-     * @return MDB2_OK on success, MDB2 Error Object on failure
-     * @access public
-     */
-    function connect()
-    {
-        if (is_resource($this->connection)) {
-            //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
-            if (MDB2::areEquals($this->connected_dsn, $this->dsn)
-                && $this->opened_persistent == $this->options['persistent']
-            ) {
-                return MDB2_OK;
-            }
-            $this->disconnect(false);
-        }
-
-        $connection = $this->_doConnect(
-            $this->dsn['username'],
-            $this->dsn['password'],
-            $this->options['persistent']
-        );
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-
-        $this->connection = $connection;
-        $this->connected_dsn = $this->dsn;
-        $this->connected_database_name = '';
-        $this->opened_persistent = $this->options['persistent'];
-        $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
-
-        if ($this->database_name) {
-            if ($this->database_name != $this->connected_database_name) {
-                if (!@mysql_select_db($this->database_name, $connection)) {
-                    $err = $this->raiseError(null, null, null,
-                        'Could not select the database: '.$this->database_name, __FUNCTION__);
-                    return $err;
-                }
-                $this->connected_database_name = $this->database_name;
-            }
-        }
-
-        $this->_getServerCapabilities();
-
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ setCharset()
-
-    /**
-     * Set the charset on the current connection
-     *
-     * @param string    charset (or array(charset, collation))
-     * @param resource  connection handle
-     *
-     * @return true on success, MDB2 Error Object on failure
-     */
-    function setCharset($charset, $connection = null)
-    {
-        if (is_null($connection)) {
-            $connection = $this->getConnection();
-            if (PEAR::isError($connection)) {
-                return $connection;
-            }
-        }
-        $collation = null;
-        if (is_array($charset) && 2 == count($charset)) {
-            $collation = array_pop($charset);
-            $charset   = array_pop($charset);
-        }
-        $client_info = mysql_get_client_info();
-        if (function_exists('mysql_set_charset') && version_compare($client_info, '5.0.6')) {
-            if (!$result = mysql_set_charset($charset, $connection)) {
-                $err =& $this->raiseError(null, null, null,
-                    'Could not set client character set', __FUNCTION__);
-                return $err;
-            }
-            return $result;
-        }
-        $query = "SET NAMES '".mysql_real_escape_string($charset, $connection)."'";
-        if (!is_null($collation)) {
-            $query .= " COLLATE '".mysqli_real_escape_string($connection, $collation)."'";
-        }
-        return $this->_doQuery($query, true, $connection);
-    }
-
-    // }}}
-    // {{{ databaseExists()
-
-    /**
-     * check if given database name is exists?
-     *
-     * @param string $name    name of the database that should be checked
-     *
-     * @return mixed true/false on success, a MDB2 error on failure
-     * @access public
-     */
-    function databaseExists($name)
-    {
-        $connection = $this->_doConnect($this->dsn['username'],
-                                        $this->dsn['password'],
-                                        $this->options['persistent']);
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-
-        $result = @mysql_select_db($name, $connection);
-        @mysql_close($connection);
-
-        return $result;
-    }
-
-    // }}}
-    // {{{ disconnect()
-
-    /**
-     * Log out and disconnect from the database.
-     *
-     * @param  boolean $force if the disconnect should be forced even if the
-     *                        connection is opened persistently
-     * @return mixed true on success, false if not connected and error
-     *                object on error
-     * @access public
-     */
-    function disconnect($force = true)
-    {
-        if (is_resource($this->connection)) {
-            if ($this->in_transaction) {
-                $dsn = $this->dsn;
-                $database_name = $this->database_name;
-                $persistent = $this->options['persistent'];
-                $this->dsn = $this->connected_dsn;
-                $this->database_name = $this->connected_database_name;
-                $this->options['persistent'] = $this->opened_persistent;
-                $this->rollback();
-                $this->dsn = $dsn;
-                $this->database_name = $database_name;
-                $this->options['persistent'] = $persistent;
-            }
-
-            if (!$this->opened_persistent || $force) {
-                $ok = @mysql_close($this->connection);
-                if (!$ok) {
-                    return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
-                           null, null, null, __FUNCTION__);
-                }
-            }
-        } else {
-            return false;
-        }
-        return parent::disconnect($force);
-    }
-
-    // }}}
-    // {{{ standaloneQuery()
-
-   /**
-     * execute a query as DBA
-     *
-     * @param string $query the SQL query
-     * @param mixed   $types  array that contains the types of the columns in
-     *                        the result set
-     * @param boolean $is_manip  if the query is a manipulation query
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function &standaloneQuery($query, $types = null, $is_manip = false)
-    {
-        $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
-        $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
-        $connection = $this->_doConnect($user, $pass, $this->options['persistent']);
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-
-        $offset = $this->offset;
-        $limit = $this->limit;
-        $this->offset = $this->limit = 0;
-        $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
-        
-        $result =& $this->_doQuery($query, $is_manip, $connection, $this->database_name);
-        if (!PEAR::isError($result)) {
-            $result = $this->_affectedRows($connection, $result);
-        }
-
-        @mysql_close($connection);
-        return $result;
-    }
-
-    // }}}
-    // {{{ _doQuery()
-
-    /**
-     * Execute a query
-     * @param string $query  query
-     * @param boolean $is_manip  if the query is a manipulation query
-     * @param resource $connection
-     * @param string $database_name
-     * @return result or error object
-     * @access protected
-     */
-    function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
-    {
-        $this->last_query = $query;
-        $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
-        if ($result) {
-            if (PEAR::isError($result)) {
-                return $result;
-            }
-            $query = $result;
-        }
-        if ($this->options['disable_query']) {
-            $result = $is_manip ? 0 : null;
-            return $result;
-        }
-
-        if (is_null($connection)) {
-            $connection = $this->getConnection();
-            if (PEAR::isError($connection)) {
-                return $connection;
-            }
-        }
-        if (is_null($database_name)) {
-            $database_name = $this->database_name;
-        }
-
-        if ($database_name) {
-            if ($database_name != $this->connected_database_name) {
-                if (!@mysql_select_db($database_name, $connection)) {
-                    $err = $this->raiseError(null, null, null,
-                        'Could not select the database: '.$database_name, __FUNCTION__);
-                    return $err;
-                }
-                $this->connected_database_name = $database_name;
-            }
-        }
-
-        $function = $this->options['result_buffering']
-            ? 'mysql_query' : 'mysql_unbuffered_query';
-        $result = @$function($query, $connection);
-        if (!$result) {
-            $err =$this->raiseError(null, null, null,
-                'Could not execute statement', __FUNCTION__);
-            return $err;
-        }
-
-        $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
-        return $result;
-    }
-
-    // }}}
-    // {{{ _affectedRows()
-
-    /**
-     * Returns the number of rows affected
-     *
-     * @param resource $result
-     * @param resource $connection
-     * @return mixed MDB2 Error Object or the number of rows affected
-     * @access private
-     */
-    function _affectedRows($connection, $result = null)
-    {
-        if (is_null($connection)) {
-            $connection = $this->getConnection();
-            if (PEAR::isError($connection)) {
-                return $connection;
-            }
-        }
-        return @mysql_affected_rows($connection);
-    }
-
-    // }}}
-    // {{{ _modifyQuery()
-
-    /**
-     * Changes a query string for various DBMS specific reasons
-     *
-     * @param string $query  query to modify
-     * @param boolean $is_manip  if it is a DML query
-     * @param integer $limit  limit the number of rows
-     * @param integer $offset  start reading from given offset
-     * @return string modified query
-     * @access protected
-     */
-    function _modifyQuery($query, $is_manip, $limit, $offset)
-    {
-        if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {
-            // "DELETE FROM table" gives 0 affected rows in MySQL.
-            // This little hack lets you know how many rows were deleted.
-            if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
-                $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
-                                      'DELETE FROM \1 WHERE 1=1', $query);
-            }
-        }
-        if ($limit > 0
-            && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
-        ) {
-            $query = rtrim($query);
-            if (substr($query, -1) == ';') {
-                $query = substr($query, 0, -1);
-            }
-
-            // LIMIT doesn't always come last in the query
-            // @see http://dev.mysql.com/doc/refman/5.0/en/select.html
-            $after = '';
-            if (preg_match('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', $query, $matches)) {
-                $after = $matches[0];
-                $query = preg_replace('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', '', $query);
-            } elseif (preg_match('/(\s+FOR\s+UPDATE\s*)$/i', $query, $matches)) {
-               $after = $matches[0];
-               $query = preg_replace('/(\s+FOR\s+UPDATE\s*)$/im', '', $query);
-            } elseif (preg_match('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', $query, $matches)) {
-               $after = $matches[0];
-               $query = preg_replace('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', '', $query);
-            }
-
-            if ($is_manip) {
-                return $query . " LIMIT $limit" . $after;
-            } else {
-                return $query . " LIMIT $offset, $limit" . $after;
-            }
-        }
-        return $query;
-    }
-
-    // }}}
-    // {{{ getServerVersion()
-
-    /**
-     * return version information about the server
-     *
-     * @param bool   $native  determines if the raw version string should be returned
-     * @return mixed array/string with version information or MDB2 error object
-     * @access public
-     */
-    function getServerVersion($native = false)
-    {
-        $connection = $this->getConnection();
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-        if ($this->connected_server_info) {
-            $server_info = $this->connected_server_info;
-        } else {
-            $server_info = @mysql_get_server_info($connection);
-        }
-        if (!$server_info) {
-            return $this->raiseError(null, null, null,
-                'Could not get server information', __FUNCTION__);
-        }
-        // cache server_info
-        $this->connected_server_info = $server_info;
-        if (!$native) {
-            $tmp = explode('.', $server_info, 3);
-            if (isset($tmp[2]) && strpos($tmp[2], '-')) {
-                $tmp2 = explode('-', @$tmp[2], 2);
-            } else {
-                $tmp2[0] = isset($tmp[2]) ? $tmp[2] : null;
-                $tmp2[1] = null;
-            }
-            $server_info = array(
-                'major' => isset($tmp[0]) ? $tmp[0] : null,
-                'minor' => isset($tmp[1]) ? $tmp[1] : null,
-                'patch' => $tmp2[0],
-                'extra' => $tmp2[1],
-                'native' => $server_info,
-            );
-        }
-        return $server_info;
-    }
-
-    // }}}
-    // {{{ _getServerCapabilities()
-
-    /**
-     * Fetch some information about the server capabilities
-     * (transactions, subselects, prepared statements, etc).
-     *
-     * @access private
-     */
-    function _getServerCapabilities()
-    {
-        if (!$this->server_capabilities_checked) {
-            $this->server_capabilities_checked = true;
-
-            //set defaults
-            $this->supported['sub_selects'] = 'emulated';
-            $this->supported['prepared_statements'] = 'emulated';
-            $this->supported['triggers'] = false;
-            $this->start_transaction = false;
-            $this->varchar_max_length = 255;
-            
-            $server_info = $this->getServerVersion();
-            if (is_array($server_info)) {
-                $server_version = $server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'];
-
-                if (!version_compare($server_version, '4.1.0', '<')) {
-                    $this->supported['sub_selects'] = true;
-                    $this->supported['prepared_statements'] = true;
-                }
-
-                // SAVEPOINTs were introduced in MySQL 4.0.14 and 4.1.1 (InnoDB)
-                if (version_compare($server_version, '4.1.0', '>=')) {
-                    if (version_compare($server_version, '4.1.1', '<')) {
-                        $this->supported['savepoints'] = false;
-                    }
-                } elseif (version_compare($server_version, '4.0.14', '<')) {
-                    $this->supported['savepoints'] = false;
-                }
-
-                if (!version_compare($server_version, '4.0.11', '<')) {
-                    $this->start_transaction = true;
-                }
-
-                if (!version_compare($server_version, '5.0.3', '<')) {
-                    $this->varchar_max_length = 65532;
-                }
-
-                if (!version_compare($server_version, '5.0.2', '<')) {
-                    $this->supported['triggers'] = true;
-                }
-            }
-        }
-    }
-
-    // }}}
-    // {{{ function _skipUserDefinedVariable($query, $position)
-
-    /**
-     * Utility method, used by prepare() to avoid misinterpreting MySQL user 
-     * defined variables (SELECT @x:=5) for placeholders.
-     * Check if the placeholder is a false positive, i.e. if it is an user defined
-     * variable instead. If so, skip it and advance the position, otherwise
-     * return the current position, which is valid
-     *
-     * @param string $query
-     * @param integer $position current string cursor position
-     * @return integer $new_position
-     * @access protected
-     */
-    function _skipUserDefinedVariable($query, $position)
-    {
-        $found = strpos(strrev(substr($query, 0, $position)), '@');
-        if ($found === false) {
-            return $position;
-        }
-        $pos = strlen($query) - strlen(substr($query, $position)) - $found - 1;
-        $substring = substr($query, $pos, $position - $pos + 2);
-        if (preg_match('/^@\w+\s*:=$/', $substring)) {
-            return $position + 1; //found an user defined variable: skip it
-        }
-        return $position;
-    }
-
-    // }}}
-    // {{{ prepare()
-
-    /**
-     * Prepares a query for multiple execution with execute().
-     * With some database backends, this is emulated.
-     * prepare() requires a generic query as string like
-     * 'INSERT INTO numbers VALUES(?,?)' or
-     * 'INSERT INTO numbers VALUES(:foo,:bar)'.
-     * The ? and :name and are placeholders which can be set using
-     * bindParam() and the query can be sent off using the execute() method.
-     * The allowed format for :name can be set with the 'bindname_format' option.
-     *
-     * @param string $query the query to prepare
-     * @param mixed   $types  array that contains the types of the placeholders
-     * @param mixed   $result_types  array that contains the types of the columns in
-     *                        the result set or MDB2_PREPARE_RESULT, if set to
-     *                        MDB2_PREPARE_MANIP the query is handled as a manipulation query
-     * @param mixed   $lobs   key (field) value (parameter) pair for all lob placeholders
-     * @return mixed resource handle for the prepared query on success, a MDB2
-     *        error on failure
-     * @access public
-     * @see bindParam, execute
-     */
-    function &prepare($query, $types = null, $result_types = null, $lobs = array())
-    {
-        if ($this->options['emulate_prepared']
-            || $this->supported['prepared_statements'] !== true
-        ) {
-            $obj =& parent::prepare($query, $types, $result_types, $lobs);
-            return $obj;
-        }
-        $is_manip = ($result_types === MDB2_PREPARE_MANIP);
-        $offset = $this->offset;
-        $limit = $this->limit;
-        $this->offset = $this->limit = 0;
-        $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
-        $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
-        if ($result) {
-            if (PEAR::isError($result)) {
-                return $result;
-            }
-            $query = $result;
-        }
-        $placeholder_type_guess = $placeholder_type = null;
-        $question = '?';
-        $colon = ':';
-        $positions = array();
-        $position = 0;
-        while ($position < strlen($query)) {
-            $q_position = strpos($query, $question, $position);
-            $c_position = strpos($query, $colon, $position);
-            if ($q_position && $c_position) {
-                $p_position = min($q_position, $c_position);
-            } elseif ($q_position) {
-                $p_position = $q_position;
-            } elseif ($c_position) {
-                $p_position = $c_position;
-            } else {
-                break;
-            }
-            if (is_null($placeholder_type)) {
-                $placeholder_type_guess = $query[$p_position];
-            }
-            
-            $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
-            if (PEAR::isError($new_pos)) {
-                return $new_pos;
-            }
-            if ($new_pos != $position) {
-                $position = $new_pos;
-                continue; //evaluate again starting from the new position
-            }
-            
-            //make sure this is not part of an user defined variable
-            $new_pos = $this->_skipUserDefinedVariable($query, $position);
-            if ($new_pos != $position) {
-                $position = $new_pos;
-                continue; //evaluate again starting from the new position
-            }
-
-            if ($query[$position] == $placeholder_type_guess) {
-                if (is_null($placeholder_type)) {
-                    $placeholder_type = $query[$p_position];
-                    $question = $colon = $placeholder_type;
-                }
-                if ($placeholder_type == ':') {
-                    $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
-                    $parameter = preg_replace($regexp, '\\1', $query);
-                    if ($parameter === '') {
-                        $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
-                            'named parameter name must match "bindname_format" option', __FUNCTION__);
-                        return $err;
-                    }
-                    $positions[$p_position] = $parameter;
-                    $query = substr_replace($query, '?', $position, strlen($parameter)+1);
-                } else {
-                    $positions[$p_position] = count($positions);
-                }
-                $position = $p_position + 1;
-            } else {
-                $position = $p_position;
-            }
-        }
-        $connection = $this->getConnection();
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-        static $prep_statement_counter = 1;
-        $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand()));
-        $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);
-        $query = "PREPARE $statement_name FROM ".$this->quote($query, 'text');
-        $statement =& $this->_doQuery($query, true, $connection);
-        if (PEAR::isError($statement)) {
-            return $statement;
-        }
-
-        $class_name = 'MDB2_Statement_'.$this->phptype;
-        $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
-        $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
-        return $obj;
-    }
-
-    // }}}
-    // {{{ replace()
-
-    /**
-     * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
-     * query, except that if there is already a row in the table with the same
-     * key field values, the old row is deleted before the new row is inserted.
-     *
-     * The REPLACE type of query does not make part of the SQL standards. Since
-     * practically only MySQL implements it natively, this type of query is
-     * emulated through this method for other DBMS using standard types of
-     * queries inside a transaction to assure the atomicity of the operation.
-     *
-     * @access public
-     *
-     * @param string $table name of the table on which the REPLACE query will
-     *  be executed.
-     * @param array $fields associative array that describes the fields and the
-     *  values that will be inserted or updated in the specified table. The
-     *  indexes of the array are the names of all the fields of the table. The
-     *  values of the array are also associative arrays that describe the
-     *  values and other properties of the table fields.
-     *
-     *  Here follows a list of field properties that need to be specified:
-     *
-     *    value:
-     *          Value to be assigned to the specified field. This value may be
-     *          of specified in database independent type format as this
-     *          function can perform the necessary datatype conversions.
-     *
-     *    Default:
-     *          this property is required unless the Null property
-     *          is set to 1.
-     *
-     *    type
-     *          Name of the type of the field. Currently, all types Metabase
-     *          are supported except for clob and blob.
-     *
-     *    Default: no type conversion
-     *
-     *    null
-     *          Boolean property that indicates that the value for this field
-     *          should be set to null.
-     *
-     *          The default value for fields missing in INSERT queries may be
-     *          specified the definition of a table. Often, the default value
-     *          is already null, but since the REPLACE may be emulated using
-     *          an UPDATE query, make sure that all fields of the table are
-     *          listed in this function argument array.
-     *
-     *    Default: 0
-     *
-     *    key
-     *          Boolean property that indicates that this field should be
-     *          handled as a primary key or at least as part of the compound
-     *          unique index of the table that will determine the row that will
-     *          updated if it exists or inserted a new row otherwise.
-     *
-     *          This function will fail if no key field is specified or if the
-     *          value of a key field is set to null because fields that are
-     *          part of unique index they may not be null.
-     *
-     *    Default: 0
-     *
-     * @see http://dev.mysql.com/doc/refman/5.0/en/replace.html
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     */
-    function replace($table, $fields)
-    {
-        $count = count($fields);
-        $query = $values = '';
-        $keys = $colnum = 0;
-        for (reset($fields); $colnum < $count; next($fields), $colnum++) {
-            $name = key($fields);
-            if ($colnum > 0) {
-                $query .= ',';
-                $values.= ',';
-            }
-            $query.= $this->quoteIdentifier($name, true);
-            if (isset($fields[$name]['null']) && $fields[$name]['null']) {
-                $value = 'NULL';
-            } else {
-                $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
-                $value = $this->quote($fields[$name]['value'], $type);
-                if (PEAR::isError($value)) {
-                    return $value;
-                }
-            }
-            $values.= $value;
-            if (isset($fields[$name]['key']) && $fields[$name]['key']) {
-                if ($value === 'NULL') {
-                    return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
-                        'key value '.$name.' may not be NULL', __FUNCTION__);
-                }
-                $keys++;
-            }
-        }
-        if ($keys == 0) {
-            return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
-                'not specified which fields are keys', __FUNCTION__);
-        }
-
-        $connection = $this->getConnection();
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-
-        $table = $this->quoteIdentifier($table, true);
-        $query = "REPLACE INTO $table ($query) VALUES ($values)";
-        $result =& $this->_doQuery($query, true, $connection);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        return $this->_affectedRows($connection, $result);
-    }
-
-    // }}}
-    // {{{ nextID()
-
-    /**
-     * Returns the next free id of a sequence
-     *
-     * @param string $seq_name name of the sequence
-     * @param boolean $ondemand when true the sequence is
-     *                          automatic created, if it
-     *                          not exists
-     *
-     * @return mixed MDB2 Error Object or id
-     * @access public
-     */
-    function nextID($seq_name, $ondemand = true)
-    {
-        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
-        $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
-        $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
-        $this->pushErrorHandling(PEAR_ERROR_RETURN);
-        $this->expectError(MDB2_ERROR_NOSUCHTABLE);
-        $result =& $this->_doQuery($query, true);
-        $this->popExpect();
-        $this->popErrorHandling();
-        if (PEAR::isError($result)) {
-            if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
-                $this->loadModule('Manager', null, true);
-                $result = $this->manager->createSequence($seq_name);
-                if (PEAR::isError($result)) {
-                    return $this->raiseError($result, null, null,
-                        'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
-                } else {
-                    return $this->nextID($seq_name, false);
-                }
-            }
-            return $result;
-        }
-        $value = $this->lastInsertID();
-        if (is_numeric($value)) {
-            $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
-            $result =& $this->_doQuery($query, true);
-            if (PEAR::isError($result)) {
-                $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
-            }
-        }
-        return $value;
-    }
-
-    // }}}
-    // {{{ lastInsertID()
-
-    /**
-     * Returns the autoincrement ID if supported or $id or fetches the current
-     * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
-     *
-     * @param string $table name of the table into which a new row was inserted
-     * @param string $field name of the field into which a new row was inserted
-     * @return mixed MDB2 Error Object or id
-     * @access public
-     */
-    function lastInsertID($table = null, $field = null)
-    {
-        // not using mysql_insert_id() due to http://pear.php.net/bugs/bug.php?id=8051
-        return $this->queryOne('SELECT LAST_INSERT_ID()', 'integer');
-    }
-
-    // }}}
-    // {{{ currID()
-
-    /**
-     * Returns the current id of a sequence
-     *
-     * @param string $seq_name name of the sequence
-     * @return mixed MDB2 Error Object or id
-     * @access public
-     */
-    function currID($seq_name)
-    {
-        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
-        $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
-        $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
-        return $this->queryOne($query, 'integer');
-    }
-}
-
-/**
- * MDB2 MySQL result driver
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Result_mysql extends MDB2_Result_Common
-{
-    // }}}
-    // {{{ fetchRow()
-
-    /**
-     * Fetch a row and insert the data into an existing array.
-     *
-     * @param int       $fetchmode  how the array data should be indexed
-     * @param int    $rownum    number of the row where the data can be found
-     * @return int data array on success, a MDB2 error on failure
-     * @access public
-     */
-    function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
-    {
-        if (!is_null($rownum)) {
-            $seek = $this->seek($rownum);
-            if (PEAR::isError($seek)) {
-                return $seek;
-            }
-        }
-        if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
-            $fetchmode = $this->db->fetchmode;
-        }
-        if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
-            $row = @mysql_fetch_assoc($this->result);
-            if (is_array($row)
-                && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
-            ) {
-                $row = array_change_key_case($row, $this->db->options['field_case']);
-            }
-        } else {
-           $row = @mysql_fetch_row($this->result);
-        }
-
-        if (!$row) {
-            if ($this->result === false) {
-                $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                    'resultset has already been freed', __FUNCTION__);
-                return $err;
-            }
-            $null = null;
-            return $null;
-        }
-        $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
-        $rtrim = false;
-        if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
-            if (empty($this->types)) {
-                $mode += MDB2_PORTABILITY_RTRIM;
-            } else {
-                $rtrim = true;
-            }
-        }
-        if ($mode) {
-            $this->db->_fixResultArrayValues($row, $mode);
-        }
-        if (!empty($this->types)) {
-            $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
-        }
-        if (!empty($this->values)) {
-            $this->_assignBindColumns($row);
-        }
-        if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
-            $object_class = $this->db->options['fetch_class'];
-            if ($object_class == 'stdClass') {
-                $row = (object) $row;
-            } else {
-                $row = new $object_class($row);
-            }
-        }
-        ++$this->rownum;
-        return $row;
-    }
-
-    // }}}
-    // {{{ _getColumnNames()
-
-    /**
-     * Retrieve the names of columns returned by the DBMS in a query result.
-     *
-     * @return  mixed   Array variable that holds the names of columns as keys
-     *                  or an MDB2 error on failure.
-     *                  Some DBMS may not return any columns when the result set
-     *                  does not contain any rows.
-     * @access private
-     */
-    function _getColumnNames()
-    {
-        $columns = array();
-        $numcols = $this->numCols();
-        if (PEAR::isError($numcols)) {
-            return $numcols;
-        }
-        for ($column = 0; $column < $numcols; $column++) {
-            $column_name = @mysql_field_name($this->result, $column);
-            $columns[$column_name] = $column;
-        }
-        if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $columns = array_change_key_case($columns, $this->db->options['field_case']);
-        }
-        return $columns;
-    }
-
-    // }}}
-    // {{{ numCols()
-
-    /**
-     * Count the number of columns returned by the DBMS in a query result.
-     *
-     * @return mixed integer value with the number of columns, a MDB2 error
-     *                       on failure
-     * @access public
-     */
-    function numCols()
-    {
-        $cols = @mysql_num_fields($this->result);
-        if (is_null($cols)) {
-            if ($this->result === false) {
-                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                    'resultset has already been freed', __FUNCTION__);
-            } elseif (is_null($this->result)) {
-                return count($this->types);
-            }
-            return $this->db->raiseError(null, null, null,
-                'Could not get column count', __FUNCTION__);
-        }
-        return $cols;
-    }
-
-    // }}}
-    // {{{ free()
-
-    /**
-     * Free the internal resources associated with result.
-     *
-     * @return boolean true on success, false if result is invalid
-     * @access public
-     */
-    function free()
-    {
-        if (is_resource($this->result) && $this->db->connection) {
-            $free = @mysql_free_result($this->result);
-            if ($free === false) {
-                return $this->db->raiseError(null, null, null,
-                    'Could not free result', __FUNCTION__);
-            }
-        }
-        $this->result = false;
-        return MDB2_OK;
-    }
-}
-
-/**
- * MDB2 MySQL buffered result driver
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_BufferedResult_mysql extends MDB2_Result_mysql
-{
-    // }}}
-    // {{{ seek()
-
-    /**
-     * Seek to a specific row in a result set
-     *
-     * @param int    $rownum    number of the row where the data can be found
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function seek($rownum = 0)
-    {
-        if ($this->rownum != ($rownum - 1) && !@mysql_data_seek($this->result, $rownum)) {
-            if ($this->result === false) {
-                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                    'resultset has already been freed', __FUNCTION__);
-            } elseif (is_null($this->result)) {
-                return MDB2_OK;
-            }
-            return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
-                'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
-        }
-        $this->rownum = $rownum - 1;
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ valid()
-
-    /**
-     * Check if the end of the result set has been reached
-     *
-     * @return mixed true or false on sucess, a MDB2 error on failure
-     * @access public
-     */
-    function valid()
-    {
-        $numrows = $this->numRows();
-        if (PEAR::isError($numrows)) {
-            return $numrows;
-        }
-        return $this->rownum < ($numrows - 1);
-    }
-
-    // }}}
-    // {{{ numRows()
-
-    /**
-     * Returns the number of rows in a result object
-     *
-     * @return mixed MDB2 Error Object or the number of rows
-     * @access public
-     */
-    function numRows()
-    {
-        $rows = @mysql_num_rows($this->result);
-        if (false === $rows) {
-            if (false === $this->result) {
-                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                    'resultset has already been freed', __FUNCTION__);
-            } elseif (is_null($this->result)) {
-                return 0;
-            }
-            return $this->db->raiseError(null, null, null,
-                'Could not get row count', __FUNCTION__);
-        }
-        return $rows;
-    }
-}
-
-/**
- * MDB2 MySQL statement driver
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Statement_mysql extends MDB2_Statement_Common
-{
-    // {{{ _execute()
-
-    /**
-     * Execute a prepared query statement helper method.
-     *
-     * @param mixed $result_class string which specifies which result class to use
-     * @param mixed $result_wrap_class string which specifies which class to wrap results in
-     *
-     * @return mixed MDB2_Result or integer (affected rows) on success,
-     *               a MDB2 error on failure
-     * @access private
-     */
-    function &_execute($result_class = true, $result_wrap_class = false)
-    {
-        if (is_null($this->statement)) {
-            $result =& parent::_execute($result_class, $result_wrap_class);
-            return $result;
-        }
-        $this->db->last_query = $this->query;
-        $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
-        if ($this->db->getOption('disable_query')) {
-            $result = $this->is_manip ? 0 : null;
-            return $result;
-        }
-
-        $connection = $this->db->getConnection();
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-
-        $query = 'EXECUTE '.$this->statement;
-        if (!empty($this->positions)) {
-            $parameters = array();
-            foreach ($this->positions as $parameter) {
-                if (!array_key_exists($parameter, $this->values)) {
-                    return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                        'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
-                }
-                $value = $this->values[$parameter];
-                $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
-                if (is_resource($value) || $type == 'clob' || $type == 'blob' && $this->db->options['lob_allow_url_include']) {
-                    if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
-                        if ($match[1] == 'file://') {
-                            $value = $match[2];
-                        }
-                        $value = @fopen($value, 'r');
-                        $close = true;
-                    }
-                    if (is_resource($value)) {
-                        $data = '';
-                        while (!@feof($value)) {
-                            $data.= @fread($value, $this->db->options['lob_buffer_length']);
-                        }
-                        if ($close) {
-                            @fclose($value);
-                        }
-                        $value = $data;
-                    }
-                }
-                $quoted = $this->db->quote($value, $type);
-                if (PEAR::isError($quoted)) {
-                    return $quoted;
-                }
-                $param_query = 'SET @'.$parameter.' = '.$quoted;
-                $result = $this->db->_doQuery($param_query, true, $connection);
-                if (PEAR::isError($result)) {
-                    return $result;
-                }
-            }
-            $query.= ' USING @'.implode(', @', array_values($this->positions));
-        }
-
-        $result = $this->db->_doQuery($query, $this->is_manip, $connection);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-
-        if ($this->is_manip) {
-            $affected_rows = $this->db->_affectedRows($connection, $result);
-            return $affected_rows;
-        }
-
-        $result =& $this->db->_wrapResult($result, $this->result_types,
-            $result_class, $result_wrap_class, $this->limit, $this->offset);
-        $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
-        return $result;
-    }
-
-    // }}}
-    // {{{ free()
-
-    /**
-     * Release resources allocated for the specified prepared query.
-     *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function free()
-    {
-        if (is_null($this->positions)) {
-            return $this->db->raiseError(MDB2_ERROR, null, null,
-                'Prepared statement has already been freed', __FUNCTION__);
-        }
-        $result = MDB2_OK;
-
-        if (!is_null($this->statement)) {
-            $connection = $this->db->getConnection();
-            if (PEAR::isError($connection)) {
-                return $connection;
-            }
-            $query = 'DEALLOCATE PREPARE '.$this->statement;
-            $result = $this->db->_doQuery($query, true, $connection);
-        }
-
-        parent::free();
-        return $result;
-    }
-}
-?>
\ No newline at end of file
+<?php\r
+// vim: set et ts=4 sw=4 fdm=marker:\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: mysql.php 302867 2010-08-29 11:22:07Z quipo $\r
+//\r
+\r
+/**\r
+ * MDB2 MySQL driver\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Driver_mysql extends MDB2_Driver_Common\r
+{\r
+    // {{{ properties\r
+\r
+    var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => '\\', 'escape_pattern' => '\\');\r
+\r
+    var $identifier_quoting = array('start' => '`', 'end' => '`', 'escape' => '`');\r
+\r
+    var $sql_comments = array(\r
+        array('start' => '-- ', 'end' => "\n", 'escape' => false),\r
+        array('start' => '#', 'end' => "\n", 'escape' => false),\r
+        array('start' => '/*', 'end' => '*/', 'escape' => false),\r
+    );\r
+\r
+    var $server_capabilities_checked = false;\r
+\r
+    var $start_transaction = false;\r
+\r
+    var $varchar_max_length = 255;\r
+\r
+    // }}}\r
+    // {{{ constructor\r
+\r
+    /**\r
+     * Constructor\r
+     */\r
+    function __construct()\r
+    {\r
+        parent::__construct();\r
+\r
+        $this->phptype = 'mysql';\r
+        $this->dbsyntax = 'mysql';\r
+\r
+        $this->supported['sequences'] = 'emulated';\r
+        $this->supported['indexes'] = true;\r
+        $this->supported['affected_rows'] = true;\r
+        $this->supported['transactions'] = false;\r
+        $this->supported['savepoints'] = false;\r
+        $this->supported['summary_functions'] = true;\r
+        $this->supported['order_by_text'] = true;\r
+        $this->supported['current_id'] = 'emulated';\r
+        $this->supported['limit_queries'] = true;\r
+        $this->supported['LOBs'] = true;\r
+        $this->supported['replace'] = true;\r
+        $this->supported['sub_selects'] = 'emulated';\r
+        $this->supported['triggers'] = false;\r
+        $this->supported['auto_increment'] = true;\r
+        $this->supported['primary_key'] = true;\r
+        $this->supported['result_introspection'] = true;\r
+        $this->supported['prepared_statements'] = 'emulated';\r
+        $this->supported['identifier_quoting'] = true;\r
+        $this->supported['pattern_escaping'] = true;\r
+        $this->supported['new_link'] = true;\r
+\r
+        $this->options['DBA_username'] = false;\r
+        $this->options['DBA_password'] = false;\r
+        $this->options['default_table_type'] = '';\r
+        $this->options['max_identifiers_length'] = 64;\r
+\r
+        $this->_reCheckSupportedOptions();\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _reCheckSupportedOptions()\r
+    \r
+    /**\r
+     * If the user changes certain options, other capabilities may depend\r
+     * on the new settings, so we need to check them (again).\r
+     *\r
+     * @access private\r
+     */\r
+    function _reCheckSupportedOptions()\r
+    {\r
+        $this->supported['transactions'] = $this->options['use_transactions'];\r
+        $this->supported['savepoints']   = $this->options['use_transactions'];\r
+        if ($this->options['default_table_type']) {\r
+            switch (strtoupper($this->options['default_table_type'])) {\r
+            case 'BLACKHOLE':\r
+            case 'MEMORY':\r
+            case 'ARCHIVE':\r
+            case 'CSV':\r
+            case 'HEAP':\r
+            case 'ISAM':\r
+            case 'MERGE':\r
+            case 'MRG_ISAM':\r
+            case 'ISAM':\r
+            case 'MRG_MYISAM':\r
+            case 'MYISAM':\r
+                $this->supported['savepoints']   = false;\r
+                $this->supported['transactions'] = false;\r
+                $this->warnings[] = $this->options['default_table_type'] .\r
+                    ' is not a supported default table type';\r
+                break;\r
+            }\r
+        }\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function setOption($option, $value)\r
+\r
+    /**\r
+     * set the option for the db class\r
+     *\r
+     * @param   string  option name\r
+     * @param   mixed   value for the option\r
+     *\r
+     * @return  mixed   MDB2_OK or MDB2 Error Object\r
+     *\r
+     * @access  public\r
+     */\r
+    function setOption($option, $value)\r
+    {\r
+        $res = parent::setOption($option, $value);\r
+        $this->_reCheckSupportedOptions();\r
+    }\r
+\r
+    // }}}\r
+    // {{{ errorInfo()\r
+\r
+    /**\r
+     * This method is used to collect information about an error\r
+     *\r
+     * @param integer $error\r
+     * @return array\r
+     * @access public\r
+     */\r
+    function errorInfo($error = null)\r
+    {\r
+        if ($this->connection) {\r
+            $native_code = @mysql_errno($this->connection);\r
+            $native_msg  = @mysql_error($this->connection);\r
+        } else {\r
+            $native_code = @mysql_errno();\r
+            $native_msg  = @mysql_error();\r
+        }\r
+        if (is_null($error)) {\r
+            static $ecode_map;\r
+            if (empty($ecode_map)) {\r
+                $ecode_map = array(\r
+                    1000 => MDB2_ERROR_INVALID, //hashchk\r
+                    1001 => MDB2_ERROR_INVALID, //isamchk\r
+                    1004 => MDB2_ERROR_CANNOT_CREATE,\r
+                    1005 => MDB2_ERROR_CANNOT_CREATE,\r
+                    1006 => MDB2_ERROR_CANNOT_CREATE,\r
+                    1007 => MDB2_ERROR_ALREADY_EXISTS,\r
+                    1008 => MDB2_ERROR_CANNOT_DROP,\r
+                    1009 => MDB2_ERROR_CANNOT_DROP,\r
+                    1010 => MDB2_ERROR_CANNOT_DROP,\r
+                    1011 => MDB2_ERROR_CANNOT_DELETE,\r
+                    1022 => MDB2_ERROR_ALREADY_EXISTS,\r
+                    1029 => MDB2_ERROR_NOT_FOUND,\r
+                    1032 => MDB2_ERROR_NOT_FOUND,\r
+                    1044 => MDB2_ERROR_ACCESS_VIOLATION,\r
+                    1045 => MDB2_ERROR_ACCESS_VIOLATION,\r
+                    1046 => MDB2_ERROR_NODBSELECTED,\r
+                    1048 => MDB2_ERROR_CONSTRAINT,\r
+                    1049 => MDB2_ERROR_NOSUCHDB,\r
+                    1050 => MDB2_ERROR_ALREADY_EXISTS,\r
+                    1051 => MDB2_ERROR_NOSUCHTABLE,\r
+                    1054 => MDB2_ERROR_NOSUCHFIELD,\r
+                    1060 => MDB2_ERROR_ALREADY_EXISTS,\r
+                    1061 => MDB2_ERROR_ALREADY_EXISTS,\r
+                    1062 => MDB2_ERROR_ALREADY_EXISTS,\r
+                    1064 => MDB2_ERROR_SYNTAX,\r
+                    1067 => MDB2_ERROR_INVALID,\r
+                    1072 => MDB2_ERROR_NOT_FOUND,\r
+                    1086 => MDB2_ERROR_ALREADY_EXISTS,\r
+                    1091 => MDB2_ERROR_NOT_FOUND,\r
+                    1100 => MDB2_ERROR_NOT_LOCKED,\r
+                    1109 => MDB2_ERROR_NOT_FOUND,\r
+                    1125 => MDB2_ERROR_ALREADY_EXISTS,\r
+                    1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW,\r
+                    1138 => MDB2_ERROR_INVALID,\r
+                    1142 => MDB2_ERROR_ACCESS_VIOLATION,\r
+                    1143 => MDB2_ERROR_ACCESS_VIOLATION,\r
+                    1146 => MDB2_ERROR_NOSUCHTABLE,\r
+                    1149 => MDB2_ERROR_SYNTAX,\r
+                    1169 => MDB2_ERROR_CONSTRAINT,\r
+                    1176 => MDB2_ERROR_NOT_FOUND,\r
+                    1177 => MDB2_ERROR_NOSUCHTABLE,\r
+                    1213 => MDB2_ERROR_DEADLOCK,\r
+                    1216 => MDB2_ERROR_CONSTRAINT,\r
+                    1217 => MDB2_ERROR_CONSTRAINT,\r
+                    1227 => MDB2_ERROR_ACCESS_VIOLATION,\r
+                    1235 => MDB2_ERROR_CANNOT_CREATE,\r
+                    1299 => MDB2_ERROR_INVALID_DATE,\r
+                    1300 => MDB2_ERROR_INVALID,\r
+                    1304 => MDB2_ERROR_ALREADY_EXISTS,\r
+                    1305 => MDB2_ERROR_NOT_FOUND,\r
+                    1306 => MDB2_ERROR_CANNOT_DROP,\r
+                    1307 => MDB2_ERROR_CANNOT_CREATE,\r
+                    1334 => MDB2_ERROR_CANNOT_ALTER,\r
+                    1339 => MDB2_ERROR_NOT_FOUND,\r
+                    1356 => MDB2_ERROR_INVALID,\r
+                    1359 => MDB2_ERROR_ALREADY_EXISTS,\r
+                    1360 => MDB2_ERROR_NOT_FOUND,\r
+                    1363 => MDB2_ERROR_NOT_FOUND,\r
+                    1365 => MDB2_ERROR_DIVZERO,\r
+                    1451 => MDB2_ERROR_CONSTRAINT,\r
+                    1452 => MDB2_ERROR_CONSTRAINT,\r
+                    1542 => MDB2_ERROR_CANNOT_DROP,\r
+                    1546 => MDB2_ERROR_CONSTRAINT,\r
+                    1582 => MDB2_ERROR_CONSTRAINT,\r
+                    2003 => MDB2_ERROR_CONNECT_FAILED,\r
+                    2019 => MDB2_ERROR_INVALID,\r
+                );\r
+            }\r
+            if ($this->options['portability'] & MDB2_PORTABILITY_ERRORS) {\r
+                $ecode_map[1022] = MDB2_ERROR_CONSTRAINT;\r
+                $ecode_map[1048] = MDB2_ERROR_CONSTRAINT_NOT_NULL;\r
+                $ecode_map[1062] = MDB2_ERROR_CONSTRAINT;\r
+            } else {\r
+                // Doing this in case mode changes during runtime.\r
+                $ecode_map[1022] = MDB2_ERROR_ALREADY_EXISTS;\r
+                $ecode_map[1048] = MDB2_ERROR_CONSTRAINT;\r
+                $ecode_map[1062] = MDB2_ERROR_ALREADY_EXISTS;\r
+            }\r
+            if (isset($ecode_map[$native_code])) {\r
+                $error = $ecode_map[$native_code];\r
+            }\r
+        }\r
+        return array($error, $native_code, $native_msg);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ escape()\r
+\r
+    /**\r
+     * Quotes a string so it can be safely used in a query. It will quote\r
+     * the text so it can safely be used within a query.\r
+     *\r
+     * @param   string  the input string to quote\r
+     * @param   bool    escape wildcards\r
+     *\r
+     * @return  string  quoted string\r
+     *\r
+     * @access  public\r
+     */\r
+    function escape($text, $escape_wildcards = false)\r
+    {\r
+        if ($escape_wildcards) {\r
+            $text = $this->escapePattern($text);\r
+        }\r
+        $connection = $this->getConnection();\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+        $text = @mysql_real_escape_string($text, $connection);\r
+        return $text;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ beginTransaction()\r
+\r
+    /**\r
+     * Start a transaction or set a savepoint.\r
+     *\r
+     * @param   string  name of a savepoint to set\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function beginTransaction($savepoint = null)\r
+    {\r
+        $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));\r
+        $this->_getServerCapabilities();\r
+        if (!is_null($savepoint)) {\r
+            if (!$this->supports('savepoints')) {\r
+                return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                    'savepoints are not supported', __FUNCTION__);\r
+            }\r
+            if (!$this->in_transaction) {\r
+                return $this->raiseError(MDB2_ERROR_INVALID, null, null,\r
+                    'savepoint cannot be released when changes are auto committed', __FUNCTION__);\r
+            }\r
+            $query = 'SAVEPOINT '.$savepoint;\r
+            return $this->_doQuery($query, true);\r
+        } elseif ($this->in_transaction) {\r
+            return MDB2_OK;  //nothing to do\r
+        }\r
+        if (!$this->destructor_registered && $this->opened_persistent) {\r
+            $this->destructor_registered = true;\r
+            register_shutdown_function('MDB2_closeOpenTransactions');\r
+        }\r
+        $query = $this->start_transaction ? 'START TRANSACTION' : 'SET AUTOCOMMIT = 0';\r
+        $result = $this->_doQuery($query, true);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        $this->in_transaction = true;\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ commit()\r
+\r
+    /**\r
+     * Commit the database changes done during a transaction that is in\r
+     * progress or release a savepoint. This function may only be called when\r
+     * auto-committing is disabled, otherwise it will fail. Therefore, a new\r
+     * transaction is implicitly started after committing the pending changes.\r
+     *\r
+     * @param   string  name of a savepoint to release\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function commit($savepoint = null)\r
+    {\r
+        $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));\r
+        if (!$this->in_transaction) {\r
+            return $this->raiseError(MDB2_ERROR_INVALID, null, null,\r
+                'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);\r
+        }\r
+        if (!is_null($savepoint)) {\r
+            if (!$this->supports('savepoints')) {\r
+                return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                    'savepoints are not supported', __FUNCTION__);\r
+            }\r
+            $server_info = $this->getServerVersion();\r
+            if (version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '5.0.3', '<')) {\r
+                return MDB2_OK;\r
+            }\r
+            $query = 'RELEASE SAVEPOINT '.$savepoint;\r
+            return $this->_doQuery($query, true);\r
+        }\r
+\r
+        if (!$this->supports('transactions')) {\r
+            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'transactions are not supported', __FUNCTION__);\r
+        }\r
+\r
+        $result = $this->_doQuery('COMMIT', true);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        if (!$this->start_transaction) {\r
+            $query = 'SET AUTOCOMMIT = 1';\r
+            $result = $this->_doQuery($query, true);\r
+            if (PEAR::isError($result)) {\r
+                return $result;\r
+            }\r
+        }\r
+        $this->in_transaction = false;\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ rollback()\r
+\r
+    /**\r
+     * Cancel any database changes done during a transaction or since a specific\r
+     * savepoint that is in progress. This function may only be called when\r
+     * auto-committing is disabled, otherwise it will fail. Therefore, a new\r
+     * transaction is implicitly started after canceling the pending changes.\r
+     *\r
+     * @param   string  name of a savepoint to rollback to\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function rollback($savepoint = null)\r
+    {\r
+        $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));\r
+        if (!$this->in_transaction) {\r
+            return $this->raiseError(MDB2_ERROR_INVALID, null, null,\r
+                'rollback cannot be done changes are auto committed', __FUNCTION__);\r
+        }\r
+        if (!is_null($savepoint)) {\r
+            if (!$this->supports('savepoints')) {\r
+                return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                    'savepoints are not supported', __FUNCTION__);\r
+            }\r
+            $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;\r
+            return $this->_doQuery($query, true);\r
+        }\r
+\r
+        $query = 'ROLLBACK';\r
+        $result = $this->_doQuery($query, true);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        if (!$this->start_transaction) {\r
+            $query = 'SET AUTOCOMMIT = 1';\r
+            $result = $this->_doQuery($query, true);\r
+            if (PEAR::isError($result)) {\r
+                return $result;\r
+            }\r
+        }\r
+        $this->in_transaction = false;\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function setTransactionIsolation()\r
+\r
+    /**\r
+     * Set the transacton isolation level.\r
+     *\r
+     * @param   string  standard isolation level\r
+     *                  READ UNCOMMITTED (allows dirty reads)\r
+     *                  READ COMMITTED (prevents dirty reads)\r
+     *                  REPEATABLE READ (prevents nonrepeatable reads)\r
+     *                  SERIALIZABLE (prevents phantom reads)\r
+     * @param   array some transaction options:\r
+     *                  'wait' => 'WAIT' | 'NO WAIT'\r
+     *                  'rw'   => 'READ WRITE' | 'READ ONLY'\r
+     *\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     * @since   2.1.1\r
+     */\r
+    function setTransactionIsolation($isolation, $options = array())\r
+    {\r
+        $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));\r
+        if (!$this->supports('transactions')) {\r
+            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'transactions are not supported', __FUNCTION__);\r
+        }\r
+        switch ($isolation) {\r
+        case 'READ UNCOMMITTED':\r
+        case 'READ COMMITTED':\r
+        case 'REPEATABLE READ':\r
+        case 'SERIALIZABLE':\r
+            break;\r
+        default:\r
+            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'isolation level is not supported: '.$isolation, __FUNCTION__);\r
+        }\r
+\r
+        $query = "SET SESSION TRANSACTION ISOLATION LEVEL $isolation";\r
+        return $this->_doQuery($query, true);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _doConnect()\r
+\r
+    /**\r
+     * do the grunt work of the connect\r
+     *\r
+     * @return connection on success or MDB2 Error Object on failure\r
+     * @access protected\r
+     */\r
+    function _doConnect($username, $password, $persistent = false)\r
+    {\r
+        if (!PEAR::loadExtension($this->phptype)) {\r
+            return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);\r
+        }\r
+\r
+        $params = array();\r
+        $unix = ($this->dsn['protocol'] && $this->dsn['protocol'] == 'unix');\r
+        if (empty($this->dsn['hostspec'])) {\r
+            $this->dsn['hostspec'] = $unix ? '' : 'localhost';\r
+        }\r
+        if ($this->dsn['hostspec']) {\r
+            $params[0] = $this->dsn['hostspec'] . ($this->dsn['port'] ? ':' . $this->dsn['port'] : '');\r
+        } else {\r
+            $params[0] = ':' . $this->dsn['socket'];\r
+        }\r
+        $params[] = $username ? $username : null;\r
+        $params[] = $password ? $password : null;\r
+        if (!$persistent) {\r
+            if ($this->_isNewLinkSet()) {\r
+                $params[] = true;\r
+            } else {\r
+                $params[] = false;\r
+            }\r
+        }\r
+        if (version_compare(phpversion(), '4.3.0', '>=')) {\r
+            $params[] = isset($this->dsn['client_flags'])\r
+                ? $this->dsn['client_flags'] : null;\r
+        }\r
+        $connect_function = $persistent ? 'mysql_pconnect' : 'mysql_connect';\r
+\r
+        $connection = @call_user_func_array($connect_function, $params);\r
+        if (!$connection) {\r
+            if (($err = @mysql_error()) != '') {\r
+                return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,\r
+                    $err, __FUNCTION__);\r
+            } else {\r
+                return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,\r
+                    'unable to establish a connection', __FUNCTION__);\r
+            }\r
+        }\r
+\r
+        if (!empty($this->dsn['charset'])) {\r
+            $result = $this->setCharset($this->dsn['charset'], $connection);\r
+            if (PEAR::isError($result)) {\r
+                $this->disconnect(false);\r
+                return $result;\r
+            }\r
+        }\r
+\r
+        return $connection;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ connect()\r
+\r
+    /**\r
+     * Connect to the database\r
+     *\r
+     * @return MDB2_OK on success, MDB2 Error Object on failure\r
+     * @access public\r
+     */\r
+    function connect()\r
+    {\r
+        if (is_resource($this->connection)) {\r
+            //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0\r
+            if (MDB2::areEquals($this->connected_dsn, $this->dsn)\r
+                && $this->opened_persistent == $this->options['persistent']\r
+            ) {\r
+                return MDB2_OK;\r
+            }\r
+            $this->disconnect(false);\r
+        }\r
+\r
+        $connection = $this->_doConnect(\r
+            $this->dsn['username'],\r
+            $this->dsn['password'],\r
+            $this->options['persistent']\r
+        );\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+\r
+        $this->connection = $connection;\r
+        $this->connected_dsn = $this->dsn;\r
+        $this->connected_database_name = '';\r
+        $this->opened_persistent = $this->options['persistent'];\r
+        $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;\r
+\r
+        if ($this->database_name) {\r
+            if ($this->database_name != $this->connected_database_name) {\r
+                if (!@mysql_select_db($this->database_name, $connection)) {\r
+                    $err = $this->raiseError(null, null, null,\r
+                        'Could not select the database: '.$this->database_name, __FUNCTION__);\r
+                    return $err;\r
+                }\r
+                $this->connected_database_name = $this->database_name;\r
+            }\r
+        }\r
+\r
+        $this->_getServerCapabilities();\r
+\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ setCharset()\r
+\r
+    /**\r
+     * Set the charset on the current connection\r
+     *\r
+     * @param string    charset (or array(charset, collation))\r
+     * @param resource  connection handle\r
+     *\r
+     * @return true on success, MDB2 Error Object on failure\r
+     */\r
+    function setCharset($charset, $connection = null)\r
+    {\r
+        if (is_null($connection)) {\r
+            $connection = $this->getConnection();\r
+            if (PEAR::isError($connection)) {\r
+                return $connection;\r
+            }\r
+        }\r
+        $collation = null;\r
+        if (is_array($charset) && 2 == count($charset)) {\r
+            $collation = array_pop($charset);\r
+            $charset   = array_pop($charset);\r
+        }\r
+        $client_info = mysql_get_client_info();\r
+        if (function_exists('mysql_set_charset') && version_compare($client_info, '5.0.6')) {\r
+            if (!$result = mysql_set_charset($charset, $connection)) {\r
+                $err = $this->raiseError(null, null, null,\r
+                    'Could not set client character set', __FUNCTION__);\r
+                return $err;\r
+            }\r
+            return $result;\r
+        }\r
+        $query = "SET NAMES '".mysql_real_escape_string($charset, $connection)."'";\r
+        if (!is_null($collation)) {\r
+            $query .= " COLLATE '".mysql_real_escape_string($collation, $connection)."'";\r
+        }\r
+        return $this->_doQuery($query, true, $connection);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ databaseExists()\r
+\r
+    /**\r
+     * check if given database name is exists?\r
+     *\r
+     * @param string $name    name of the database that should be checked\r
+     *\r
+     * @return mixed true/false on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function databaseExists($name)\r
+    {\r
+        $connection = $this->_doConnect($this->dsn['username'],\r
+                                        $this->dsn['password'],\r
+                                        $this->options['persistent']);\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+\r
+        $result = @mysql_select_db($name, $connection);\r
+        @mysql_close($connection);\r
+\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ disconnect()\r
+\r
+    /**\r
+     * Log out and disconnect from the database.\r
+     *\r
+     * @param  boolean $force if the disconnect should be forced even if the\r
+     *                        connection is opened persistently\r
+     * @return mixed true on success, false if not connected and error\r
+     *                object on error\r
+     * @access public\r
+     */\r
+    function disconnect($force = true)\r
+    {\r
+        if (is_resource($this->connection)) {\r
+            if ($this->in_transaction) {\r
+                $dsn = $this->dsn;\r
+                $database_name = $this->database_name;\r
+                $persistent = $this->options['persistent'];\r
+                $this->dsn = $this->connected_dsn;\r
+                $this->database_name = $this->connected_database_name;\r
+                $this->options['persistent'] = $this->opened_persistent;\r
+                $this->rollback();\r
+                $this->dsn = $dsn;\r
+                $this->database_name = $database_name;\r
+                $this->options['persistent'] = $persistent;\r
+            }\r
+\r
+            if (!$this->opened_persistent || $force) {\r
+                $ok = @mysql_close($this->connection);\r
+                if (!$ok) {\r
+                    return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,\r
+                           null, null, null, __FUNCTION__);\r
+                }\r
+            }\r
+        } else {\r
+            return false;\r
+        }\r
+        return parent::disconnect($force);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ standaloneQuery()\r
+\r
+    /**\r
+     * execute a query as DBA\r
+     *\r
+     * @param string $query the SQL query\r
+     * @param mixed   $types  array that contains the types of the columns in\r
+     *                        the result set\r
+     * @param boolean $is_manip  if the query is a manipulation query\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function standaloneQuery($query, $types = null, $is_manip = false)\r
+    {\r
+        $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];\r
+        $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];\r
+        $connection = $this->_doConnect($user, $pass, $this->options['persistent']);\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+\r
+        $offset = $this->offset;\r
+        $limit = $this->limit;\r
+        $this->offset = $this->limit = 0;\r
+        $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);\r
+        \r
+        $result = $this->_doQuery($query, $is_manip, $connection, $this->database_name);\r
+        if (!PEAR::isError($result)) {\r
+            $result = $this->_affectedRows($connection, $result);\r
+        }\r
+\r
+        @mysql_close($connection);\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _doQuery()\r
+\r
+    /**\r
+     * Execute a query\r
+     * @param string $query  query\r
+     * @param boolean $is_manip  if the query is a manipulation query\r
+     * @param resource $connection\r
+     * @param string $database_name\r
+     * @return result or error object\r
+     * @access protected\r
+     */\r
+    function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)\r
+    {\r
+        $this->last_query = $query;\r
+        $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));\r
+        if ($result) {\r
+            if (PEAR::isError($result)) {\r
+                return $result;\r
+            }\r
+            $query = $result;\r
+        }\r
+        if ($this->options['disable_query']) {\r
+            $result = $is_manip ? 0 : null;\r
+            return $result;\r
+        }\r
+\r
+        if (is_null($connection)) {\r
+            $connection = $this->getConnection();\r
+            if (PEAR::isError($connection)) {\r
+                return $connection;\r
+            }\r
+        }\r
+        if (is_null($database_name)) {\r
+            $database_name = $this->database_name;\r
+        }\r
+\r
+        if ($database_name) {\r
+            if ($database_name != $this->connected_database_name) {\r
+                if (!@mysql_select_db($database_name, $connection)) {\r
+                    $err = $this->raiseError(null, null, null,\r
+                        'Could not select the database: '.$database_name, __FUNCTION__);\r
+                    return $err;\r
+                }\r
+                $this->connected_database_name = $database_name;\r
+            }\r
+        }\r
+\r
+        $function = $this->options['result_buffering']\r
+            ? 'mysql_query' : 'mysql_unbuffered_query';\r
+        $result = @$function($query, $connection);\r
+        if (!$result && 0 !== mysql_errno($connection)) {\r
+            $err = $this->raiseError(null, null, null,\r
+                'Could not execute statement', __FUNCTION__);\r
+            return $err;\r
+        }\r
+\r
+        $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _affectedRows()\r
+\r
+    /**\r
+     * Returns the number of rows affected\r
+     *\r
+     * @param resource $result\r
+     * @param resource $connection\r
+     * @return mixed MDB2 Error Object or the number of rows affected\r
+     * @access private\r
+     */\r
+    function _affectedRows($connection, $result = null)\r
+    {\r
+        if (is_null($connection)) {\r
+            $connection = $this->getConnection();\r
+            if (PEAR::isError($connection)) {\r
+                return $connection;\r
+            }\r
+        }\r
+        return @mysql_affected_rows($connection);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _modifyQuery()\r
+\r
+    /**\r
+     * Changes a query string for various DBMS specific reasons\r
+     *\r
+     * @param string $query  query to modify\r
+     * @param boolean $is_manip  if it is a DML query\r
+     * @param integer $limit  limit the number of rows\r
+     * @param integer $offset  start reading from given offset\r
+     * @return string modified query\r
+     * @access protected\r
+     */\r
+    function _modifyQuery($query, $is_manip, $limit, $offset)\r
+    {\r
+        if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {\r
+            // "DELETE FROM table" gives 0 affected rows in MySQL.\r
+            // This little hack lets you know how many rows were deleted.\r
+            if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {\r
+                $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',\r
+                                      'DELETE FROM \1 WHERE 1=1', $query);\r
+            }\r
+        }\r
+        if ($limit > 0\r
+            && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)\r
+        ) {\r
+            $query = rtrim($query);\r
+            if (substr($query, -1) == ';') {\r
+                $query = substr($query, 0, -1);\r
+            }\r
+\r
+            // LIMIT doesn't always come last in the query\r
+            // @see http://dev.mysql.com/doc/refman/5.0/en/select.html\r
+            $after = '';\r
+            if (preg_match('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', $query, $matches)) {\r
+                $after = $matches[0];\r
+                $query = preg_replace('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', '', $query);\r
+            } elseif (preg_match('/(\s+FOR\s+UPDATE\s*)$/i', $query, $matches)) {\r
+               $after = $matches[0];\r
+               $query = preg_replace('/(\s+FOR\s+UPDATE\s*)$/im', '', $query);\r
+            } elseif (preg_match('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', $query, $matches)) {\r
+               $after = $matches[0];\r
+               $query = preg_replace('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', '', $query);\r
+            }\r
+\r
+            if ($is_manip) {\r
+                return $query . " LIMIT $limit" . $after;\r
+            } else {\r
+                return $query . " LIMIT $offset, $limit" . $after;\r
+            }\r
+        }\r
+        return $query;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getServerVersion()\r
+\r
+    /**\r
+     * return version information about the server\r
+     *\r
+     * @param bool   $native  determines if the raw version string should be returned\r
+     * @return mixed array/string with version information or MDB2 error object\r
+     * @access public\r
+     */\r
+    function getServerVersion($native = false)\r
+    {\r
+        $connection = $this->getConnection();\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+        if ($this->connected_server_info) {\r
+            $server_info = $this->connected_server_info;\r
+        } else {\r
+            $server_info = @mysql_get_server_info($connection);\r
+        }\r
+        if (!$server_info) {\r
+            return $this->raiseError(null, null, null,\r
+                'Could not get server information', __FUNCTION__);\r
+        }\r
+        // cache server_info\r
+        $this->connected_server_info = $server_info;\r
+        if (!$native) {\r
+            $tmp = explode('.', $server_info, 3);\r
+            if (isset($tmp[2]) && strpos($tmp[2], '-')) {\r
+                $tmp2 = explode('-', @$tmp[2], 2);\r
+            } else {\r
+                $tmp2[0] = isset($tmp[2]) ? $tmp[2] : null;\r
+                $tmp2[1] = null;\r
+            }\r
+            $server_info = array(\r
+                'major' => isset($tmp[0]) ? $tmp[0] : null,\r
+                'minor' => isset($tmp[1]) ? $tmp[1] : null,\r
+                'patch' => $tmp2[0],\r
+                'extra' => $tmp2[1],\r
+                'native' => $server_info,\r
+            );\r
+        }\r
+        return $server_info;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getServerCapabilities()\r
+\r
+    /**\r
+     * Fetch some information about the server capabilities\r
+     * (transactions, subselects, prepared statements, etc).\r
+     *\r
+     * @access private\r
+     */\r
+    function _getServerCapabilities()\r
+    {\r
+        if (!$this->server_capabilities_checked) {\r
+            $this->server_capabilities_checked = true;\r
+\r
+            //set defaults\r
+            $this->supported['sub_selects'] = 'emulated';\r
+            $this->supported['prepared_statements'] = 'emulated';\r
+            $this->supported['triggers'] = false;\r
+            $this->start_transaction = false;\r
+            $this->varchar_max_length = 255;\r
+            \r
+            $server_info = $this->getServerVersion();\r
+            if (is_array($server_info)) {\r
+                $server_version = $server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'];\r
+\r
+                if (!version_compare($server_version, '4.1.0', '<')) {\r
+                    $this->supported['sub_selects'] = true;\r
+                    $this->supported['prepared_statements'] = true;\r
+                }\r
+\r
+                // SAVEPOINTs were introduced in MySQL 4.0.14 and 4.1.1 (InnoDB)\r
+                if (version_compare($server_version, '4.1.0', '>=')) {\r
+                    if (version_compare($server_version, '4.1.1', '<')) {\r
+                        $this->supported['savepoints'] = false;\r
+                    }\r
+                } elseif (version_compare($server_version, '4.0.14', '<')) {\r
+                    $this->supported['savepoints'] = false;\r
+                }\r
+\r
+                if (!version_compare($server_version, '4.0.11', '<')) {\r
+                    $this->start_transaction = true;\r
+                }\r
+\r
+                if (!version_compare($server_version, '5.0.3', '<')) {\r
+                    $this->varchar_max_length = 65532;\r
+                }\r
+\r
+                if (!version_compare($server_version, '5.0.2', '<')) {\r
+                    $this->supported['triggers'] = true;\r
+                }\r
+            }\r
+        }\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function _skipUserDefinedVariable($query, $position)\r
+\r
+    /**\r
+     * Utility method, used by prepare() to avoid misinterpreting MySQL user \r
+     * defined variables (SELECT @x:=5) for placeholders.\r
+     * Check if the placeholder is a false positive, i.e. if it is an user defined\r
+     * variable instead. If so, skip it and advance the position, otherwise\r
+     * return the current position, which is valid\r
+     *\r
+     * @param string $query\r
+     * @param integer $position current string cursor position\r
+     * @return integer $new_position\r
+     * @access protected\r
+     */\r
+    function _skipUserDefinedVariable($query, $position)\r
+    {\r
+        $found = strpos(strrev(substr($query, 0, $position)), '@');\r
+        if ($found === false) {\r
+            return $position;\r
+        }\r
+        $pos = strlen($query) - strlen(substr($query, $position)) - $found - 1;\r
+        $substring = substr($query, $pos, $position - $pos + 2);\r
+        if (preg_match('/^@\w+\s*:=$/', $substring)) {\r
+            return $position + 1; //found an user defined variable: skip it\r
+        }\r
+        return $position;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ prepare()\r
+\r
+    /**\r
+     * Prepares a query for multiple execution with execute().\r
+     * With some database backends, this is emulated.\r
+     * prepare() requires a generic query as string like\r
+     * 'INSERT INTO numbers VALUES(?,?)' or\r
+     * 'INSERT INTO numbers VALUES(:foo,:bar)'.\r
+     * The ? and :name and are placeholders which can be set using\r
+     * bindParam() and the query can be sent off using the execute() method.\r
+     * The allowed format for :name can be set with the 'bindname_format' option.\r
+     *\r
+     * @param string $query the query to prepare\r
+     * @param mixed   $types  array that contains the types of the placeholders\r
+     * @param mixed   $result_types  array that contains the types of the columns in\r
+     *                        the result set or MDB2_PREPARE_RESULT, if set to\r
+     *                        MDB2_PREPARE_MANIP the query is handled as a manipulation query\r
+     * @param mixed   $lobs   key (field) value (parameter) pair for all lob placeholders\r
+     * @return mixed resource handle for the prepared query on success, a MDB2\r
+     *        error on failure\r
+     * @access public\r
+     * @see bindParam, execute\r
+     */\r
+    function prepare($query, $types = null, $result_types = null, $lobs = array())\r
+    {\r
+        // connect to get server capabilities (http://pear.php.net/bugs/16147)\r
+        $connection = $this->getConnection();\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+\r
+        if ($this->options['emulate_prepared']\r
+            || $this->supported['prepared_statements'] !== true\r
+        ) {\r
+            return parent::prepare($query, $types, $result_types, $lobs);\r
+        }\r
+        $is_manip = ($result_types === MDB2_PREPARE_MANIP);\r
+        $offset = $this->offset;\r
+        $limit = $this->limit;\r
+        $this->offset = $this->limit = 0;\r
+        $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);\r
+        $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));\r
+        if ($result) {\r
+            if (PEAR::isError($result)) {\r
+                return $result;\r
+            }\r
+            $query = $result;\r
+        }\r
+        $placeholder_type_guess = $placeholder_type = null;\r
+        $question = '?';\r
+        $colon = ':';\r
+        $positions = array();\r
+        $position = 0;\r
+        while ($position < strlen($query)) {\r
+            $q_position = strpos($query, $question, $position);\r
+            $c_position = strpos($query, $colon, $position);\r
+            if ($q_position && $c_position) {\r
+                $p_position = min($q_position, $c_position);\r
+            } elseif ($q_position) {\r
+                $p_position = $q_position;\r
+            } elseif ($c_position) {\r
+                $p_position = $c_position;\r
+            } else {\r
+                break;\r
+            }\r
+            if (is_null($placeholder_type)) {\r
+                $placeholder_type_guess = $query[$p_position];\r
+            }\r
+            \r
+            $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);\r
+            if (PEAR::isError($new_pos)) {\r
+                return $new_pos;\r
+            }\r
+            if ($new_pos != $position) {\r
+                $position = $new_pos;\r
+                continue; //evaluate again starting from the new position\r
+            }\r
+            \r
+            //make sure this is not part of an user defined variable\r
+            $new_pos = $this->_skipUserDefinedVariable($query, $position);\r
+            if ($new_pos != $position) {\r
+                $position = $new_pos;\r
+                continue; //evaluate again starting from the new position\r
+            }\r
+\r
+            if ($query[$position] == $placeholder_type_guess) {\r
+                if (is_null($placeholder_type)) {\r
+                    $placeholder_type = $query[$p_position];\r
+                    $question = $colon = $placeholder_type;\r
+                }\r
+                if ($placeholder_type == ':') {\r
+                    $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';\r
+                    $parameter = preg_replace($regexp, '\\1', $query);\r
+                    if ($parameter === '') {\r
+                        $err = $this->raiseError(MDB2_ERROR_SYNTAX, null, null,\r
+                            'named parameter name must match "bindname_format" option', __FUNCTION__);\r
+                        return $err;\r
+                    }\r
+                    $positions[$p_position] = $parameter;\r
+                    $query = substr_replace($query, '?', $position, strlen($parameter)+1);\r
+                } else {\r
+                    $positions[$p_position] = count($positions);\r
+                }\r
+                $position = $p_position + 1;\r
+            } else {\r
+                $position = $p_position;\r
+            }\r
+        }\r
+\r
+        static $prep_statement_counter = 1;\r
+        $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand()));\r
+        $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);\r
+        $query = "PREPARE $statement_name FROM ".$this->quote($query, 'text');\r
+        $statement = $this->_doQuery($query, true, $connection);\r
+        if (PEAR::isError($statement)) {\r
+            return $statement;\r
+        }\r
+\r
+        $class_name = 'MDB2_Statement_'.$this->phptype;\r
+        $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);\r
+        $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));\r
+        return $obj;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ replace()\r
+\r
+    /**\r
+     * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT\r
+     * query, except that if there is already a row in the table with the same\r
+     * key field values, the old row is deleted before the new row is inserted.\r
+     *\r
+     * The REPLACE type of query does not make part of the SQL standards. Since\r
+     * practically only MySQL implements it natively, this type of query is\r
+     * emulated through this method for other DBMS using standard types of\r
+     * queries inside a transaction to assure the atomicity of the operation.\r
+     *\r
+     * @access public\r
+     *\r
+     * @param string $table name of the table on which the REPLACE query will\r
+     *  be executed.\r
+     * @param array $fields associative array that describes the fields and the\r
+     *  values that will be inserted or updated in the specified table. The\r
+     *  indexes of the array are the names of all the fields of the table. The\r
+     *  values of the array are also associative arrays that describe the\r
+     *  values and other properties of the table fields.\r
+     *\r
+     *  Here follows a list of field properties that need to be specified:\r
+     *\r
+     *    value:\r
+     *          Value to be assigned to the specified field. This value may be\r
+     *          of specified in database independent type format as this\r
+     *          function can perform the necessary datatype conversions.\r
+     *\r
+     *    Default:\r
+     *          this property is required unless the Null property\r
+     *          is set to 1.\r
+     *\r
+     *    type\r
+     *          Name of the type of the field. Currently, all types Metabase\r
+     *          are supported except for clob and blob.\r
+     *\r
+     *    Default: no type conversion\r
+     *\r
+     *    null\r
+     *          Boolean property that indicates that the value for this field\r
+     *          should be set to null.\r
+     *\r
+     *          The default value for fields missing in INSERT queries may be\r
+     *          specified the definition of a table. Often, the default value\r
+     *          is already null, but since the REPLACE may be emulated using\r
+     *          an UPDATE query, make sure that all fields of the table are\r
+     *          listed in this function argument array.\r
+     *\r
+     *    Default: 0\r
+     *\r
+     *    key\r
+     *          Boolean property that indicates that this field should be\r
+     *          handled as a primary key or at least as part of the compound\r
+     *          unique index of the table that will determine the row that will\r
+     *          updated if it exists or inserted a new row otherwise.\r
+     *\r
+     *          This function will fail if no key field is specified or if the\r
+     *          value of a key field is set to null because fields that are\r
+     *          part of unique index they may not be null.\r
+     *\r
+     *    Default: 0\r
+     *\r
+     * @see http://dev.mysql.com/doc/refman/5.0/en/replace.html\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     */\r
+    function replace($table, $fields)\r
+    {\r
+        $count = count($fields);\r
+        $query = $values = '';\r
+        $keys = $colnum = 0;\r
+        for (reset($fields); $colnum < $count; next($fields), $colnum++) {\r
+            $name = key($fields);\r
+            if ($colnum > 0) {\r
+                $query .= ',';\r
+                $values.= ',';\r
+            }\r
+            $query.= $this->quoteIdentifier($name, true);\r
+            if (isset($fields[$name]['null']) && $fields[$name]['null']) {\r
+                $value = 'NULL';\r
+            } else {\r
+                $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;\r
+                $value = $this->quote($fields[$name]['value'], $type);\r
+                if (PEAR::isError($value)) {\r
+                    return $value;\r
+                }\r
+            }\r
+            $values.= $value;\r
+            if (isset($fields[$name]['key']) && $fields[$name]['key']) {\r
+                if ($value === 'NULL') {\r
+                    return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,\r
+                        'key value '.$name.' may not be NULL', __FUNCTION__);\r
+                }\r
+                $keys++;\r
+            }\r
+        }\r
+        if ($keys == 0) {\r
+            return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,\r
+                'not specified which fields are keys', __FUNCTION__);\r
+        }\r
+\r
+        $connection = $this->getConnection();\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+\r
+        $table = $this->quoteIdentifier($table, true);\r
+        $query = "REPLACE INTO $table ($query) VALUES ($values)";\r
+        $result = $this->_doQuery($query, true, $connection);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        return $this->_affectedRows($connection, $result);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ nextID()\r
+\r
+    /**\r
+     * Returns the next free id of a sequence\r
+     *\r
+     * @param string $seq_name name of the sequence\r
+     * @param boolean $ondemand when true the sequence is\r
+     *                          automatic created, if it\r
+     *                          not exists\r
+     *\r
+     * @return mixed MDB2 Error Object or id\r
+     * @access public\r
+     */\r
+    function nextID($seq_name, $ondemand = true)\r
+    {\r
+        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);\r
+        $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);\r
+        $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";\r
+        $this->pushErrorHandling(PEAR_ERROR_RETURN);\r
+        $this->expectError(MDB2_ERROR_NOSUCHTABLE);\r
+        $result = $this->_doQuery($query, true);\r
+        $this->popExpect();\r
+        $this->popErrorHandling();\r
+        if (PEAR::isError($result)) {\r
+            if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {\r
+                $this->loadModule('Manager', null, true);\r
+                $result = $this->manager->createSequence($seq_name);\r
+                if (PEAR::isError($result)) {\r
+                    return $this->raiseError($result, null, null,\r
+                        'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);\r
+                } else {\r
+                    return $this->nextID($seq_name, false);\r
+                }\r
+            }\r
+            return $result;\r
+        }\r
+        $value = $this->lastInsertID();\r
+        if (is_numeric($value)) {\r
+            $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";\r
+            $result = $this->_doQuery($query, true);\r
+            if (PEAR::isError($result)) {\r
+                $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;\r
+            }\r
+        }\r
+        return $value;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ lastInsertID()\r
+\r
+    /**\r
+     * Returns the autoincrement ID if supported or $id or fetches the current\r
+     * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)\r
+     *\r
+     * @param string $table name of the table into which a new row was inserted\r
+     * @param string $field name of the field into which a new row was inserted\r
+     * @return mixed MDB2 Error Object or id\r
+     * @access public\r
+     */\r
+    function lastInsertID($table = null, $field = null)\r
+    {\r
+        // not using mysql_insert_id() due to http://pear.php.net/bugs/bug.php?id=8051\r
+        // not casting to integer to handle BIGINT http://pear.php.net/bugs/bug.php?id=17650\r
+        return $this->queryOne('SELECT LAST_INSERT_ID()');\r
+    }\r
+\r
+    // }}}\r
+    // {{{ currID()\r
+\r
+    /**\r
+     * Returns the current id of a sequence\r
+     *\r
+     * @param string $seq_name name of the sequence\r
+     * @return mixed MDB2 Error Object or id\r
+     * @access public\r
+     */\r
+    function currID($seq_name)\r
+    {\r
+        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);\r
+        $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);\r
+        $query = "SELECT MAX($seqcol_name) FROM $sequence_name";\r
+        return $this->queryOne($query, 'integer');\r
+    }\r
+}\r
+\r
+/**\r
+ * MDB2 MySQL result driver\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Result_mysql extends MDB2_Result_Common\r
+{\r
+    // }}}\r
+    // {{{ fetchRow()\r
+\r
+    /**\r
+     * Fetch a row and insert the data into an existing array.\r
+     *\r
+     * @param int       $fetchmode  how the array data should be indexed\r
+     * @param int    $rownum    number of the row where the data can be found\r
+     * @return int data array on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)\r
+    {\r
+        if (!is_null($rownum)) {\r
+            $seek = $this->seek($rownum);\r
+            if (PEAR::isError($seek)) {\r
+                return $seek;\r
+            }\r
+        }\r
+        if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {\r
+            $fetchmode = $this->db->fetchmode;\r
+        }\r
+        if ($fetchmode & MDB2_FETCHMODE_ASSOC) {\r
+            $row = @mysql_fetch_assoc($this->result);\r
+            if (is_array($row)\r
+                && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE\r
+            ) {\r
+                $row = array_change_key_case($row, $this->db->options['field_case']);\r
+            }\r
+        } else {\r
+           $row = @mysql_fetch_row($this->result);\r
+        }\r
+\r
+        if (!$row) {\r
+            if ($this->result === false) {\r
+                $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,\r
+                    'resultset has already been freed', __FUNCTION__);\r
+                return $err;\r
+            }\r
+            return null;\r
+        }\r
+        $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;\r
+        $rtrim = false;\r
+        if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {\r
+            if (empty($this->types)) {\r
+                $mode += MDB2_PORTABILITY_RTRIM;\r
+            } else {\r
+                $rtrim = true;\r
+            }\r
+        }\r
+        if ($mode) {\r
+            $this->db->_fixResultArrayValues($row, $mode);\r
+        }\r
+        if (!empty($this->types)) {\r
+            $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);\r
+        }\r
+        if (!empty($this->values)) {\r
+            $this->_assignBindColumns($row);\r
+        }\r
+        if ($fetchmode === MDB2_FETCHMODE_OBJECT) {\r
+            $object_class = $this->db->options['fetch_class'];\r
+            if ($object_class == 'stdClass') {\r
+                $row = (object) $row;\r
+            } else {\r
+                $rowObj = new $object_class($row);\r
+                $row = $rowObj;\r
+            }\r
+        }\r
+        ++$this->rownum;\r
+        return $row;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getColumnNames()\r
+\r
+    /**\r
+     * Retrieve the names of columns returned by the DBMS in a query result.\r
+     *\r
+     * @return  mixed   Array variable that holds the names of columns as keys\r
+     *                  or an MDB2 error on failure.\r
+     *                  Some DBMS may not return any columns when the result set\r
+     *                  does not contain any rows.\r
+     * @access private\r
+     */\r
+    function _getColumnNames()\r
+    {\r
+        $columns = array();\r
+        $numcols = $this->numCols();\r
+        if (PEAR::isError($numcols)) {\r
+            return $numcols;\r
+        }\r
+        for ($column = 0; $column < $numcols; $column++) {\r
+            $column_name = @mysql_field_name($this->result, $column);\r
+            $columns[$column_name] = $column;\r
+        }\r
+        if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $columns = array_change_key_case($columns, $this->db->options['field_case']);\r
+        }\r
+        return $columns;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ numCols()\r
+\r
+    /**\r
+     * Count the number of columns returned by the DBMS in a query result.\r
+     *\r
+     * @return mixed integer value with the number of columns, a MDB2 error\r
+     *                       on failure\r
+     * @access public\r
+     */\r
+    function numCols()\r
+    {\r
+        $cols = @mysql_num_fields($this->result);\r
+        if (is_null($cols)) {\r
+            if ($this->result === false) {\r
+                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,\r
+                    'resultset has already been freed', __FUNCTION__);\r
+            } elseif (is_null($this->result)) {\r
+                return count($this->types);\r
+            }\r
+            return $this->db->raiseError(null, null, null,\r
+                'Could not get column count', __FUNCTION__);\r
+        }\r
+        return $cols;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ free()\r
+\r
+    /**\r
+     * Free the internal resources associated with result.\r
+     *\r
+     * @return boolean true on success, false if result is invalid\r
+     * @access public\r
+     */\r
+    function free()\r
+    {\r
+        if (is_resource($this->result) && $this->db->connection) {\r
+            $free = @mysql_free_result($this->result);\r
+            if ($free === false) {\r
+                return $this->db->raiseError(null, null, null,\r
+                    'Could not free result', __FUNCTION__);\r
+            }\r
+        }\r
+        $this->result = false;\r
+        return MDB2_OK;\r
+    }\r
+}\r
+\r
+/**\r
+ * MDB2 MySQL buffered result driver\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_BufferedResult_mysql extends MDB2_Result_mysql\r
+{\r
+    // }}}\r
+    // {{{ seek()\r
+\r
+    /**\r
+     * Seek to a specific row in a result set\r
+     *\r
+     * @param int    $rownum    number of the row where the data can be found\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function seek($rownum = 0)\r
+    {\r
+        if ($this->rownum != ($rownum - 1) && !@mysql_data_seek($this->result, $rownum)) {\r
+            if ($this->result === false) {\r
+                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,\r
+                    'resultset has already been freed', __FUNCTION__);\r
+            } elseif (is_null($this->result)) {\r
+                return MDB2_OK;\r
+            }\r
+            return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,\r
+                'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);\r
+        }\r
+        $this->rownum = $rownum - 1;\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ valid()\r
+\r
+    /**\r
+     * Check if the end of the result set has been reached\r
+     *\r
+     * @return mixed true or false on sucess, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function valid()\r
+    {\r
+        $numrows = $this->numRows();\r
+        if (PEAR::isError($numrows)) {\r
+            return $numrows;\r
+        }\r
+        return $this->rownum < ($numrows - 1);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ numRows()\r
+\r
+    /**\r
+     * Returns the number of rows in a result object\r
+     *\r
+     * @return mixed MDB2 Error Object or the number of rows\r
+     * @access public\r
+     */\r
+    function numRows()\r
+    {\r
+        $rows = @mysql_num_rows($this->result);\r
+        if (false === $rows) {\r
+            if (false === $this->result) {\r
+                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,\r
+                    'resultset has already been freed', __FUNCTION__);\r
+            } elseif (is_null($this->result)) {\r
+                return 0;\r
+            }\r
+            return $this->db->raiseError(null, null, null,\r
+                'Could not get row count', __FUNCTION__);\r
+        }\r
+        return $rows;\r
+    }\r
+    \r
+    // }}}\r
+}\r
+\r
+/**\r
+ * MDB2 MySQL statement driver\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Statement_mysql extends MDB2_Statement_Common\r
+{\r
+    // {{{ _execute()\r
+\r
+    /**\r
+     * Execute a prepared query statement helper method.\r
+     *\r
+     * @param mixed $result_class string which specifies which result class to use\r
+     * @param mixed $result_wrap_class string which specifies which class to wrap results in\r
+     *\r
+     * @return mixed MDB2_Result or integer (affected rows) on success,\r
+     *               a MDB2 error on failure\r
+     * @access private\r
+     */\r
+    function _execute($result_class = true, $result_wrap_class = false)\r
+    {\r
+        if (is_null($this->statement)) {\r
+            $result = parent::_execute($result_class, $result_wrap_class);\r
+            return $result;\r
+        }\r
+        $this->db->last_query = $this->query;\r
+        $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));\r
+        if ($this->db->getOption('disable_query')) {\r
+            $result = $this->is_manip ? 0 : null;\r
+            return $result;\r
+        }\r
+\r
+        $connection = $this->db->getConnection();\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+\r
+        $query = 'EXECUTE '.$this->statement;\r
+        if (!empty($this->positions)) {\r
+            $parameters = array();\r
+            foreach ($this->positions as $parameter) {\r
+                if (!array_key_exists($parameter, $this->values)) {\r
+                    return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                        'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);\r
+                }\r
+                $close = false;\r
+                $value = $this->values[$parameter];\r
+                $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;\r
+                if (is_resource($value) || $type == 'clob' || $type == 'blob' && $this->db->options['lob_allow_url_include']) {\r
+                    if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {\r
+                        if ($match[1] == 'file://') {\r
+                            $value = $match[2];\r
+                        }\r
+                        $value = @fopen($value, 'r');\r
+                        $close = true;\r
+                    }\r
+                    if (is_resource($value)) {\r
+                        $data = '';\r
+                        while (!@feof($value)) {\r
+                            $data.= @fread($value, $this->db->options['lob_buffer_length']);\r
+                        }\r
+                        if ($close) {\r
+                            @fclose($value);\r
+                        }\r
+                        $value = $data;\r
+                    }\r
+                }\r
+                $quoted = $this->db->quote($value, $type);\r
+                if (PEAR::isError($quoted)) {\r
+                    return $quoted;\r
+                }\r
+                $param_query = 'SET @'.$parameter.' = '.$quoted;\r
+                $result = $this->db->_doQuery($param_query, true, $connection);\r
+                if (PEAR::isError($result)) {\r
+                    return $result;\r
+                }\r
+            }\r
+            $query.= ' USING @'.implode(', @', array_values($this->positions));\r
+        }\r
+\r
+        $result = $this->db->_doQuery($query, $this->is_manip, $connection);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+\r
+        if ($this->is_manip) {\r
+            $affected_rows = $this->db->_affectedRows($connection, $result);\r
+            return $affected_rows;\r
+        }\r
+\r
+        $result = $this->db->_wrapResult($result, $this->result_types,\r
+            $result_class, $result_wrap_class, $this->limit, $this->offset);\r
+        $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ free()\r
+\r
+    /**\r
+     * Release resources allocated for the specified prepared query.\r
+     *\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function free()\r
+    {\r
+        if (is_null($this->positions)) {\r
+            return $this->db->raiseError(MDB2_ERROR, null, null,\r
+                'Prepared statement has already been freed', __FUNCTION__);\r
+        }\r
+        $result = MDB2_OK;\r
+\r
+        if (!is_null($this->statement)) {\r
+            $connection = $this->db->getConnection();\r
+            if (PEAR::isError($connection)) {\r
+                return $connection;\r
+            }\r
+            $query = 'DEALLOCATE PREPARE '.$this->statement;\r
+            $result = $this->db->_doQuery($query, true, $connection);\r
+        }\r
+\r
+        parent::free();\r
+        return $result;\r
+    }\r
+}\r
+?>\r
index 13fea6906806f2b3f41b85b204181ce67a75eae4..15bd280f40bc7f8d22a3af4c7b6c94f020136e9d 100644 (file)
-<?php
-// vim: set et ts=4 sw=4 fdm=marker:
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Paul Cooper <pgc@ucecom.com>                                 |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.203 2008/11/29 14:04:46 afz Exp $
-
-/**
- * MDB2 PostGreSQL driver
- *
- * @package MDB2
- * @category Database
- * @author  Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_Driver_pgsql extends MDB2_Driver_Common
-{
-    // {{{ properties
-    var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => '\\');
-
-    var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
-    // }}}
-    // {{{ constructor
-
-    /**
-     * Constructor
-     */
-    function __construct()
-    {
-        parent::__construct();
-
-        $this->phptype = 'pgsql';
-        $this->dbsyntax = 'pgsql';
-
-        $this->supported['sequences'] = true;
-        $this->supported['indexes'] = true;
-        $this->supported['affected_rows'] = true;
-        $this->supported['summary_functions'] = true;
-        $this->supported['order_by_text'] = true;
-        $this->supported['transactions'] = true;
-        $this->supported['savepoints'] = true;
-        $this->supported['current_id'] = true;
-        $this->supported['limit_queries'] = true;
-        $this->supported['LOBs'] = true;
-        $this->supported['replace'] = 'emulated';
-        $this->supported['sub_selects'] = true;
-        $this->supported['triggers'] = true;
-        $this->supported['auto_increment'] = 'emulated';
-        $this->supported['primary_key'] = true;
-        $this->supported['result_introspection'] = true;
-        $this->supported['prepared_statements'] = true;
-        $this->supported['identifier_quoting'] = true;
-        $this->supported['pattern_escaping'] = true;
-        $this->supported['new_link'] = true;
-
-        $this->options['DBA_username'] = false;
-        $this->options['DBA_password'] = false;
-        $this->options['multi_query'] = false;
-        $this->options['disable_smart_seqname'] = true;
-        $this->options['max_identifiers_length'] = 63;
-    }
-
-    // }}}
-    // {{{ errorInfo()
-
-    /**
-     * This method is used to collect information about an error
-     *
-     * @param integer $error
-     * @return array
-     * @access public
-     */
-    function errorInfo($error = null)
-    {
-        // Fall back to MDB2_ERROR if there was no mapping.
-        $error_code = MDB2_ERROR;
-
-        $native_msg = '';
-        if (is_resource($error)) {
-            $native_msg = @pg_result_error($error);
-        } elseif ($this->connection) {
-            $native_msg = @pg_last_error($this->connection);
-            if (!$native_msg && @pg_connection_status($this->connection) === PGSQL_CONNECTION_BAD) {
-                $native_msg = 'Database connection has been lost.';
-                $error_code = MDB2_ERROR_CONNECT_FAILED;
-            }
-        } else {
-            $native_msg = @pg_last_error();
-        }
-
-        static $error_regexps;
-        if (empty($error_regexps)) {
-            $error_regexps = array(
-                '/column .* (of relation .*)?does not exist/i'
-                    => MDB2_ERROR_NOSUCHFIELD,
-                '/(relation|sequence|table).*does not exist|class .* not found/i'
-                    => MDB2_ERROR_NOSUCHTABLE,
-                '/database .* does not exist/'
-                    => MDB2_ERROR_NOT_FOUND,
-                '/constraint .* does not exist/'
-                    => MDB2_ERROR_NOT_FOUND,
-                '/index .* does not exist/'
-                    => MDB2_ERROR_NOT_FOUND,
-                '/database .* already exists/i'
-                    => MDB2_ERROR_ALREADY_EXISTS,
-                '/relation .* already exists/i'
-                    => MDB2_ERROR_ALREADY_EXISTS,
-                '/(divide|division) by zero$/i'
-                    => MDB2_ERROR_DIVZERO,
-                '/pg_atoi: error in .*: can\'t parse /i'
-                    => MDB2_ERROR_INVALID_NUMBER,
-                '/invalid input syntax for( type)? (integer|numeric)/i'
-                    => MDB2_ERROR_INVALID_NUMBER,
-                '/value .* is out of range for type \w*int/i'
-                    => MDB2_ERROR_INVALID_NUMBER,
-                '/integer out of range/i'
-                    => MDB2_ERROR_INVALID_NUMBER,
-                '/value too long for type character/i'
-                    => MDB2_ERROR_INVALID,
-                '/attribute .* not found|relation .* does not have attribute/i'
-                    => MDB2_ERROR_NOSUCHFIELD,
-                '/column .* specified in USING clause does not exist in (left|right) table/i'
-                    => MDB2_ERROR_NOSUCHFIELD,
-                '/parser: parse error at or near/i'
-                    => MDB2_ERROR_SYNTAX,
-                '/syntax error at/'
-                    => MDB2_ERROR_SYNTAX,
-                '/column reference .* is ambiguous/i'
-                    => MDB2_ERROR_SYNTAX,
-                '/permission denied/'
-                    => MDB2_ERROR_ACCESS_VIOLATION,
-                '/violates not-null constraint/'
-                    => MDB2_ERROR_CONSTRAINT_NOT_NULL,
-                '/violates [\w ]+ constraint/'
-                    => MDB2_ERROR_CONSTRAINT,
-                '/referential integrity violation/'
-                    => MDB2_ERROR_CONSTRAINT,
-                '/more expressions than target columns/i'
-                    => MDB2_ERROR_VALUE_COUNT_ON_ROW,
-            );
-        }
-        if (is_numeric($error) && $error < 0) {
-            $error_code = $error;
-        } else {
-            foreach ($error_regexps as $regexp => $code) {
-                if (preg_match($regexp, $native_msg)) {
-                    $error_code = $code;
-                    break;
-                }
-            }
-        }
-        return array($error_code, null, $native_msg);
-    }
-
-    // }}}
-    // {{{ escape()
-
-    /**
-     * Quotes a string so it can be safely used in a query. It will quote
-     * the text so it can safely be used within a query.
-     *
-     * @param   string  the input string to quote
-     * @param   bool    escape wildcards
-     *
-     * @return  string  quoted string
-     *
-     * @access  public
-     */
-    function escape($text, $escape_wildcards = false)
-    {
-        if ($escape_wildcards) {
-            $text = $this->escapePattern($text);
-        }
-        $connection = $this->getConnection();
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-        if (is_resource($connection) && version_compare(PHP_VERSION, '5.2.0RC5', '>=')) {
-            $text = @pg_escape_string($connection, $text);
-        } else {
-            $text = @pg_escape_string($text);
-        }
-        return $text;
-    }
-
-    // }}}
-    // {{{ beginTransaction()
-
-    /**
-     * Start a transaction or set a savepoint.
-     *
-     * @param   string  name of a savepoint to set
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function beginTransaction($savepoint = null)
-    {
-        $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
-        if (!is_null($savepoint)) {
-            if (!$this->in_transaction) {
-                return $this->raiseError(MDB2_ERROR_INVALID, null, null,
-                    'savepoint cannot be released when changes are auto committed', __FUNCTION__);
-            }
-            $query = 'SAVEPOINT '.$savepoint;
-            return $this->_doQuery($query, true);
-        } elseif ($this->in_transaction) {
-            return MDB2_OK;  //nothing to do
-        }
-        if (!$this->destructor_registered && $this->opened_persistent) {
-            $this->destructor_registered = true;
-            register_shutdown_function('MDB2_closeOpenTransactions');
-        }
-        $result =& $this->_doQuery('BEGIN', true);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        $this->in_transaction = true;
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ commit()
-
-    /**
-     * Commit the database changes done during a transaction that is in
-     * progress or release a savepoint. This function may only be called when
-     * auto-committing is disabled, otherwise it will fail. Therefore, a new
-     * transaction is implicitly started after committing the pending changes.
-     *
-     * @param   string  name of a savepoint to release
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function commit($savepoint = null)
-    {
-        $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
-        if (!$this->in_transaction) {
-            return $this->raiseError(MDB2_ERROR_INVALID, null, null,
-                'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
-        }
-        if (!is_null($savepoint)) {
-            $query = 'RELEASE SAVEPOINT '.$savepoint;
-            return $this->_doQuery($query, true);
-        }
-
-        $result =& $this->_doQuery('COMMIT', true);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        $this->in_transaction = false;
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ rollback()
-
-    /**
-     * Cancel any database changes done during a transaction or since a specific
-     * savepoint that is in progress. This function may only be called when
-     * auto-committing is disabled, otherwise it will fail. Therefore, a new
-     * transaction is implicitly started after canceling the pending changes.
-     *
-     * @param   string  name of a savepoint to rollback to
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function rollback($savepoint = null)
-    {
-        $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
-        if (!$this->in_transaction) {
-            return $this->raiseError(MDB2_ERROR_INVALID, null, null,
-                'rollback cannot be done changes are auto committed', __FUNCTION__);
-        }
-        if (!is_null($savepoint)) {
-            $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
-            return $this->_doQuery($query, true);
-        }
-
-        $query = 'ROLLBACK';
-        $result =& $this->_doQuery($query, true);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        $this->in_transaction = false;
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ function setTransactionIsolation()
-
-    /**
-     * Set the transacton isolation level.
-     *
-     * @param   string  standard isolation level
-     *                  READ UNCOMMITTED (allows dirty reads)
-     *                  READ COMMITTED (prevents dirty reads)
-     *                  REPEATABLE READ (prevents nonrepeatable reads)
-     *                  SERIALIZABLE (prevents phantom reads)
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     * @since   2.1.1
-     */
-    static function setTransactionIsolation($isolation, $options = array())
-    {
-        $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
-        switch ($isolation) {
-        case 'READ UNCOMMITTED':
-        case 'READ COMMITTED':
-        case 'REPEATABLE READ':
-        case 'SERIALIZABLE':
-            break;
-        default:
-            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'isolation level is not supported: '.$isolation, __FUNCTION__);
-        }
-
-        $query = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL $isolation";
-        return $this->_doQuery($query, true);
-    }
-
-    // }}}
-    // {{{ _doConnect()
-
-    /**
-     * Do the grunt work of connecting to the database
-     *
-     * @return mixed connection resource on success, MDB2 Error Object on failure
-     * @access protected
-     */
-    function _doConnect($username, $password, $database_name, $persistent = false)
-    {
-        if (!PEAR::loadExtension($this->phptype)) {
-            return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
-        }
-        
-        if ($database_name == '') {
-            $database_name = 'template1';
-        }
-
-        $protocol = $this->dsn['protocol'] ? $this->dsn['protocol'] : 'tcp';
-
-        $params = array('');
-        if ($protocol == 'tcp') {
-            if ($this->dsn['hostspec']) {
-                $params[0].= 'host=' . $this->dsn['hostspec'];
-            }
-            if ($this->dsn['port']) {
-                $params[0].= ' port=' . $this->dsn['port'];
-            }
-        } elseif ($protocol == 'unix') {
-            // Allow for pg socket in non-standard locations.
-            if ($this->dsn['socket']) {
-                $params[0].= 'host=' . $this->dsn['socket'];
-            }
-            if ($this->dsn['port']) {
-                $params[0].= ' port=' . $this->dsn['port'];
-            }
-        }
-        if ($database_name) {
-            $params[0].= ' dbname=\'' . addslashes($database_name) . '\'';
-        }
-        if ($username) {
-            $params[0].= ' user=\'' . addslashes($username) . '\'';
-        }
-        if ($password) {
-            $params[0].= ' password=\'' . addslashes($password) . '\'';
-        }
-        if (!empty($this->dsn['options'])) {
-            $params[0].= ' options=' . $this->dsn['options'];
-        }
-        if (!empty($this->dsn['tty'])) {
-            $params[0].= ' tty=' . $this->dsn['tty'];
-        }
-        if (!empty($this->dsn['connect_timeout'])) {
-            $params[0].= ' connect_timeout=' . $this->dsn['connect_timeout'];
-        }
-        if (!empty($this->dsn['sslmode'])) {
-            $params[0].= ' sslmode=' . $this->dsn['sslmode'];
-        }
-        if (!empty($this->dsn['service'])) {
-            $params[0].= ' service=' . $this->dsn['service'];
-        }
-
-        if ($this->_isNewLinkSet()) {
-            if (version_compare(phpversion(), '4.3.0', '>=')) {
-                $params[] = PGSQL_CONNECT_FORCE_NEW;
-            }
-        }
-
-        $connect_function = $persistent ? 'pg_pconnect' : 'pg_connect';
-        $connection = @call_user_func_array($connect_function, $params);
-        if (!$connection) {
-            return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
-                'unable to establish a connection', __FUNCTION__);
-        }
-
-       if (empty($this->dsn['disable_iso_date'])) {
-            if (!@pg_query($connection, "SET SESSION DATESTYLE = 'ISO'")) {
-                return $this->raiseError(null, null, null,
-                    'Unable to set date style to iso', __FUNCTION__);
-            }
-       }
-
-        if (!empty($this->dsn['charset'])) {
-            $result = $this->setCharset($this->dsn['charset'], $connection);
-            if (PEAR::isError($result)) {
-                return $result;
-            }
-        }
-
-        return $connection;
-    }
-
-    // }}}
-    // {{{ connect()
-
-    /**
-     * Connect to the database
-     *
-     * @return true on success, MDB2 Error Object on failure
-     * @access public
-     */
-    function connect()
-    {
-        if (is_resource($this->connection)) {
-            //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
-            if (MDB2::areEquals($this->connected_dsn, $this->dsn)
-                && $this->connected_database_name == $this->database_name
-                && ($this->opened_persistent == $this->options['persistent'])
-            ) {
-                return MDB2_OK;
-            }
-            $this->disconnect(false);
-        }
-
-        if ($this->database_name) {
-            $connection = $this->_doConnect($this->dsn['username'],
-                                            $this->dsn['password'],
-                                            $this->database_name,
-                                            $this->options['persistent']);
-            if (PEAR::isError($connection)) {
-                return $connection;
-            }
-
-            $this->connection = $connection;
-            $this->connected_dsn = $this->dsn;
-            $this->connected_database_name = $this->database_name;
-            $this->opened_persistent = $this->options['persistent'];
-            $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
-        }
-
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ setCharset()
-
-    /**
-     * Set the charset on the current connection
-     *
-     * @param string    charset
-     * @param resource  connection handle
-     *
-     * @return true on success, MDB2 Error Object on failure
-     */
-    function setCharset($charset, $connection = null)
-    {
-        if (is_null($connection)) {
-            $connection = $this->getConnection();
-            if (PEAR::isError($connection)) {
-                return $connection;
-            }
-        }
-        if (is_array($charset)) {
-            $charset   = array_shift($charset);
-            $this->warnings[] = 'postgresql does not support setting client collation';
-        }
-        $result = @pg_set_client_encoding($connection, $charset);
-        if ($result == -1) {
-            return $this->raiseError(null, null, null,
-                'Unable to set client charset: '.$charset, __FUNCTION__);
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ databaseExists()
-
-    /**
-     * check if given database name is exists?
-     *
-     * @param string $name    name of the database that should be checked
-     *
-     * @return mixed true/false on success, a MDB2 error on failure
-     * @access public
-     */
-    function databaseExists($name)
-    {
-        $res = $this->_doConnect($this->dsn['username'],
-                                 $this->dsn['password'],
-                                 $this->escape($name),
-                                 $this->options['persistent']);
-        if (!PEAR::isError($res)) {
-            return true;
-        }
-
-        return false;
-    }
-
-    // }}}
-    // {{{ disconnect()
-
-    /**
-     * Log out and disconnect from the database.
-     *
-     * @param  boolean $force if the disconnect should be forced even if the
-     *                        connection is opened persistently
-     * @return mixed true on success, false if not connected and error
-     *                object on error
-     * @access public
-     */
-    function disconnect($force = true)
-    {
-        if (is_resource($this->connection)) {
-            if ($this->in_transaction) {
-                $dsn = $this->dsn;
-                $database_name = $this->database_name;
-                $persistent = $this->options['persistent'];
-                $this->dsn = $this->connected_dsn;
-                $this->database_name = $this->connected_database_name;
-                $this->options['persistent'] = $this->opened_persistent;
-                $this->rollback();
-                $this->dsn = $dsn;
-                $this->database_name = $database_name;
-                $this->options['persistent'] = $persistent;
-            }
-
-            if (!$this->opened_persistent || $force) {
-                $ok = @pg_close($this->connection);
-                if (!$ok) {
-                    return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
-                           null, null, null, __FUNCTION__);
-                }
-            }
-        } else {
-            return false;
-        }
-        return parent::disconnect($force);
-    }
-
-    // }}}
-    // {{{ standaloneQuery()
-
-   /**
-     * execute a query as DBA
-     *
-     * @param string $query the SQL query
-     * @param mixed   $types  array that contains the types of the columns in
-     *                        the result set
-     * @param boolean $is_manip  if the query is a manipulation query
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function &standaloneQuery($query, $types = null, $is_manip = false)
-    {
-        $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
-        $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
-        $connection = $this->_doConnect($user, $pass, $this->database_name, $this->options['persistent']);
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-
-        $offset = $this->offset;
-        $limit = $this->limit;
-        $this->offset = $this->limit = 0;
-        $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
-
-        $result =& $this->_doQuery($query, $is_manip, $connection, $this->database_name);
-        if (!PEAR::isError($result)) {
-            if ($is_manip) {
-                $result =  $this->_affectedRows($connection, $result);
-            } else {
-                $result =& $this->_wrapResult($result, $types, true, false, $limit, $offset);
-            }
-        }
-
-        @pg_close($connection);
-        return $result;
-    }
-
-    // }}}
-    // {{{ _doQuery()
-
-    /**
-     * Execute a query
-     * @param string $query  query
-     * @param boolean $is_manip  if the query is a manipulation query
-     * @param resource $connection
-     * @param string $database_name
-     * @return result or error object
-     * @access protected
-     */
-    function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
-    {
-        $this->last_query = $query;
-        $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
-        if ($result) {
-            if (PEAR::isError($result)) {
-                return $result;
-            }
-            $query = $result;
-        }
-        if ($this->options['disable_query']) {
-            $result = $is_manip ? 0 : null;
-            return $result;
-        }
-
-        if (is_null($connection)) {
-            $connection = $this->getConnection();
-            if (PEAR::isError($connection)) {
-                return $connection;
-            }
-        }
-
-        $function = $this->options['multi_query'] ? 'pg_send_query' : 'pg_query';
-        $result = @$function($connection, $query);
-        if (!$result) {
-            $err =& $this->raiseError(null, null, null,
-                'Could not execute statement', __FUNCTION__);
-            return $err;
-        } elseif ($this->options['multi_query']) {
-            if (!($result = @pg_get_result($connection))) {
-                $err =& $this->raiseError(null, null, null,
-                        'Could not get the first result from a multi query', __FUNCTION__);
-                return $err;
-            }
-        }
-
-        $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
-        return $result;
-    }
-
-    // }}}
-    // {{{ _affectedRows()
-
-    /**
-     * Returns the number of rows affected
-     *
-     * @param resource $result
-     * @param resource $connection
-     * @return mixed MDB2 Error Object or the number of rows affected
-     * @access private
-     */
-    function _affectedRows($connection, $result = null)
-    {
-        if (is_null($connection)) {
-            $connection = $this->getConnection();
-            if (PEAR::isError($connection)) {
-                return $connection;
-            }
-        }
-        return @pg_affected_rows($result);
-    }
-
-    // }}}
-    // {{{ _modifyQuery()
-
-    /**
-     * Changes a query string for various DBMS specific reasons
-     *
-     * @param string $query  query to modify
-     * @param boolean $is_manip  if it is a DML query
-     * @param integer $limit  limit the number of rows
-     * @param integer $offset  start reading from given offset
-     * @return string modified query
-     * @access protected
-     */
-    function _modifyQuery($query, $is_manip, $limit, $offset)
-    {
-        if ($limit > 0
-            && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
-        ) {
-            $query = rtrim($query);
-            if (substr($query, -1) == ';') {
-                $query = substr($query, 0, -1);
-            }
-            if ($is_manip) {
-                $query = $this->_modifyManipQuery($query, $limit);
-            } else {
-                $query.= " LIMIT $limit OFFSET $offset";
-            }
-        }
-        return $query;
-    }
-    
-    // }}}
-    // {{{ _modifyManipQuery()
-    
-    /**
-     * Changes a manip query string for various DBMS specific reasons
-     *
-     * @param string $query  query to modify
-     * @param integer $limit  limit the number of rows
-     * @return string modified query
-     * @access protected
-     */
-    function _modifyManipQuery($query, $limit)
-    {
-        $pos = strpos(strtolower($query), 'where');
-        $where = $pos ? substr($query, $pos) : '';
-
-        $manip_clause = '(\bDELETE\b\s+(?:\*\s+)?\bFROM\b|\bUPDATE\b)';
-        $from_clause  = '([\w\.]+)';
-        $where_clause = '(?:(.*)\bWHERE\b\s+(.*))|(.*)';
-        $pattern = '/^'. $manip_clause . '\s+' . $from_clause .'(?:\s)*(?:'. $where_clause .')?$/i';
-        $matches = preg_match($pattern, $query, $match);
-        if ($matches) {
-            $manip = $match[1];
-            $from  = $match[2];
-            $what  = (count($matches) == 6) ? $match[5] : $match[3];
-            return $manip.' '.$from.' '.$what.' WHERE ctid=(SELECT ctid FROM '.$from.' '.$where.' LIMIT '.$limit.')';
-        }
-        //return error?
-        return $query;
-    }
-
-    // }}}
-    // {{{ getServerVersion()
-
-    /**
-     * return version information about the server
-     *
-     * @param bool   $native  determines if the raw version string should be returned
-     * @return mixed array/string with version information or MDB2 error object
-     * @access public
-     */
-    function getServerVersion($native = false)
-    {
-        $query = 'SHOW SERVER_VERSION';
-        if ($this->connected_server_info) {
-            $server_info = $this->connected_server_info;
-        } else {
-            $server_info = $this->queryOne($query, 'text');
-            if (PEAR::isError($server_info)) {
-                return $server_info;
-            }
-        }
-        // cache server_info
-        $this->connected_server_info = $server_info;
-        if (!$native && !PEAR::isError($server_info)) {
-            $tmp = explode('.', $server_info, 3);
-            if (empty($tmp[2])
-                && isset($tmp[1])
-                && preg_match('/(\d+)(.*)/', $tmp[1], $tmp2)
-            ) {
-                $server_info = array(
-                    'major' => $tmp[0],
-                    'minor' => $tmp2[1],
-                    'patch' => null,
-                    'extra' => $tmp2[2],
-                    'native' => $server_info,
-                );
-            } else {
-                $server_info = array(
-                    'major' => isset($tmp[0]) ? $tmp[0] : null,
-                    'minor' => isset($tmp[1]) ? $tmp[1] : null,
-                    'patch' => isset($tmp[2]) ? $tmp[2] : null,
-                    'extra' => null,
-                    'native' => $server_info,
-                );
-            }
-        }
-        return $server_info;
-    }
-
-    // }}}
-    // {{{ prepare()
-
-    /**
-     * Prepares a query for multiple execution with execute().
-     * With some database backends, this is emulated.
-     * prepare() requires a generic query as string like
-     * 'INSERT INTO numbers VALUES(?,?)' or
-     * 'INSERT INTO numbers VALUES(:foo,:bar)'.
-     * The ? and :name and are placeholders which can be set using
-     * bindParam() and the query can be sent off using the execute() method.
-     * The allowed format for :name can be set with the 'bindname_format' option.
-     *
-     * @param string $query the query to prepare
-     * @param mixed   $types  array that contains the types of the placeholders
-     * @param mixed   $result_types  array that contains the types of the columns in
-     *                        the result set or MDB2_PREPARE_RESULT, if set to
-     *                        MDB2_PREPARE_MANIP the query is handled as a manipulation query
-     * @param mixed   $lobs   key (field) value (parameter) pair for all lob placeholders
-     * @return mixed resource handle for the prepared query on success, a MDB2
-     *        error on failure
-     * @access public
-     * @see bindParam, execute
-     */
-    function &prepare($query, $types = null, $result_types = null, $lobs = array())
-    {
-        if ($this->options['emulate_prepared']) {
-            $obj =& parent::prepare($query, $types, $result_types, $lobs);
-            return $obj;
-        }
-        $is_manip = ($result_types === MDB2_PREPARE_MANIP);
-        $offset = $this->offset;
-        $limit = $this->limit;
-        $this->offset = $this->limit = 0;
-        $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
-        if ($result) {
-            if (PEAR::isError($result)) {
-                return $result;
-            }
-            $query = $result;
-        }
-        $pgtypes = function_exists('pg_prepare') ? false : array();
-        if ($pgtypes !== false && !empty($types)) {
-            $this->loadModule('Datatype', null, true);
-        }
-        $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
-        $placeholder_type_guess = $placeholder_type = null;
-        $question = '?';
-        $colon = ':';
-        $positions = array();
-        $position = $parameter = 0;
-        while ($position < strlen($query)) {
-            $q_position = strpos($query, $question, $position);
-            $c_position = strpos($query, $colon, $position);
-            //skip "::type" cast ("select id::varchar(20) from sometable where name=?")
-            $doublecolon_position = strpos($query, '::', $position);
-            if ($doublecolon_position !== false && $doublecolon_position == $c_position) {
-                $c_position = strpos($query, $colon, $position+2);
-            }
-            if ($q_position && $c_position) {
-                $p_position = min($q_position, $c_position);
-            } elseif ($q_position) {
-                $p_position = $q_position;
-            } elseif ($c_position) {
-                $p_position = $c_position;
-            } else {
-                break;
-            }
-            if (is_null($placeholder_type)) {
-                $placeholder_type_guess = $query[$p_position];
-            }
-            
-            $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
-            if (PEAR::isError($new_pos)) {
-                return $new_pos;
-            }
-            if ($new_pos != $position) {
-                $position = $new_pos;
-                continue; //evaluate again starting from the new position
-            }
-
-            if ($query[$position] == $placeholder_type_guess) {
-                if (is_null($placeholder_type)) {
-                    $placeholder_type = $query[$p_position];
-                    $question = $colon = $placeholder_type;
-                    if (!empty($types) && is_array($types)) {
-                        if ($placeholder_type == ':') {
-                        } else {
-                            $types = array_values($types);
-                        }
-                    }
-                }
-                if ($placeholder_type_guess == '?') {
-                    $length = 1;
-                    $name = $parameter;
-                } else {
-                    $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
-                    $param = preg_replace($regexp, '\\1', $query);
-                    if ($param === '') {
-                        $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
-                            'named parameter name must match "bindname_format" option', __FUNCTION__);
-                        return $err;
-                    }
-                    $length = strlen($param) + 1;
-                    $name = $param;
-                }
-                if ($pgtypes !== false) {
-                    if (is_array($types) && array_key_exists($name, $types)) {
-                        $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$name]);
-                    } elseif (is_array($types) && array_key_exists($parameter, $types)) {
-                        $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$parameter]);
-                    } else {
-                        $pgtypes[] = 'text';
-                    }
-                }
-                if (($key_parameter = array_search($name, $positions))) {
-                    $next_parameter = 1;
-                    foreach ($positions as $key => $value) {
-                        if ($key_parameter == $key) {
-                            break;
-                        }
-                        ++$next_parameter;
-                    }
-                } else {
-                    ++$parameter;
-                    $next_parameter = $parameter;
-                    $positions[] = $name;
-                }
-                $query = substr_replace($query, '$'.$parameter, $position, $length);
-                $position = $p_position + strlen($parameter);
-            } else {
-                $position = $p_position;
-            }
-        }
-        $connection = $this->getConnection();
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-        static $prep_statement_counter = 1;
-        $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand()));
-        $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);
-        if ($pgtypes === false) {
-            $result = @pg_prepare($connection, $statement_name, $query);
-            if (!$result) {
-                $err =& $this->raiseError(null, null, null,
-                    'Unable to create prepared statement handle', __FUNCTION__);
-                return $err;
-            }
-        } else {
-            $types_string = '';
-            if ($pgtypes) {
-                $types_string = ' ('.implode(', ', $pgtypes).') ';
-            }
-            $query = 'PREPARE '.$statement_name.$types_string.' AS '.$query;
-            $statement =& $this->_doQuery($query, true, $connection);
-            if (PEAR::isError($statement)) {
-                return $statement;
-            }
-        }
-
-        $class_name = 'MDB2_Statement_'.$this->phptype;
-        $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
-        $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
-        return $obj;
-    }
-
-    // }}}
-    // {{{ function getSequenceName($sqn)
-
-    /**
-     * adds sequence name formatting to a sequence name
-     *
-     * @param   string  name of the sequence
-     *
-     * @return  string  formatted sequence name
-     *
-     * @access  public
-     */
-    function getSequenceName($sqn)
-    {
-        if (false === $this->options['disable_smart_seqname']) {
-            if (strpos($sqn, '_') !== false) {
-                list($table, $field) = explode('_', $sqn, 2);
-            }
-            $schema_list = $this->queryOne("SELECT array_to_string(current_schemas(false), ',')");
-            if (PEAR::isError($schema_list) || empty($schema_list) || count($schema_list) < 2) {
-                $order_by = ' a.attnum';
-                $schema_clause = ' AND n.nspname=current_schema()';
-            } else {
-                $schemas = explode(',', $schema_list);
-                $schema_clause = ' AND n.nspname IN ('.$schema_list.')';
-                $counter = 1;
-                $order_by = ' CASE ';
-                foreach ($schemas as $schema) {
-                    $order_by .= ' WHEN n.nspname='.$schema.' THEN '.$counter++;
-                }
-                $order_by .= ' ELSE '.$counter.' END, a.attnum';
-            }
-
-            $query = "SELECT substring((SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)
-                           FROM pg_attrdef d
-                          WHERE d.adrelid = a.attrelid
-                            AND d.adnum = a.attnum
-                            AND a.atthasdef
-                        ) FROM 'nextval[^'']*''([^'']*)')
-                        FROM pg_attribute a
-                    LEFT JOIN pg_class c ON c.oid = a.attrelid
-                    LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef
-                    LEFT JOIN pg_namespace n ON c.relnamespace = n.oid
-                       WHERE (c.relname = ".$this->quote($sqn, 'text');
-            if (!empty($field)) {
-                $query .= " OR (c.relname = ".$this->quote($table, 'text')." AND a.attname = ".$this->quote($field, 'text').")";
-            }
-            $query .= "      )"
-                         .$schema_clause."
-                         AND NOT a.attisdropped
-                         AND a.attnum > 0
-                         AND pg_get_expr(d.adbin, d.adrelid) LIKE 'nextval%'
-                    ORDER BY ".$order_by;
-            $seqname = $this->queryOne($query);
-            if (!PEAR::isError($seqname) && !empty($seqname) && is_string($seqname)) {
-                return $seqname;
-            }
-        }
-
-        return parent::getSequenceName($sqn);
-    }
-
-    // }}}
-    // {{{ nextID()
-
-    /**
-     * Returns the next free id of a sequence
-     *
-     * @param string $seq_name name of the sequence
-     * @param boolean $ondemand when true the sequence is
-     *                          automatic created, if it
-     *                          not exists
-     * @return mixed MDB2 Error Object or id
-     * @access public
-     */
-    function nextID($seq_name, $ondemand = true)
-    {
-        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
-        $query = "SELECT NEXTVAL('$sequence_name')";
-        $this->pushErrorHandling(PEAR_ERROR_RETURN);
-        $this->expectError(MDB2_ERROR_NOSUCHTABLE);
-        $result = $this->queryOne($query, 'integer');
-        $this->popExpect();
-        $this->popErrorHandling();
-        if (PEAR::isError($result)) {
-            if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
-                $this->loadModule('Manager', null, true);
-                $result = $this->manager->createSequence($seq_name);
-                if (PEAR::isError($result)) {
-                    return $this->raiseError($result, null, null,
-                        'on demand sequence could not be created', __FUNCTION__);
-                }
-                return $this->nextId($seq_name, false);
-            }
-        }
-        return $result;
-    }
-
-    // }}}
-    // {{{ lastInsertID()
-
-    /**
-     * Returns the autoincrement ID if supported or $id or fetches the current
-     * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
-     *
-     * @param string $table name of the table into which a new row was inserted
-     * @param string $field name of the field into which a new row was inserted
-     * @return mixed MDB2 Error Object or id
-     * @access public
-     */
-    function lastInsertID($table = null, $field = null)
-    {
-        if (empty($table) && empty($field)) {
-            return $this->queryOne('SELECT lastval()', 'integer');
-        }
-        $seq = $table.(empty($field) ? '' : '_'.$field);
-        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq), true);
-        return $this->queryOne("SELECT currval('$sequence_name')", 'integer');
-    }
-
-    // }}}
-    // {{{ currID()
-
-    /**
-     * Returns the current id of a sequence
-     *
-     * @param string $seq_name name of the sequence
-     * @return mixed MDB2 Error Object or id
-     * @access public
-     */
-    function currID($seq_name)
-    {
-        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
-        return $this->queryOne("SELECT last_value FROM $sequence_name", 'integer');
-    }
-}
-
-/**
- * MDB2 PostGreSQL result driver
- *
- * @package MDB2
- * @category Database
- * @author  Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_Result_pgsql extends MDB2_Result_Common
-{
-    // }}}
-    // {{{ fetchRow()
-
-    /**
-     * Fetch a row and insert the data into an existing array.
-     *
-     * @param int       $fetchmode  how the array data should be indexed
-     * @param int    $rownum    number of the row where the data can be found
-     * @return int data array on success, a MDB2 error on failure
-     * @access public
-     */
-    function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
-    {
-        if (!is_null($rownum)) {
-            $seek = $this->seek($rownum);
-            if (PEAR::isError($seek)) {
-                return $seek;
-            }
-        }
-        if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
-            $fetchmode = $this->db->fetchmode;
-        }
-        if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
-            $row = @pg_fetch_array($this->result, null, PGSQL_ASSOC);
-            if (is_array($row)
-                && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
-            ) {
-                $row = array_change_key_case($row, $this->db->options['field_case']);
-            }
-        } else {
-            $row = @pg_fetch_row($this->result);
-        }
-        if (!$row) {
-            if ($this->result === false) {
-                $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                    'resultset has already been freed', __FUNCTION__);
-                return $err;
-            }
-            $null = null;
-            return $null;
-        }
-        $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
-        $rtrim = false;
-        if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
-            if (empty($this->types)) {
-                $mode += MDB2_PORTABILITY_RTRIM;
-            } else {
-                $rtrim = true;
-            }
-        }
-        if ($mode) {
-            $this->db->_fixResultArrayValues($row, $mode);
-        }
-        if (!empty($this->types)) {
-            $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
-        }
-        if (!empty($this->values)) {
-            $this->_assignBindColumns($row);
-        }
-        if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
-            $object_class = $this->db->options['fetch_class'];
-            if ($object_class == 'stdClass') {
-                $row = (object) $row;
-            } else {
-                $row = new $object_class($row);
-            }
-        }
-        ++$this->rownum;
-        return $row;
-    }
-
-    // }}}
-    // {{{ _getColumnNames()
-
-    /**
-     * Retrieve the names of columns returned by the DBMS in a query result.
-     *
-     * @return  mixed   Array variable that holds the names of columns as keys
-     *                  or an MDB2 error on failure.
-     *                  Some DBMS may not return any columns when the result set
-     *                  does not contain any rows.
-     * @access private
-     */
-    function _getColumnNames()
-    {
-        $columns = array();
-        $numcols = $this->numCols();
-        if (PEAR::isError($numcols)) {
-            return $numcols;
-        }
-        for ($column = 0; $column < $numcols; $column++) {
-            $column_name = @pg_field_name($this->result, $column);
-            $columns[$column_name] = $column;
-        }
-        if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $columns = array_change_key_case($columns, $this->db->options['field_case']);
-        }
-        return $columns;
-    }
-
-    // }}}
-    // {{{ numCols()
-
-    /**
-     * Count the number of columns returned by the DBMS in a query result.
-     *
-     * @access public
-     * @return mixed integer value with the number of columns, a MDB2 error
-     *                       on failure
-     */
-    function numCols()
-    {
-        $cols = @pg_num_fields($this->result);
-        if (is_null($cols)) {
-            if ($this->result === false) {
-                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                    'resultset has already been freed', __FUNCTION__);
-            } elseif (is_null($this->result)) {
-                return count($this->types);
-            }
-            return $this->db->raiseError(null, null, null,
-                'Could not get column count', __FUNCTION__);
-        }
-        return $cols;
-    }
-
-    // }}}
-    // {{{ nextResult()
-
-    /**
-     * Move the internal result pointer to the next available result
-     *
-     * @return true on success, false if there is no more result set or an error object on failure
-     * @access public
-     */
-    function nextResult()
-    {
-        $connection = $this->db->getConnection();
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-
-        if (!($this->result = @pg_get_result($connection))) {
-            return false;
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ free()
-
-    /**
-     * Free the internal resources associated with result.
-     *
-     * @return boolean true on success, false if result is invalid
-     * @access public
-     */
-    function free()
-    {
-        if (is_resource($this->result) && $this->db->connection) {
-            $free = @pg_free_result($this->result);
-            if ($free === false) {
-                return $this->db->raiseError(null, null, null,
-                    'Could not free result', __FUNCTION__);
-            }
-        }
-        $this->result = false;
-        return MDB2_OK;
-    }
-}
-
-/**
- * MDB2 PostGreSQL buffered result driver
- *
- * @package MDB2
- * @category Database
- * @author  Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_BufferedResult_pgsql extends MDB2_Result_pgsql
-{
-    // {{{ seek()
-
-    /**
-     * Seek to a specific row in a result set
-     *
-     * @param int    $rownum    number of the row where the data can be found
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function seek($rownum = 0)
-    {
-        if ($this->rownum != ($rownum - 1) && !@pg_result_seek($this->result, $rownum)) {
-            if ($this->result === false) {
-                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                    'resultset has already been freed', __FUNCTION__);
-            } elseif (is_null($this->result)) {
-                return MDB2_OK;
-            }
-            return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
-                'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
-        }
-        $this->rownum = $rownum - 1;
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ valid()
-
-    /**
-     * Check if the end of the result set has been reached
-     *
-     * @return mixed true or false on sucess, a MDB2 error on failure
-     * @access public
-     */
-    function valid()
-    {
-        $numrows = $this->numRows();
-        if (PEAR::isError($numrows)) {
-            return $numrows;
-        }
-        return $this->rownum < ($numrows - 1);
-    }
-
-    // }}}
-    // {{{ numRows()
-
-    /**
-     * Returns the number of rows in a result object
-     *
-     * @return mixed MDB2 Error Object or the number of rows
-     * @access public
-     */
-    function numRows()
-    {
-        $rows = @pg_num_rows($this->result);
-        if (is_null($rows)) {
-            if ($this->result === false) {
-                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                    'resultset has already been freed', __FUNCTION__);
-            } elseif (is_null($this->result)) {
-                return 0;
-            }
-            return $this->db->raiseError(null, null, null,
-                'Could not get row count', __FUNCTION__);
-        }
-        return $rows;
-    }
-}
-
-/**
- * MDB2 PostGreSQL statement driver
- *
- * @package MDB2
- * @category Database
- * @author  Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_Statement_pgsql extends MDB2_Statement_Common
-{
-    // {{{ _execute()
-
-    /**
-     * Execute a prepared query statement helper method.
-     *
-     * @param mixed $result_class string which specifies which result class to use
-     * @param mixed $result_wrap_class string which specifies which class to wrap results in
-     *
-     * @return mixed MDB2_Result or integer (affected rows) on success,
-     *               a MDB2 error on failure
-     * @access private
-     */
-    function &_execute($result_class = true, $result_wrap_class = false)
-    {
-        if (is_null($this->statement)) {
-            $result =& parent::_execute($result_class, $result_wrap_class);
-            return $result;
-        }
-        $this->db->last_query = $this->query;
-        $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
-        if ($this->db->getOption('disable_query')) {
-            $result = $this->is_manip ? 0 : null;
-            return $result;
-        }
-
-        $connection = $this->db->getConnection();
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-
-        $query = false;
-        $parameters = array();
-        // todo: disabled until pg_execute() bytea issues are cleared up
-        if (true || !function_exists('pg_execute')) {
-            $query = 'EXECUTE '.$this->statement;
-        }
-        if (!empty($this->positions)) {
-            foreach ($this->positions as $parameter) {
-                if (!array_key_exists($parameter, $this->values)) {
-                    return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                        'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
-                }
-                $value = $this->values[$parameter];
-                $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
-                if (is_resource($value) || $type == 'clob' || $type == 'blob' || $this->db->options['lob_allow_url_include']) {
-                    if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
-                        if ($match[1] == 'file://') {
-                            $value = $match[2];
-                        }
-                        $value = @fopen($value, 'r');
-                        $close = true;
-                    }
-                    if (is_resource($value)) {
-                        $data = '';
-                        while (!@feof($value)) {
-                            $data.= @fread($value, $this->db->options['lob_buffer_length']);
-                        }
-                        if ($close) {
-                            @fclose($value);
-                        }
-                        $value = $data;
-                    }
-                }
-                $quoted = $this->db->quote($value, $type, $query);
-                if (PEAR::isError($quoted)) {
-                    return $quoted;
-                }
-                $parameters[] = $quoted;
-            }
-            if ($query) {
-                $query.= ' ('.implode(', ', $parameters).')';
-            }
-        }
-
-        if (!$query) {
-            $result = @pg_execute($connection, $this->statement, $parameters);
-            if (!$result) {
-                $err =& $this->db->raiseError(null, null, null,
-                    'Unable to execute statement', __FUNCTION__);
-                return $err;
-            }
-        } else {
-            $result = $this->db->_doQuery($query, $this->is_manip, $connection);
-            if (PEAR::isError($result)) {
-                return $result;
-            }
-        }
-
-        if ($this->is_manip) {
-            $affected_rows = $this->db->_affectedRows($connection, $result);
-            return $affected_rows;
-        }
-
-        $result =& $this->db->_wrapResult($result, $this->result_types,
-            $result_class, $result_wrap_class, $this->limit, $this->offset);
-        $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
-        return $result;
-    }
-
-    // }}}
-    // {{{ free()
-
-    /**
-     * Release resources allocated for the specified prepared query.
-     *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function free()
-    {
-        if (is_null($this->positions)) {
-            return $this->db->raiseError(MDB2_ERROR, null, null,
-                'Prepared statement has already been freed', __FUNCTION__);
-        }
-        $result = MDB2_OK;
-
-        if (!is_null($this->statement)) {
-            $connection = $this->db->getConnection();
-            if (PEAR::isError($connection)) {
-                return $connection;
-            }
-            $query = 'DEALLOCATE PREPARE '.$this->statement;
-            $result = $this->db->_doQuery($query, true, $connection);
-        }
-
-        parent::free();
-        return $result;
-    }
-}
+<?php\r
+// vim: set et ts=4 sw=4 fdm=marker:\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Paul Cooper <pgc@ucecom.com>                                 |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: pgsql.php 295587 2010-02-28 17:16:38Z quipo $\r
+\r
+/**\r
+ * MDB2 PostGreSQL driver\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Paul Cooper <pgc@ucecom.com>\r
+ */\r
+class MDB2_Driver_pgsql extends MDB2_Driver_Common\r
+{\r
+    // {{{ properties\r
+    var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => '\\');\r
+\r
+    var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');\r
+    // }}}\r
+    // {{{ constructor\r
+\r
+    /**\r
+     * Constructor\r
+     */\r
+    function __construct()\r
+    {\r
+        parent::__construct();\r
+\r
+        $this->phptype = 'pgsql';\r
+        $this->dbsyntax = 'pgsql';\r
+\r
+        $this->supported['sequences'] = true;\r
+        $this->supported['indexes'] = true;\r
+        $this->supported['affected_rows'] = true;\r
+        $this->supported['summary_functions'] = true;\r
+        $this->supported['order_by_text'] = true;\r
+        $this->supported['transactions'] = true;\r
+        $this->supported['savepoints'] = true;\r
+        $this->supported['current_id'] = true;\r
+        $this->supported['limit_queries'] = true;\r
+        $this->supported['LOBs'] = true;\r
+        $this->supported['replace'] = 'emulated';\r
+        $this->supported['sub_selects'] = true;\r
+        $this->supported['triggers'] = true;\r
+        $this->supported['auto_increment'] = 'emulated';\r
+        $this->supported['primary_key'] = true;\r
+        $this->supported['result_introspection'] = true;\r
+        $this->supported['prepared_statements'] = true;\r
+        $this->supported['identifier_quoting'] = true;\r
+        $this->supported['pattern_escaping'] = true;\r
+        $this->supported['new_link'] = true;\r
+\r
+        $this->options['DBA_username'] = false;\r
+        $this->options['DBA_password'] = false;\r
+        $this->options['multi_query'] = false;\r
+        $this->options['disable_smart_seqname'] = true;\r
+        $this->options['max_identifiers_length'] = 63;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ errorInfo()\r
+\r
+    /**\r
+     * This method is used to collect information about an error\r
+     *\r
+     * @param integer $error\r
+     * @return array\r
+     * @access public\r
+     */\r
+    function errorInfo($error = null)\r
+    {\r
+        // Fall back to MDB2_ERROR if there was no mapping.\r
+        $error_code = MDB2_ERROR;\r
+\r
+        $native_msg = '';\r
+        if (is_resource($error)) {\r
+            $native_msg = @pg_result_error($error);\r
+        } elseif ($this->connection) {\r
+            $native_msg = @pg_last_error($this->connection);\r
+            if (!$native_msg && @pg_connection_status($this->connection) === PGSQL_CONNECTION_BAD) {\r
+                $native_msg = 'Database connection has been lost.';\r
+                $error_code = MDB2_ERROR_CONNECT_FAILED;\r
+            }\r
+        } else {\r
+            $native_msg = @pg_last_error();\r
+        }\r
+\r
+        static $error_regexps;\r
+        if (empty($error_regexps)) {\r
+            $error_regexps = array(\r
+                '/column .* (of relation .*)?does not exist/i'\r
+                    => MDB2_ERROR_NOSUCHFIELD,\r
+                '/(relation|sequence|table).*does not exist|class .* not found/i'\r
+                    => MDB2_ERROR_NOSUCHTABLE,\r
+                '/database .* does not exist/'\r
+                    => MDB2_ERROR_NOT_FOUND,\r
+                '/constraint .* does not exist/'\r
+                    => MDB2_ERROR_NOT_FOUND,\r
+                '/index .* does not exist/'\r
+                    => MDB2_ERROR_NOT_FOUND,\r
+                '/database .* already exists/i'\r
+                    => MDB2_ERROR_ALREADY_EXISTS,\r
+                '/relation .* already exists/i'\r
+                    => MDB2_ERROR_ALREADY_EXISTS,\r
+                '/(divide|division) by zero$/i'\r
+                    => MDB2_ERROR_DIVZERO,\r
+                '/pg_atoi: error in .*: can\'t parse /i'\r
+                    => MDB2_ERROR_INVALID_NUMBER,\r
+                '/invalid input syntax for( type)? (integer|numeric)/i'\r
+                    => MDB2_ERROR_INVALID_NUMBER,\r
+                '/value .* is out of range for type \w*int/i'\r
+                    => MDB2_ERROR_INVALID_NUMBER,\r
+                '/integer out of range/i'\r
+                    => MDB2_ERROR_INVALID_NUMBER,\r
+                '/value too long for type character/i'\r
+                    => MDB2_ERROR_INVALID,\r
+                '/attribute .* not found|relation .* does not have attribute/i'\r
+                    => MDB2_ERROR_NOSUCHFIELD,\r
+                '/column .* specified in USING clause does not exist in (left|right) table/i'\r
+                    => MDB2_ERROR_NOSUCHFIELD,\r
+                '/parser: parse error at or near/i'\r
+                    => MDB2_ERROR_SYNTAX,\r
+                '/syntax error at/'\r
+                    => MDB2_ERROR_SYNTAX,\r
+                '/column reference .* is ambiguous/i'\r
+                    => MDB2_ERROR_SYNTAX,\r
+                '/permission denied/'\r
+                    => MDB2_ERROR_ACCESS_VIOLATION,\r
+                '/violates not-null constraint/'\r
+                    => MDB2_ERROR_CONSTRAINT_NOT_NULL,\r
+                '/violates [\w ]+ constraint/'\r
+                    => MDB2_ERROR_CONSTRAINT,\r
+                '/referential integrity violation/'\r
+                    => MDB2_ERROR_CONSTRAINT,\r
+                '/more expressions than target columns/i'\r
+                    => MDB2_ERROR_VALUE_COUNT_ON_ROW,\r
+            );\r
+        }\r
+        if (is_numeric($error) && $error < 0) {\r
+            $error_code = $error;\r
+        } else {\r
+            foreach ($error_regexps as $regexp => $code) {\r
+                if (preg_match($regexp, $native_msg)) {\r
+                    $error_code = $code;\r
+                    break;\r
+                }\r
+            }\r
+        }\r
+        return array($error_code, null, $native_msg);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ escape()\r
+\r
+    /**\r
+     * Quotes a string so it can be safely used in a query. It will quote\r
+     * the text so it can safely be used within a query.\r
+     *\r
+     * @param   string  the input string to quote\r
+     * @param   bool    escape wildcards\r
+     *\r
+     * @return  string  quoted string\r
+     *\r
+     * @access  public\r
+     */\r
+    function escape($text, $escape_wildcards = false)\r
+    {\r
+        if ($escape_wildcards) {\r
+            $text = $this->escapePattern($text);\r
+        }\r
+        $connection = $this->getConnection();\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+        if (is_resource($connection) && version_compare(PHP_VERSION, '5.2.0RC5', '>=')) {\r
+            $text = @pg_escape_string($connection, $text);\r
+        } else {\r
+            $text = @pg_escape_string($text);\r
+        }\r
+        return $text;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ beginTransaction()\r
+\r
+    /**\r
+     * Start a transaction or set a savepoint.\r
+     *\r
+     * @param   string  name of a savepoint to set\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function beginTransaction($savepoint = null)\r
+    {\r
+        $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));\r
+        if (null !== $savepoint) {\r
+            if (!$this->in_transaction) {\r
+                return $this->raiseError(MDB2_ERROR_INVALID, null, null,\r
+                    'savepoint cannot be released when changes are auto committed', __FUNCTION__);\r
+            }\r
+            $query = 'SAVEPOINT '.$savepoint;\r
+            return $this->_doQuery($query, true);\r
+        }\r
+        if ($this->in_transaction) {\r
+            return MDB2_OK;  //nothing to do\r
+        }\r
+        if (!$this->destructor_registered && $this->opened_persistent) {\r
+            $this->destructor_registered = true;\r
+            register_shutdown_function('MDB2_closeOpenTransactions');\r
+        }\r
+        $result = $this->_doQuery('BEGIN', true);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        $this->in_transaction = true;\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ commit()\r
+\r
+    /**\r
+     * Commit the database changes done during a transaction that is in\r
+     * progress or release a savepoint. This function may only be called when\r
+     * auto-committing is disabled, otherwise it will fail. Therefore, a new\r
+     * transaction is implicitly started after committing the pending changes.\r
+     *\r
+     * @param   string  name of a savepoint to release\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function commit($savepoint = null)\r
+    {\r
+        $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));\r
+        if (!$this->in_transaction) {\r
+            return $this->raiseError(MDB2_ERROR_INVALID, null, null,\r
+                'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);\r
+        }\r
+        if (null !== $savepoint) {\r
+            $query = 'RELEASE SAVEPOINT '.$savepoint;\r
+            return $this->_doQuery($query, true);\r
+        }\r
+\r
+        $result = $this->_doQuery('COMMIT', true);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        $this->in_transaction = false;\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ rollback()\r
+\r
+    /**\r
+     * Cancel any database changes done during a transaction or since a specific\r
+     * savepoint that is in progress. This function may only be called when\r
+     * auto-committing is disabled, otherwise it will fail. Therefore, a new\r
+     * transaction is implicitly started after canceling the pending changes.\r
+     *\r
+     * @param   string  name of a savepoint to rollback to\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function rollback($savepoint = null)\r
+    {\r
+        $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));\r
+        if (!$this->in_transaction) {\r
+            return $this->raiseError(MDB2_ERROR_INVALID, null, null,\r
+                'rollback cannot be done changes are auto committed', __FUNCTION__);\r
+        }\r
+        if (null !== $savepoint) {\r
+            $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;\r
+            return $this->_doQuery($query, true);\r
+        }\r
+\r
+        $query = 'ROLLBACK';\r
+        $result = $this->_doQuery($query, true);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        $this->in_transaction = false;\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function setTransactionIsolation()\r
+\r
+    /**\r
+     * Set the transacton isolation level.\r
+     *\r
+     * @param   string  standard isolation level\r
+     *                  READ UNCOMMITTED (allows dirty reads)\r
+     *                  READ COMMITTED (prevents dirty reads)\r
+     *                  REPEATABLE READ (prevents nonrepeatable reads)\r
+     *                  SERIALIZABLE (prevents phantom reads)\r
+     * @param   array some transaction options:\r
+     *                  'wait' => 'WAIT' | 'NO WAIT'\r
+     *                  'rw'   => 'READ WRITE' | 'READ ONLY'\r
+     *\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     * @since   2.1.1\r
+     */\r
+    function setTransactionIsolation($isolation, $options = array())\r
+    {\r
+        $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));\r
+        switch ($isolation) {\r
+        case 'READ UNCOMMITTED':\r
+        case 'READ COMMITTED':\r
+        case 'REPEATABLE READ':\r
+        case 'SERIALIZABLE':\r
+            break;\r
+        default:\r
+            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'isolation level is not supported: '.$isolation, __FUNCTION__);\r
+        }\r
+\r
+        $query = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL $isolation";\r
+        return $this->_doQuery($query, true);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _doConnect()\r
+\r
+    /**\r
+     * Do the grunt work of connecting to the database\r
+     *\r
+     * @return mixed connection resource on success, MDB2 Error Object on failure\r
+     * @access protected\r
+     */\r
+    function _doConnect($username, $password, $database_name, $persistent = false)\r
+    {\r
+        if (!PEAR::loadExtension($this->phptype)) {\r
+            return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);\r
+        }\r
+        \r
+        if ($database_name == '') {\r
+            $database_name = 'template1';\r
+        }\r
+\r
+        $protocol = $this->dsn['protocol'] ? $this->dsn['protocol'] : 'tcp';\r
+\r
+        $params = array('');\r
+        if ($protocol == 'tcp') {\r
+            if ($this->dsn['hostspec']) {\r
+                $params[0].= 'host=' . $this->dsn['hostspec'];\r
+            }\r
+            if ($this->dsn['port']) {\r
+                $params[0].= ' port=' . $this->dsn['port'];\r
+            }\r
+        } elseif ($protocol == 'unix') {\r
+            // Allow for pg socket in non-standard locations.\r
+            if ($this->dsn['socket']) {\r
+                $params[0].= 'host=' . $this->dsn['socket'];\r
+            }\r
+            if ($this->dsn['port']) {\r
+                $params[0].= ' port=' . $this->dsn['port'];\r
+            }\r
+        }\r
+        if ($database_name) {\r
+            $params[0].= ' dbname=\'' . addslashes($database_name) . '\'';\r
+        }\r
+        if ($username) {\r
+            $params[0].= ' user=\'' . addslashes($username) . '\'';\r
+        }\r
+        if ($password) {\r
+            $params[0].= ' password=\'' . addslashes($password) . '\'';\r
+        }\r
+        if (!empty($this->dsn['options'])) {\r
+            $params[0].= ' options=' . $this->dsn['options'];\r
+        }\r
+        if (!empty($this->dsn['tty'])) {\r
+            $params[0].= ' tty=' . $this->dsn['tty'];\r
+        }\r
+        if (!empty($this->dsn['connect_timeout'])) {\r
+            $params[0].= ' connect_timeout=' . $this->dsn['connect_timeout'];\r
+        }\r
+        if (!empty($this->dsn['sslmode'])) {\r
+            $params[0].= ' sslmode=' . $this->dsn['sslmode'];\r
+        }\r
+        if (!empty($this->dsn['service'])) {\r
+            $params[0].= ' service=' . $this->dsn['service'];\r
+        }\r
+\r
+        if ($this->_isNewLinkSet()) {\r
+            if (version_compare(phpversion(), '4.3.0', '>=')) {\r
+                $params[] = PGSQL_CONNECT_FORCE_NEW;\r
+            }\r
+        }\r
+\r
+        $connect_function = $persistent ? 'pg_pconnect' : 'pg_connect';\r
+        $connection = @call_user_func_array($connect_function, $params);\r
+        if (!$connection) {\r
+            return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,\r
+                'unable to establish a connection', __FUNCTION__);\r
+        }\r
+\r
+       if (empty($this->dsn['disable_iso_date'])) {\r
+            if (!@pg_query($connection, "SET SESSION DATESTYLE = 'ISO'")) {\r
+                return $this->raiseError(null, null, null,\r
+                    'Unable to set date style to iso', __FUNCTION__);\r
+            }\r
+       }\r
+\r
+        if (!empty($this->dsn['charset'])) {\r
+            $result = $this->setCharset($this->dsn['charset'], $connection);\r
+            if (PEAR::isError($result)) {\r
+                return $result;\r
+            }\r
+        }\r
+\r
+        // Enable extra compatibility settings on 8.2 and later\r
+        if (function_exists('pg_parameter_status')) {\r
+            $version = pg_parameter_status($connection, 'server_version');\r
+            if ($version == false) {\r
+                return $this->raiseError(null, null, null,\r
+                  'Unable to retrieve server version', __FUNCTION__);\r
+            }\r
+            $version = explode ('.', $version);\r
+            if (    $version['0'] > 8\r
+                || ($version['0'] == 8 && $version['1'] >= 2)\r
+            ) {\r
+                if (!@pg_query($connection, "SET SESSION STANDARD_CONFORMING_STRINGS = OFF")) {\r
+                    return $this->raiseError(null, null, null,\r
+                      'Unable to set standard_conforming_strings to off', __FUNCTION__);\r
+                }\r
+\r
+                if (!@pg_query($connection, "SET SESSION ESCAPE_STRING_WARNING = OFF")) {\r
+                    return $this->raiseError(null, null, null,\r
+                      'Unable to set escape_string_warning to off', __FUNCTION__);\r
+                }\r
+            }\r
+        }\r
+\r
+        return $connection;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ connect()\r
+\r
+    /**\r
+     * Connect to the database\r
+     *\r
+     * @return true on success, MDB2 Error Object on failure\r
+     * @access public\r
+     */\r
+    function connect()\r
+    {\r
+        if (is_resource($this->connection)) {\r
+            //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0\r
+            if (MDB2::areEquals($this->connected_dsn, $this->dsn)\r
+                && $this->connected_database_name == $this->database_name\r
+                && ($this->opened_persistent == $this->options['persistent'])\r
+            ) {\r
+                return MDB2_OK;\r
+            }\r
+            $this->disconnect(false);\r
+        }\r
+\r
+        if ($this->database_name) {\r
+            $connection = $this->_doConnect($this->dsn['username'],\r
+                                            $this->dsn['password'],\r
+                                            $this->database_name,\r
+                                            $this->options['persistent']);\r
+            if (PEAR::isError($connection)) {\r
+                return $connection;\r
+            }\r
+\r
+            $this->connection = $connection;\r
+            $this->connected_dsn = $this->dsn;\r
+            $this->connected_database_name = $this->database_name;\r
+            $this->opened_persistent = $this->options['persistent'];\r
+            $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;\r
+        }\r
+\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ setCharset()\r
+\r
+    /**\r
+     * Set the charset on the current connection\r
+     *\r
+     * @param string    charset\r
+     * @param resource  connection handle\r
+     *\r
+     * @return true on success, MDB2 Error Object on failure\r
+     */\r
+    function setCharset($charset, $connection = null)\r
+    {\r
+        if (null === $connection) {\r
+            $connection = $this->getConnection();\r
+            if (PEAR::isError($connection)) {\r
+                return $connection;\r
+            }\r
+        }\r
+        if (is_array($charset)) {\r
+            $charset   = array_shift($charset);\r
+            $this->warnings[] = 'postgresql does not support setting client collation';\r
+        }\r
+        $result = @pg_set_client_encoding($connection, $charset);\r
+        if ($result == -1) {\r
+            return $this->raiseError(null, null, null,\r
+                'Unable to set client charset: '.$charset, __FUNCTION__);\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ databaseExists()\r
+\r
+    /**\r
+     * check if given database name is exists?\r
+     *\r
+     * @param string $name    name of the database that should be checked\r
+     *\r
+     * @return mixed true/false on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function databaseExists($name)\r
+    {\r
+        $res = $this->_doConnect($this->dsn['username'],\r
+                                 $this->dsn['password'],\r
+                                 $this->escape($name),\r
+                                 $this->options['persistent']);\r
+        if (!PEAR::isError($res)) {\r
+            return true;\r
+        }\r
+\r
+        return false;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ disconnect()\r
+\r
+    /**\r
+     * Log out and disconnect from the database.\r
+     *\r
+     * @param  boolean $force if the disconnect should be forced even if the\r
+     *                        connection is opened persistently\r
+     * @return mixed true on success, false if not connected and error\r
+     *                object on error\r
+     * @access public\r
+     */\r
+    function disconnect($force = true)\r
+    {\r
+        if (is_resource($this->connection)) {\r
+            if ($this->in_transaction) {\r
+                $dsn = $this->dsn;\r
+                $database_name = $this->database_name;\r
+                $persistent = $this->options['persistent'];\r
+                $this->dsn = $this->connected_dsn;\r
+                $this->database_name = $this->connected_database_name;\r
+                $this->options['persistent'] = $this->opened_persistent;\r
+                $this->rollback();\r
+                $this->dsn = $dsn;\r
+                $this->database_name = $database_name;\r
+                $this->options['persistent'] = $persistent;\r
+            }\r
+\r
+            if (!$this->opened_persistent || $force) {\r
+                $ok = @pg_close($this->connection);\r
+                if (!$ok) {\r
+                    return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,\r
+                           null, null, null, __FUNCTION__);\r
+                }\r
+            }\r
+        } else {\r
+            return false;\r
+        }\r
+        return parent::disconnect($force);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ standaloneQuery()\r
+\r
+    /**\r
+     * execute a query as DBA\r
+     *\r
+     * @param string $query the SQL query\r
+     * @param mixed   $types  array that contains the types of the columns in\r
+     *                        the result set\r
+     * @param boolean $is_manip  if the query is a manipulation query\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function standaloneQuery($query, $types = null, $is_manip = false)\r
+    {\r
+        $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];\r
+        $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];\r
+        $connection = $this->_doConnect($user, $pass, $this->database_name, $this->options['persistent']);\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+\r
+        $offset = $this->offset;\r
+        $limit = $this->limit;\r
+        $this->offset = $this->limit = 0;\r
+        $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);\r
+\r
+        $result = $this->_doQuery($query, $is_manip, $connection, $this->database_name);\r
+        if (!PEAR::isError($result)) {\r
+            if ($is_manip) {\r
+                $result =  $this->_affectedRows($connection, $result);\r
+            } else {\r
+                $result =& $this->_wrapResult($result, $types, true, false, $limit, $offset);\r
+            }\r
+        }\r
+\r
+        @pg_close($connection);\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _doQuery()\r
+\r
+    /**\r
+     * Execute a query\r
+     * @param string $query  query\r
+     * @param boolean $is_manip  if the query is a manipulation query\r
+     * @param resource $connection\r
+     * @param string $database_name\r
+     * @return result or error object\r
+     * @access protected\r
+     */\r
+    function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)\r
+    {\r
+        $this->last_query = $query;\r
+        $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));\r
+        if ($result) {\r
+            if (PEAR::isError($result)) {\r
+                return $result;\r
+            }\r
+            $query = $result;\r
+        }\r
+        if ($this->options['disable_query']) {\r
+            $result = $is_manip ? 0 : null;\r
+            return $result;\r
+        }\r
+\r
+        if (null === $connection) {\r
+            $connection = $this->getConnection();\r
+            if (PEAR::isError($connection)) {\r
+                return $connection;\r
+            }\r
+        }\r
+\r
+        $function = $this->options['multi_query'] ? 'pg_send_query' : 'pg_query';\r
+        $result = @$function($connection, $query);\r
+        if (!$result) {\r
+            $err = $this->raiseError(null, null, null,\r
+                'Could not execute statement', __FUNCTION__);\r
+            return $err;\r
+        } elseif ($this->options['multi_query']) {\r
+            if (!($result = @pg_get_result($connection))) {\r
+                $err = $this->raiseError(null, null, null,\r
+                        'Could not get the first result from a multi query', __FUNCTION__);\r
+                return $err;\r
+            }\r
+        }\r
+\r
+        $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _affectedRows()\r
+\r
+    /**\r
+     * Returns the number of rows affected\r
+     *\r
+     * @param resource $result\r
+     * @param resource $connection\r
+     * @return mixed MDB2 Error Object or the number of rows affected\r
+     * @access private\r
+     */\r
+    function _affectedRows($connection, $result = null)\r
+    {\r
+        if (null === $connection) {\r
+            $connection = $this->getConnection();\r
+            if (PEAR::isError($connection)) {\r
+                return $connection;\r
+            }\r
+        }\r
+        return @pg_affected_rows($result);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _modifyQuery()\r
+\r
+    /**\r
+     * Changes a query string for various DBMS specific reasons\r
+     *\r
+     * @param string $query  query to modify\r
+     * @param boolean $is_manip  if it is a DML query\r
+     * @param integer $limit  limit the number of rows\r
+     * @param integer $offset  start reading from given offset\r
+     * @return string modified query\r
+     * @access protected\r
+     */\r
+    function _modifyQuery($query, $is_manip, $limit, $offset)\r
+    {\r
+        if ($limit > 0\r
+            && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)\r
+        ) {\r
+            $query = rtrim($query);\r
+            if (substr($query, -1) == ';') {\r
+                $query = substr($query, 0, -1);\r
+            }\r
+            if ($is_manip) {\r
+                $query = $this->_modifyManipQuery($query, $limit);\r
+            } else {\r
+                $query.= " LIMIT $limit OFFSET $offset";\r
+            }\r
+        }\r
+        return $query;\r
+    }\r
+    \r
+    // }}}\r
+    // {{{ _modifyManipQuery()\r
+    \r
+    /**\r
+     * Changes a manip query string for various DBMS specific reasons\r
+     *\r
+     * @param string $query  query to modify\r
+     * @param integer $limit  limit the number of rows\r
+     * @return string modified query\r
+     * @access protected\r
+     */\r
+    function _modifyManipQuery($query, $limit)\r
+    {\r
+        $pos = strpos(strtolower($query), 'where');\r
+        $where = $pos ? substr($query, $pos) : '';\r
+\r
+        $manip_clause = '(\bDELETE\b\s+(?:\*\s+)?\bFROM\b|\bUPDATE\b)';\r
+        $from_clause  = '([\w\.]+)';\r
+        $where_clause = '(?:(.*)\bWHERE\b\s+(.*))|(.*)';\r
+        $pattern = '/^'. $manip_clause . '\s+' . $from_clause .'(?:\s)*(?:'. $where_clause .')?$/i';\r
+        $matches = preg_match($pattern, $query, $match);\r
+        if ($matches) {\r
+            $manip = $match[1];\r
+            $from  = $match[2];\r
+            $what  = (count($matches) == 6) ? $match[5] : $match[3];\r
+            return $manip.' '.$from.' '.$what.' WHERE ctid=(SELECT ctid FROM '.$from.' '.$where.' LIMIT '.$limit.')';\r
+        }\r
+        //return error?\r
+        return $query;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getServerVersion()\r
+\r
+    /**\r
+     * return version information about the server\r
+     *\r
+     * @param bool   $native  determines if the raw version string should be returned\r
+     * @return mixed array/string with version information or MDB2 error object\r
+     * @access public\r
+     */\r
+    function getServerVersion($native = false)\r
+    {\r
+        $query = 'SHOW SERVER_VERSION';\r
+        if ($this->connected_server_info) {\r
+            $server_info = $this->connected_server_info;\r
+        } else {\r
+            $server_info = $this->queryOne($query, 'text');\r
+            if (PEAR::isError($server_info)) {\r
+                return $server_info;\r
+            }\r
+        }\r
+        // cache server_info\r
+        $this->connected_server_info = $server_info;\r
+        if (!$native && !PEAR::isError($server_info)) {\r
+            $tmp = explode('.', $server_info, 3);\r
+            if (empty($tmp[2])\r
+                && isset($tmp[1])\r
+                && preg_match('/(\d+)(.*)/', $tmp[1], $tmp2)\r
+            ) {\r
+                $server_info = array(\r
+                    'major' => $tmp[0],\r
+                    'minor' => $tmp2[1],\r
+                    'patch' => null,\r
+                    'extra' => $tmp2[2],\r
+                    'native' => $server_info,\r
+                );\r
+            } else {\r
+                $server_info = array(\r
+                    'major' => isset($tmp[0]) ? $tmp[0] : null,\r
+                    'minor' => isset($tmp[1]) ? $tmp[1] : null,\r
+                    'patch' => isset($tmp[2]) ? $tmp[2] : null,\r
+                    'extra' => null,\r
+                    'native' => $server_info,\r
+                );\r
+            }\r
+        }\r
+        return $server_info;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ prepare()\r
+\r
+    /**\r
+     * Prepares a query for multiple execution with execute().\r
+     * With some database backends, this is emulated.\r
+     * prepare() requires a generic query as string like\r
+     * 'INSERT INTO numbers VALUES(?,?)' or\r
+     * 'INSERT INTO numbers VALUES(:foo,:bar)'.\r
+     * The ? and :name and are placeholders which can be set using\r
+     * bindParam() and the query can be sent off using the execute() method.\r
+     * The allowed format for :name can be set with the 'bindname_format' option.\r
+     *\r
+     * @param string $query the query to prepare\r
+     * @param mixed   $types  array that contains the types of the placeholders\r
+     * @param mixed   $result_types  array that contains the types of the columns in\r
+     *                        the result set or MDB2_PREPARE_RESULT, if set to\r
+     *                        MDB2_PREPARE_MANIP the query is handled as a manipulation query\r
+     * @param mixed   $lobs   key (field) value (parameter) pair for all lob placeholders\r
+     * @return mixed resource handle for the prepared query on success, a MDB2\r
+     *        error on failure\r
+     * @access public\r
+     * @see bindParam, execute\r
+     */\r
+    function prepare($query, $types = null, $result_types = null, $lobs = array())\r
+    {\r
+        if ($this->options['emulate_prepared']) {\r
+            return parent::prepare($query, $types, $result_types, $lobs);\r
+        }\r
+        $is_manip = ($result_types === MDB2_PREPARE_MANIP);\r
+        $offset = $this->offset;\r
+        $limit = $this->limit;\r
+        $this->offset = $this->limit = 0;\r
+        $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));\r
+        if ($result) {\r
+            if (PEAR::isError($result)) {\r
+                return $result;\r
+            }\r
+            $query = $result;\r
+        }\r
+        $pgtypes = function_exists('pg_prepare') ? false : array();\r
+        if ($pgtypes !== false && !empty($types)) {\r
+            $this->loadModule('Datatype', null, true);\r
+        }\r
+        $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);\r
+        $placeholder_type_guess = $placeholder_type = null;\r
+        $question = '?';\r
+        $colon = ':';\r
+        $positions = array();\r
+        $position = $parameter = 0;\r
+        while ($position < strlen($query)) {\r
+            $q_position = strpos($query, $question, $position);\r
+            $c_position = strpos($query, $colon, $position);\r
+            //skip "::type" cast ("select id::varchar(20) from sometable where name=?")\r
+            $doublecolon_position = strpos($query, '::', $position);\r
+            if ($doublecolon_position !== false && $doublecolon_position == $c_position) {\r
+                $c_position = strpos($query, $colon, $position+2);\r
+            }\r
+            if ($q_position && $c_position) {\r
+                $p_position = min($q_position, $c_position);\r
+            } elseif ($q_position) {\r
+                $p_position = $q_position;\r
+            } elseif ($c_position) {\r
+                $p_position = $c_position;\r
+            } else {\r
+                break;\r
+            }\r
+            if (null === $placeholder_type) {\r
+                $placeholder_type_guess = $query[$p_position];\r
+            }\r
+            \r
+            $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);\r
+            if (PEAR::isError($new_pos)) {\r
+                return $new_pos;\r
+            }\r
+            if ($new_pos != $position) {\r
+                $position = $new_pos;\r
+                continue; //evaluate again starting from the new position\r
+            }\r
+\r
+            if ($query[$position] == $placeholder_type_guess) {\r
+                if (null === $placeholder_type) {\r
+                    $placeholder_type = $query[$p_position];\r
+                    $question = $colon = $placeholder_type;\r
+                    if (!empty($types) && is_array($types)) {\r
+                        if ($placeholder_type == ':') {\r
+                        } else {\r
+                            $types = array_values($types);\r
+                        }\r
+                    }\r
+                }\r
+                if ($placeholder_type_guess == '?') {\r
+                    $length = 1;\r
+                    $name = $parameter;\r
+                } else {\r
+                    $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';\r
+                    $param = preg_replace($regexp, '\\1', $query);\r
+                    if ($param === '') {\r
+                        $err = $this->raiseError(MDB2_ERROR_SYNTAX, null, null,\r
+                            'named parameter name must match "bindname_format" option', __FUNCTION__);\r
+                        return $err;\r
+                    }\r
+                    $length = strlen($param) + 1;\r
+                    $name = $param;\r
+                }\r
+                if ($pgtypes !== false) {\r
+                    if (is_array($types) && array_key_exists($name, $types)) {\r
+                        $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$name]);\r
+                    } elseif (is_array($types) && array_key_exists($parameter, $types)) {\r
+                        $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$parameter]);\r
+                    } else {\r
+                        $pgtypes[] = 'text';\r
+                    }\r
+                }\r
+                if (($key_parameter = array_search($name, $positions))) {\r
+                    $next_parameter = 1;\r
+                    foreach ($positions as $key => $value) {\r
+                        if ($key_parameter == $key) {\r
+                            break;\r
+                        }\r
+                        ++$next_parameter;\r
+                    }\r
+                } else {\r
+                    ++$parameter;\r
+                    $next_parameter = $parameter;\r
+                    $positions[] = $name;\r
+                }\r
+                $query = substr_replace($query, '$'.$parameter, $position, $length);\r
+                $position = $p_position + strlen($parameter);\r
+            } else {\r
+                $position = $p_position;\r
+            }\r
+        }\r
+        $connection = $this->getConnection();\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+        static $prep_statement_counter = 1;\r
+        $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand()));\r
+        $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);\r
+        if (false === $pgtypes) {\r
+            $result = @pg_prepare($connection, $statement_name, $query);\r
+            if (!$result) {\r
+                $err = $this->raiseError(null, null, null,\r
+                    'Unable to create prepared statement handle', __FUNCTION__);\r
+                return $err;\r
+            }\r
+        } else {\r
+            $types_string = '';\r
+            if ($pgtypes) {\r
+                $types_string = ' ('.implode(', ', $pgtypes).') ';\r
+            }\r
+            $query = 'PREPARE '.$statement_name.$types_string.' AS '.$query;\r
+            $statement = $this->_doQuery($query, true, $connection);\r
+            if (PEAR::isError($statement)) {\r
+                return $statement;\r
+            }\r
+        }\r
+\r
+        $class_name = 'MDB2_Statement_'.$this->phptype;\r
+        $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);\r
+        $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));\r
+        return $obj;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function getSequenceName($sqn)\r
+\r
+    /**\r
+     * adds sequence name formatting to a sequence name\r
+     *\r
+     * @param   string  name of the sequence\r
+     *\r
+     * @return  string  formatted sequence name\r
+     *\r
+     * @access  public\r
+     */\r
+    function getSequenceName($sqn)\r
+    {\r
+        if (false === $this->options['disable_smart_seqname']) {\r
+            if (strpos($sqn, '_') !== false) {\r
+                list($table, $field) = explode('_', $sqn, 2);\r
+            }\r
+            $schema_list = $this->queryOne("SELECT array_to_string(current_schemas(false), ',')");\r
+            if (PEAR::isError($schema_list) || empty($schema_list) || count($schema_list) < 2) {\r
+                $order_by = ' a.attnum';\r
+                $schema_clause = ' AND n.nspname=current_schema()';\r
+            } else {\r
+                $schemas = explode(',', $schema_list);\r
+                $schema_clause = ' AND n.nspname IN ('.$schema_list.')';\r
+                $counter = 1;\r
+                $order_by = ' CASE ';\r
+                foreach ($schemas as $schema) {\r
+                    $order_by .= ' WHEN n.nspname='.$schema.' THEN '.$counter++;\r
+                }\r
+                $order_by .= ' ELSE '.$counter.' END, a.attnum';\r
+            }\r
+\r
+            $query = "SELECT substring((SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)\r
+                           FROM pg_attrdef d\r
+                          WHERE d.adrelid = a.attrelid\r
+                            AND d.adnum = a.attnum\r
+                            AND a.atthasdef\r
+                        ) FROM 'nextval[^'']*''([^'']*)')\r
+                        FROM pg_attribute a\r
+                    LEFT JOIN pg_class c ON c.oid = a.attrelid\r
+                    LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef\r
+                    LEFT JOIN pg_namespace n ON c.relnamespace = n.oid\r
+                       WHERE (c.relname = ".$this->quote($sqn, 'text');\r
+            if (!empty($field)) {\r
+                $query .= " OR (c.relname = ".$this->quote($table, 'text')." AND a.attname = ".$this->quote($field, 'text').")";\r
+            }\r
+            $query .= "      )"\r
+                         .$schema_clause."\r
+                         AND NOT a.attisdropped\r
+                         AND a.attnum > 0\r
+                         AND pg_get_expr(d.adbin, d.adrelid) LIKE 'nextval%'\r
+                    ORDER BY ".$order_by;\r
+            $seqname = $this->queryOne($query);\r
+            if (!PEAR::isError($seqname) && !empty($seqname) && is_string($seqname)) {\r
+                return $seqname;\r
+            }\r
+        }\r
+\r
+        return parent::getSequenceName($sqn);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ nextID()\r
+\r
+    /**\r
+     * Returns the next free id of a sequence\r
+     *\r
+     * @param string $seq_name name of the sequence\r
+     * @param boolean $ondemand when true the sequence is\r
+     *                          automatic created, if it\r
+     *                          not exists\r
+     * @return mixed MDB2 Error Object or id\r
+     * @access public\r
+     */\r
+    function nextID($seq_name, $ondemand = true)\r
+    {\r
+        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);\r
+        $query = "SELECT NEXTVAL('$sequence_name')";\r
+        $this->pushErrorHandling(PEAR_ERROR_RETURN);\r
+        $this->expectError(MDB2_ERROR_NOSUCHTABLE);\r
+        $result = $this->queryOne($query, 'integer');\r
+        $this->popExpect();\r
+        $this->popErrorHandling();\r
+        if (PEAR::isError($result)) {\r
+            if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {\r
+                $this->loadModule('Manager', null, true);\r
+                $result = $this->manager->createSequence($seq_name);\r
+                if (PEAR::isError($result)) {\r
+                    return $this->raiseError($result, null, null,\r
+                        'on demand sequence could not be created', __FUNCTION__);\r
+                }\r
+                return $this->nextId($seq_name, false);\r
+            }\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ lastInsertID()\r
+\r
+    /**\r
+     * Returns the autoincrement ID if supported or $id or fetches the current\r
+     * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)\r
+     *\r
+     * @param string $table name of the table into which a new row was inserted\r
+     * @param string $field name of the field into which a new row was inserted\r
+     * @return mixed MDB2 Error Object or id\r
+     * @access public\r
+     */\r
+    function lastInsertID($table = null, $field = null)\r
+    {\r
+        if (empty($table) && empty($field)) {\r
+            return $this->queryOne('SELECT lastval()', 'integer');\r
+        }\r
+        $seq = $table.(empty($field) ? '' : '_'.$field);\r
+        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq), true);\r
+        return $this->queryOne("SELECT currval('$sequence_name')", 'integer');\r
+    }\r
+\r
+    // }}}\r
+    // {{{ currID()\r
+\r
+    /**\r
+     * Returns the current id of a sequence\r
+     *\r
+     * @param string $seq_name name of the sequence\r
+     * @return mixed MDB2 Error Object or id\r
+     * @access public\r
+     */\r
+    function currID($seq_name)\r
+    {\r
+        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);\r
+        return $this->queryOne("SELECT last_value FROM $sequence_name", 'integer');\r
+    }\r
+}\r
+\r
+/**\r
+ * MDB2 PostGreSQL result driver\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Paul Cooper <pgc@ucecom.com>\r
+ */\r
+class MDB2_Result_pgsql extends MDB2_Result_Common\r
+{\r
+    // }}}\r
+    // {{{ fetchRow()\r
+\r
+    /**\r
+     * Fetch a row and insert the data into an existing array.\r
+     *\r
+     * @param int       $fetchmode  how the array data should be indexed\r
+     * @param int    $rownum    number of the row where the data can be found\r
+     * @return int data array on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)\r
+    {\r
+        if (null !== $rownum) {\r
+            $seek = $this->seek($rownum);\r
+            if (PEAR::isError($seek)) {\r
+                return $seek;\r
+            }\r
+        }\r
+        if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {\r
+            $fetchmode = $this->db->fetchmode;\r
+        }\r
+        if ($fetchmode & MDB2_FETCHMODE_ASSOC) {\r
+            $row = @pg_fetch_array($this->result, null, PGSQL_ASSOC);\r
+            if (is_array($row)\r
+                && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE\r
+            ) {\r
+                $row = array_change_key_case($row, $this->db->options['field_case']);\r
+            }\r
+        } else {\r
+            $row = @pg_fetch_row($this->result);\r
+        }\r
+        if (!$row) {\r
+            if (false === $this->result) {\r
+                $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,\r
+                    'resultset has already been freed', __FUNCTION__);\r
+                return $err;\r
+            }\r
+            return null;\r
+        }\r
+        $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;\r
+        $rtrim = false;\r
+        if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {\r
+            if (empty($this->types)) {\r
+                $mode += MDB2_PORTABILITY_RTRIM;\r
+            } else {\r
+                $rtrim = true;\r
+            }\r
+        }\r
+        if ($mode) {\r
+            $this->db->_fixResultArrayValues($row, $mode);\r
+        }\r
+        if (!empty($this->types)) {\r
+            $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);\r
+        }\r
+        if (!empty($this->values)) {\r
+            $this->_assignBindColumns($row);\r
+        }\r
+        if ($fetchmode === MDB2_FETCHMODE_OBJECT) {\r
+            $object_class = $this->db->options['fetch_class'];\r
+            if ($object_class == 'stdClass') {\r
+                $row = (object) $row;\r
+            } else {\r
+                $rowObj = new $object_class($row);\r
+                $row = $rowObj;\r
+            }\r
+        }\r
+        ++$this->rownum;\r
+        return $row;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getColumnNames()\r
+\r
+    /**\r
+     * Retrieve the names of columns returned by the DBMS in a query result.\r
+     *\r
+     * @return  mixed   Array variable that holds the names of columns as keys\r
+     *                  or an MDB2 error on failure.\r
+     *                  Some DBMS may not return any columns when the result set\r
+     *                  does not contain any rows.\r
+     * @access private\r
+     */\r
+    function _getColumnNames()\r
+    {\r
+        $columns = array();\r
+        $numcols = $this->numCols();\r
+        if (PEAR::isError($numcols)) {\r
+            return $numcols;\r
+        }\r
+        for ($column = 0; $column < $numcols; $column++) {\r
+            $column_name = @pg_field_name($this->result, $column);\r
+            $columns[$column_name] = $column;\r
+        }\r
+        if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $columns = array_change_key_case($columns, $this->db->options['field_case']);\r
+        }\r
+        return $columns;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ numCols()\r
+\r
+    /**\r
+     * Count the number of columns returned by the DBMS in a query result.\r
+     *\r
+     * @access public\r
+     * @return mixed integer value with the number of columns, a MDB2 error\r
+     *                       on failure\r
+     */\r
+    function numCols()\r
+    {\r
+        $cols = @pg_num_fields($this->result);\r
+        if (null === $cols) {\r
+            if (false === $this->result) {\r
+                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,\r
+                    'resultset has already been freed', __FUNCTION__);\r
+            }\r
+            if (null === $this->result) {\r
+                return count($this->types);\r
+            }\r
+            return $this->db->raiseError(null, null, null,\r
+                'Could not get column count', __FUNCTION__);\r
+        }\r
+        return $cols;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ nextResult()\r
+\r
+    /**\r
+     * Move the internal result pointer to the next available result\r
+     *\r
+     * @return true on success, false if there is no more result set or an error object on failure\r
+     * @access public\r
+     */\r
+    function nextResult()\r
+    {\r
+        $connection = $this->db->getConnection();\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+\r
+        if (!($this->result = @pg_get_result($connection))) {\r
+            return false;\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ free()\r
+\r
+    /**\r
+     * Free the internal resources associated with result.\r
+     *\r
+     * @return boolean true on success, false if result is invalid\r
+     * @access public\r
+     */\r
+    function free()\r
+    {\r
+        if (is_resource($this->result) && $this->db->connection) {\r
+            $free = @pg_free_result($this->result);\r
+            if (false === $free) {\r
+                return $this->db->raiseError(null, null, null,\r
+                    'Could not free result', __FUNCTION__);\r
+            }\r
+        }\r
+        $this->result = false;\r
+        return MDB2_OK;\r
+    }\r
+}\r
+\r
+/**\r
+ * MDB2 PostGreSQL buffered result driver\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Paul Cooper <pgc@ucecom.com>\r
+ */\r
+class MDB2_BufferedResult_pgsql extends MDB2_Result_pgsql\r
+{\r
+    // {{{ seek()\r
+\r
+    /**\r
+     * Seek to a specific row in a result set\r
+     *\r
+     * @param int    $rownum    number of the row where the data can be found\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function seek($rownum = 0)\r
+    {\r
+        if ($this->rownum != ($rownum - 1) && !@pg_result_seek($this->result, $rownum)) {\r
+            if (false === $this->result) {\r
+                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,\r
+                    'resultset has already been freed', __FUNCTION__);\r
+            }\r
+            if (null === $this->result) {\r
+                return MDB2_OK;\r
+            }\r
+            return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,\r
+                'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);\r
+        }\r
+        $this->rownum = $rownum - 1;\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ valid()\r
+\r
+    /**\r
+     * Check if the end of the result set has been reached\r
+     *\r
+     * @return mixed true or false on sucess, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function valid()\r
+    {\r
+        $numrows = $this->numRows();\r
+        if (PEAR::isError($numrows)) {\r
+            return $numrows;\r
+        }\r
+        return $this->rownum < ($numrows - 1);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ numRows()\r
+\r
+    /**\r
+     * Returns the number of rows in a result object\r
+     *\r
+     * @return mixed MDB2 Error Object or the number of rows\r
+     * @access public\r
+     */\r
+    function numRows()\r
+    {\r
+        $rows = @pg_num_rows($this->result);\r
+        if (null === $rows) {\r
+            if (false === $this->result) {\r
+                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,\r
+                    'resultset has already been freed', __FUNCTION__);\r
+            }\r
+            if (null === $this->result) {\r
+                return 0;\r
+            }\r
+            return $this->db->raiseError(null, null, null,\r
+                'Could not get row count', __FUNCTION__);\r
+        }\r
+        return $rows;\r
+    }\r
+}\r
+\r
+/**\r
+ * MDB2 PostGreSQL statement driver\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Paul Cooper <pgc@ucecom.com>\r
+ */\r
+class MDB2_Statement_pgsql extends MDB2_Statement_Common\r
+{\r
+    // {{{ _execute()\r
+\r
+    /**\r
+     * Execute a prepared query statement helper method.\r
+     *\r
+     * @param mixed $result_class string which specifies which result class to use\r
+     * @param mixed $result_wrap_class string which specifies which class to wrap results in\r
+     *\r
+     * @return mixed MDB2_Result or integer (affected rows) on success,\r
+     *               a MDB2 error on failure\r
+     * @access private\r
+     */\r
+    function _execute($result_class = true, $result_wrap_class = false)\r
+    {\r
+        if (null === $this->statement) {\r
+            return parent::_execute($result_class, $result_wrap_class);\r
+        }\r
+        $this->db->last_query = $this->query;\r
+        $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));\r
+        if ($this->db->getOption('disable_query')) {\r
+            $result = $this->is_manip ? 0 : null;\r
+            return $result;\r
+        }\r
+\r
+        $connection = $this->db->getConnection();\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+\r
+        $query = false;\r
+        $parameters = array();\r
+        // todo: disabled until pg_execute() bytea issues are cleared up\r
+        if (true || !function_exists('pg_execute')) {\r
+            $query = 'EXECUTE '.$this->statement;\r
+        }\r
+        if (!empty($this->positions)) {\r
+            foreach ($this->positions as $parameter) {\r
+                if (!array_key_exists($parameter, $this->values)) {\r
+                    return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                        'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);\r
+                }\r
+                $value = $this->values[$parameter];\r
+                $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;\r
+                if (is_resource($value) || $type == 'clob' || $type == 'blob' || $this->db->options['lob_allow_url_include']) {\r
+                    if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {\r
+                        if ($match[1] == 'file://') {\r
+                            $value = $match[2];\r
+                        }\r
+                        $value = @fopen($value, 'r');\r
+                        $close = true;\r
+                    }\r
+                    if (is_resource($value)) {\r
+                        $data = '';\r
+                        while (!@feof($value)) {\r
+                            $data.= @fread($value, $this->db->options['lob_buffer_length']);\r
+                        }\r
+                        if ($close) {\r
+                            @fclose($value);\r
+                        }\r
+                        $value = $data;\r
+                    }\r
+                }\r
+                $quoted = $this->db->quote($value, $type, $query);\r
+                if (PEAR::isError($quoted)) {\r
+                    return $quoted;\r
+                }\r
+                $parameters[] = $quoted;\r
+            }\r
+            if ($query) {\r
+                $query.= ' ('.implode(', ', $parameters).')';\r
+            }\r
+        }\r
+\r
+        if (!$query) {\r
+            $result = @pg_execute($connection, $this->statement, $parameters);\r
+            if (!$result) {\r
+                $err = $this->db->raiseError(null, null, null,\r
+                    'Unable to execute statement', __FUNCTION__);\r
+                return $err;\r
+            }\r
+        } else {\r
+            $result = $this->db->_doQuery($query, $this->is_manip, $connection);\r
+            if (PEAR::isError($result)) {\r
+                return $result;\r
+            }\r
+        }\r
+\r
+        if ($this->is_manip) {\r
+            $affected_rows = $this->db->_affectedRows($connection, $result);\r
+            return $affected_rows;\r
+        }\r
+\r
+        $result = $this->db->_wrapResult($result, $this->result_types,\r
+            $result_class, $result_wrap_class, $this->limit, $this->offset);\r
+        $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ free()\r
+\r
+    /**\r
+     * Release resources allocated for the specified prepared query.\r
+     *\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function free()\r
+    {\r
+        if (null === $this->positions) {\r
+            return $this->db->raiseError(MDB2_ERROR, null, null,\r
+                'Prepared statement has already been freed', __FUNCTION__);\r
+        }\r
+        $result = MDB2_OK;\r
+\r
+        if (null !== $this->statement) {\r
+            $connection = $this->db->getConnection();\r
+            if (PEAR::isError($connection)) {\r
+                return $connection;\r
+            }\r
+            $query = 'DEALLOCATE PREPARE '.$this->statement;\r
+            $result = $this->db->_doQuery($query, true, $connection);\r
+        }\r
+\r
+        parent::free();\r
+        return $result;\r
+    }\r
+}\r
 ?>
\ No newline at end of file
index 5d2ad27d01635d94b0fe112d63f1e9f205448f52..e8f1bba583cdf9651b32a646844de0ed6eec0c99 100644 (file)
-<?php
-// vim: set et ts=4 sw=4 fdm=marker:
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: sqlite.php,v 1.165 2008/11/30 14:28:01 afz Exp $
-//
-
-/**
- * MDB2 SQLite driver
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_sqlite extends MDB2_Driver_Common
-{
-    // {{{ properties
-    var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => false);
-
-    var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
-
-    var $_lasterror = '';
-
-    var $fix_assoc_fields_names = false;
-
-    // }}}
-    // {{{ constructor
-
-    /**
-     * Constructor
-     */
-    function __construct()
-    {
-        parent::__construct();
-
-        $this->phptype = 'sqlite';
-        $this->dbsyntax = 'sqlite';
-
-        $this->supported['sequences'] = 'emulated';
-        $this->supported['indexes'] = true;
-        $this->supported['affected_rows'] = true;
-        $this->supported['summary_functions'] = true;
-        $this->supported['order_by_text'] = true;
-        $this->supported['current_id'] = 'emulated';
-        $this->supported['limit_queries'] = true;
-        $this->supported['LOBs'] = true;
-        $this->supported['replace'] = true;
-        $this->supported['transactions'] = true;
-        $this->supported['savepoints'] = false;
-        $this->supported['sub_selects'] = true;
-        $this->supported['triggers'] = true;
-        $this->supported['auto_increment'] = true;
-        $this->supported['primary_key'] = false; // requires alter table implementation
-        $this->supported['result_introspection'] = false; // not implemented
-        $this->supported['prepared_statements'] = 'emulated';
-        $this->supported['identifier_quoting'] = true;
-        $this->supported['pattern_escaping'] = false;
-        $this->supported['new_link'] = false;
-
-        $this->options['DBA_username'] = false;
-        $this->options['DBA_password'] = false;
-        $this->options['base_transaction_name'] = '___php_MDB2_sqlite_auto_commit_off';
-        $this->options['fixed_float'] = 0;
-        $this->options['database_path'] = '';
-        $this->options['database_extension'] = '';
-        $this->options['server_version'] = '';
-        $this->options['max_identifiers_length'] = 128; //no real limit
-    }
-
-    // }}}
-    // {{{ errorInfo()
-
-    /**
-     * This method is used to collect information about an error
-     *
-     * @param integer $error
-     * @return array
-     * @access public
-     */
-    function errorInfo($error = null)
-    {
-        $native_code = null;
-        if ($this->connection) {
-            $native_code = @sqlite_last_error($this->connection);
-        }
-        $native_msg = $this->_lasterror
-            ? html_entity_decode($this->_lasterror) : @sqlite_error_string($native_code);
-            
-        // PHP 5.2+ prepends the function name to $php_errormsg, so we need
-        // this hack to work around it, per bug #9599.
-        $native_msg = preg_replace('/^sqlite[a-z_]+\(\)[^:]*: /', '', $native_msg);
-
-        if (is_null($error)) {
-            static $error_regexps;
-            if (empty($error_regexps)) {
-                $error_regexps = array(
-                    '/^no such table:/' => MDB2_ERROR_NOSUCHTABLE,
-                    '/^no such index:/' => MDB2_ERROR_NOT_FOUND,
-                    '/^(table|index) .* already exists$/' => MDB2_ERROR_ALREADY_EXISTS,
-                    '/PRIMARY KEY must be unique/i' => MDB2_ERROR_CONSTRAINT,
-                    '/is not unique/' => MDB2_ERROR_CONSTRAINT,
-                    '/columns .* are not unique/i' => MDB2_ERROR_CONSTRAINT,
-                    '/uniqueness constraint failed/' => MDB2_ERROR_CONSTRAINT,
-                    '/may not be NULL/' => MDB2_ERROR_CONSTRAINT_NOT_NULL,
-                    '/^no such column:/' => MDB2_ERROR_NOSUCHFIELD,
-                    '/no column named/' => MDB2_ERROR_NOSUCHFIELD,
-                    '/column not present in both tables/i' => MDB2_ERROR_NOSUCHFIELD,
-                    '/^near ".*": syntax error$/' => MDB2_ERROR_SYNTAX,
-                    '/[0-9]+ values for [0-9]+ columns/i' => MDB2_ERROR_VALUE_COUNT_ON_ROW,
-                 );
-            }
-            foreach ($error_regexps as $regexp => $code) {
-                if (preg_match($regexp, $native_msg)) {
-                    $error = $code;
-                    break;
-                }
-            }
-        }
-        return array($error, $native_code, $native_msg);
-    }
-
-    // }}}
-    // {{{ escape()
-
-    /**
-     * Quotes a string so it can be safely used in a query. It will quote
-     * the text so it can safely be used within a query.
-     *
-     * @param   string  the input string to quote
-     * @param   bool    escape wildcards
-     *
-     * @return  string  quoted string
-     *
-     * @access  public
-     */
-    function escape($text, $escape_wildcards = false)
-    {
-        $text = @sqlite_escape_string($text);
-        return $text;
-    }
-
-    // }}}
-    // {{{ beginTransaction()
-
-    /**
-     * Start a transaction or set a savepoint.
-     *
-     * @param   string  name of a savepoint to set
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function beginTransaction($savepoint = null)
-    {
-        $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
-        if (!is_null($savepoint)) {
-            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'savepoints are not supported', __FUNCTION__);
-        } elseif ($this->in_transaction) {
-            return MDB2_OK;  //nothing to do
-        }
-        if (!$this->destructor_registered && $this->opened_persistent) {
-            $this->destructor_registered = true;
-            register_shutdown_function('MDB2_closeOpenTransactions');
-        }
-        $query = 'BEGIN TRANSACTION '.$this->options['base_transaction_name'];
-        $result =$this->_doQuery($query, true);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        $this->in_transaction = true;
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ commit()
-
-    /**
-     * Commit the database changes done during a transaction that is in
-     * progress or release a savepoint. This function may only be called when
-     * auto-committing is disabled, otherwise it will fail. Therefore, a new
-     * transaction is implicitly started after committing the pending changes.
-     *
-     * @param   string  name of a savepoint to release
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function commit($savepoint = null)
-    {
-        $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
-        if (!$this->in_transaction) {
-            return $this->raiseError(MDB2_ERROR_INVALID, null, null,
-                'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
-        }
-        if (!is_null($savepoint)) {
-            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'savepoints are not supported', __FUNCTION__);
-        }
-
-        $query = 'COMMIT TRANSACTION '.$this->options['base_transaction_name'];
-        $result =$this->_doQuery($query, true);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        $this->in_transaction = false;
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{
-
-    /**
-     * Cancel any database changes done during a transaction or since a specific
-     * savepoint that is in progress. This function may only be called when
-     * auto-committing is disabled, otherwise it will fail. Therefore, a new
-     * transaction is implicitly started after canceling the pending changes.
-     *
-     * @param   string  name of a savepoint to rollback to
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     */
-    function rollback($savepoint = null)
-    {
-        $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
-        if (!$this->in_transaction) {
-            return $this->raiseError(MDB2_ERROR_INVALID, null, null,
-                'rollback cannot be done changes are auto committed', __FUNCTION__);
-        }
-        if (!is_null($savepoint)) {
-            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'savepoints are not supported', __FUNCTION__);
-        }
-
-        $query = 'ROLLBACK TRANSACTION '.$this->options['base_transaction_name'];
-        $result =$this->_doQuery($query, true);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        $this->in_transaction = false;
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ function setTransactionIsolation()
-
-    /**
-     * Set the transacton isolation level.
-     *
-     * @param   string  standard isolation level
-     *                  READ UNCOMMITTED (allows dirty reads)
-     *                  READ COMMITTED (prevents dirty reads)
-     *                  REPEATABLE READ (prevents nonrepeatable reads)
-     *                  SERIALIZABLE (prevents phantom reads)
-     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
-     *
-     * @access  public
-     * @since   2.1.1
-     */
-    static function setTransactionIsolation($isolation,$options=array())
-    {
-        $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
-        switch ($isolation) {
-        case 'READ UNCOMMITTED':
-            $isolation = 0;
-            break;
-        case 'READ COMMITTED':
-        case 'REPEATABLE READ':
-        case 'SERIALIZABLE':
-            $isolation = 1;
-            break;
-        default:
-            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'isolation level is not supported: '.$isolation, __FUNCTION__);
-        }
-
-        $query = "PRAGMA read_uncommitted=$isolation";
-        return $this->_doQuery($query, true);
-    }
-
-    // }}}
-    // {{{ getDatabaseFile()
-
-    /**
-     * Builds the string with path+dbname+extension
-     *
-     * @return string full database path+file
-     * @access protected
-     */
-    function _getDatabaseFile($database_name)
-    {
-        if ($database_name === '' || $database_name === ':memory:') {
-            return $database_name;
-        }
-        return $this->options['database_path'].$database_name.$this->options['database_extension'];
-    }
-
-    // }}}
-    // {{{ connect()
-
-    /**
-     * Connect to the database
-     *
-     * @return true on success, MDB2 Error Object on failure
-     **/
-    function connect()
-    {
-               $datadir=OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" );
-        $database_file = $this->_getDatabaseFile($this->database_name);
-        if (is_resource($this->connection)) {
-            //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
-            if (MDB2::areEquals($this->connected_dsn, $this->dsn)
-                && $this->connected_database_name == $database_file
-                && $this->opened_persistent == $this->options['persistent']
-            ) {
-                return MDB2_OK;
-            }
-            $this->disconnect(false);
-        }
-
-        if (!PEAR::loadExtension($this->phptype)) {
-            return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
-        }
-
-        if (empty($this->database_name)) {
-            return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
-            'unable to establish a connection', __FUNCTION__);
-        }
-
-        if ($database_file !== ':memory:') {
-                       if(!strpos($database_file,'.db')){
-                               $database_file="$datadir/$database_file.db";
-                       }
-            if (!file_exists($database_file)) {
-                if (!touch($database_file)) {
-                    return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                        'Could not create database file', __FUNCTION__);
-                }
-                if (!isset($this->dsn['mode'])
-                    || !is_numeric($this->dsn['mode'])
-                ) {
-                    $mode = 0644;
-                } else {
-                    $mode = octdec($this->dsn['mode']);
-                }
-                if (!chmod($database_file, $mode)) {
-                    return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                        'Could not be chmodded database file', __FUNCTION__);
-                }
-                if (!file_exists($database_file)) {
-                    return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                        'Could not be found database file', __FUNCTION__);
-                }
-            }
-            if (!is_file($database_file)) {
-                return $this->raiseError(MDB2_ERROR_INVALID, null, null,
-                        'Database is a directory name', __FUNCTION__);
-            }
-            if (!is_readable($database_file)) {
-                return $this->raiseError(MDB2_ERROR_ACCESS_VIOLATION, null, null,
-                        'Could not read database file', __FUNCTION__);
-            }
-        }
-
-        $connect_function = ($this->options['persistent'] ? 'sqlite_popen' : 'sqlite_open');
-        $php_errormsg = '';
-        if (version_compare('5.1.0', PHP_VERSION, '>')) {
-            @ini_set('track_errors', true);
-            echo 1;
-            $connection = @$connect_function($database_file);
-            echo 2;
-            @ini_restore('track_errors');
-        } else {
-            $connection = @$connect_function($database_file, 0666, $php_errormsg);
-        }
-        $this->_lasterror = $php_errormsg;
-        if (!$connection) {
-            return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
-            'unable to establish a connection', __FUNCTION__);
-        }
-
-        if ($this->fix_assoc_fields_names ||
-            $this->options['portability'] & MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES)
-        {
-            @sqlite_query("PRAGMA short_column_names = 1", $connection);
-            $this->fix_assoc_fields_names = true;
-        }
-
-        $this->connection = $connection;
-        $this->connected_dsn = $this->dsn;
-        $this->connected_database_name = $database_file;
-        $this->opened_persistent = $this->getoption('persistent');
-        $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
-
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ databaseExists()
-
-    /**
-     * check if given database name is exists?
-     *
-     * @param string $name    name of the database that should be checked
-     *
-     * @return mixed true/false on success, a MDB2 error on failure
-     * @access public
-     */
-    function databaseExists($name)
-    {
-        $database_file = $this->_getDatabaseFile($name);
-        $result = file_exists($database_file);
-        return $result;
-    }
-
-    // }}}
-    // {{{ disconnect()
-
-    /**
-     * Log out and disconnect from the database.
-     *
-     * @param  boolean $force if the disconnect should be forced even if the
-     *                        connection is opened persistently
-     * @return mixed true on success, false if not connected and error
-     *                object on error
-     * @access public
-     */
-    function disconnect($force = true)
-    {
-        if (is_resource($this->connection)) {
-            if ($this->in_transaction) {
-                $dsn = $this->dsn;
-                $database_name = $this->database_name;
-                $persistent = $this->options['persistent'];
-                $this->dsn = $this->connected_dsn;
-                $this->database_name = $this->connected_database_name;
-                $this->options['persistent'] = $this->opened_persistent;
-                $this->rollback();
-                $this->dsn = $dsn;
-                $this->database_name = $database_name;
-                $this->options['persistent'] = $persistent;
-            }
-
-            if (!$this->opened_persistent || $force) {
-                @sqlite_close($this->connection);
-            }
-        } else {
-            return false;
-        }
-        return parent::disconnect($force);
-    }
-
-    // }}}
-    // {{{ _doQuery()
-
-    /**
-     * Execute a query
-     * @param string $query  query
-     * @param boolean $is_manip  if the query is a manipulation query
-     * @param resource $connection
-     * @param string $database_name
-     * @return result or error object
-     * @access protected
-     */
-    function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
-    {
-        $this->last_query = $query;
-        $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
-        if ($result) {
-            if (PEAR::isError($result)) {
-                return $result;
-            }
-            $query = $result;
-        }
-        if ($this->options['disable_query']) {
-            $result = $is_manip ? 0 : null;
-            return $result;
-        }
-
-        if (is_null($connection)) {
-            $connection = $this->getConnection();
-            if (PEAR::isError($connection)) {
-                return $connection;
-            }
-        }
-
-        $function = $this->options['result_buffering']
-            ? 'sqlite_query' : 'sqlite_unbuffered_query';
-        $php_errormsg = '';
-        if (version_compare('5.1.0', PHP_VERSION, '>')) {
-            @ini_set('track_errors', true);
-            do {
-                $result = @$function($query.';', $connection);
-            } while (sqlite_last_error($connection) == SQLITE_SCHEMA);
-            @ini_restore('track_errors');
-        } else {
-            do {
-                $result = @$function($query.';', $connection, SQLITE_BOTH, $php_errormsg);
-            } while (sqlite_last_error($connection) == SQLITE_SCHEMA);
-        }
-        $this->_lasterror = $php_errormsg;
-
-        if (!$result) {
-            $err =$this->raiseError(null, null, null,
-                'Could not execute statement', __FUNCTION__);
-            return $err;
-        }
-
-        $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
-        return $result;
-    }
-
-    // }}}
-    // {{{ _affectedRows()
-
-    /**
-     * Returns the number of rows affected
-     *
-     * @param resource $result
-     * @param resource $connection
-     * @return mixed MDB2 Error Object or the number of rows affected
-     * @access private
-     */
-    function _affectedRows($connection, $result = null)
-    {
-        if (is_null($connection)) {
-            $connection = $this->getConnection();
-            if (PEAR::isError($connection)) {
-                return $connection;
-            }
-        }
-        return @sqlite_changes($connection);
-    }
-
-    // }}}
-    // {{{ _modifyQuery()
-
-    /**
-     * Changes a query string for various DBMS specific reasons
-     *
-     * @param string $query  query to modify
-     * @param boolean $is_manip  if it is a DML query
-     * @param integer $limit  limit the number of rows
-     * @param integer $offset  start reading from given offset
-     * @return string modified query
-     * @access protected
-     */
-    function _modifyQuery($query, $is_manip, $limit, $offset)
-    {
-        if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {
-            if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
-                $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
-                                      'DELETE FROM \1 WHERE 1=1', $query);
-            }
-        }
-        if ($limit > 0
-            && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
-        ) {
-            $query = rtrim($query);
-            if (substr($query, -1) == ';') {
-                $query = substr($query, 0, -1);
-            }
-            if ($is_manip) {
-                $query.= " LIMIT $limit";
-            } else {
-                $query.= " LIMIT $offset,$limit";
-            }
-        }
-        return $query;
-    }
-
-    // }}}
-    // {{{ getServerVersion()
-
-    /**
-     * return version information about the server
-     *
-     * @param bool   $native  determines if the raw version string should be returned
-     * @return mixed array/string with version information or MDB2 error object
-     * @access public
-     */
-    function getServerVersion($native = false)
-    {
-        $server_info = false;
-        if ($this->connected_server_info) {
-            $server_info = $this->connected_server_info;
-        } elseif ($this->options['server_version']) {
-            $server_info = $this->options['server_version'];
-        } elseif (function_exists('sqlite_libversion')) {
-            $server_info = @sqlite_libversion();
-        }
-        if (!$server_info) {
-            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
-                'Requires either the "server_version" option or the sqlite_libversion() function', __FUNCTION__);
-        }
-        // cache server_info
-        $this->connected_server_info = $server_info;
-        if (!$native) {
-            $tmp = explode('.', $server_info, 3);
-            $server_info = array(
-                'major' => isset($tmp[0]) ? $tmp[0] : null,
-                'minor' => isset($tmp[1]) ? $tmp[1] : null,
-                'patch' => isset($tmp[2]) ? $tmp[2] : null,
-                'extra' => null,
-                'native' => $server_info,
-            );
-        }
-        return $server_info;
-    }
-
-    // }}}
-    // {{{ replace()
-
-    /**
-     * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
-     * query, except that if there is already a row in the table with the same
-     * key field values, the old row is deleted before the new row is inserted.
-     *
-     * The REPLACE type of query does not make part of the SQL standards. Since
-     * practically only SQLite implements it natively, this type of query is
-     * emulated through this method for other DBMS using standard types of
-     * queries inside a transaction to assure the atomicity of the operation.
-     *
-     * @access public
-     *
-     * @param string $table name of the table on which the REPLACE query will
-     *  be executed.
-     * @param array $fields associative array that describes the fields and the
-     *  values that will be inserted or updated in the specified table. The
-     *  indexes of the array are the names of all the fields of the table. The
-     *  values of the array are also associative arrays that describe the
-     *  values and other properties of the table fields.
-     *
-     *  Here follows a list of field properties that need to be specified:
-     *
-     *    value:
-     *          Value to be assigned to the specified field. This value may be
-     *          of specified in database independent type format as this
-     *          function can perform the necessary datatype conversions.
-     *
-     *    Default:
-     *          this property is required unless the Null property
-     *          is set to 1.
-     *
-     *    type
-     *          Name of the type of the field. Currently, all types Metabase
-     *          are supported except for clob and blob.
-     *
-     *    Default: no type conversion
-     *
-     *    null
-     *          Boolean property that indicates that the value for this field
-     *          should be set to null.
-     *
-     *          The default value for fields missing in INSERT queries may be
-     *          specified the definition of a table. Often, the default value
-     *          is already null, but since the REPLACE may be emulated using
-     *          an UPDATE query, make sure that all fields of the table are
-     *          listed in this function argument array.
-     *
-     *    Default: 0
-     *
-     *    key
-     *          Boolean property that indicates that this field should be
-     *          handled as a primary key or at least as part of the compound
-     *          unique index of the table that will determine the row that will
-     *          updated if it exists or inserted a new row otherwise.
-     *
-     *          This function will fail if no key field is specified or if the
-     *          value of a key field is set to null because fields that are
-     *          part of unique index they may not be null.
-     *
-     *    Default: 0
-     *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     */
-    function replace($table, $fields)
-    {
-        $count = count($fields);
-        $query = $values = '';
-        $keys = $colnum = 0;
-        for (reset($fields); $colnum < $count; next($fields), $colnum++) {
-            $name = key($fields);
-            if ($colnum > 0) {
-                $query .= ',';
-                $values.= ',';
-            }
-            $query.= $this->quoteIdentifier($name, true);
-            if (isset($fields[$name]['null']) && $fields[$name]['null']) {
-                $value = 'NULL';
-            } else {
-                $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
-                $value = $this->quote($fields[$name]['value'], $type);
-                if (PEAR::isError($value)) {
-                    return $value;
-                }
-            }
-            $values.= $value;
-            if (isset($fields[$name]['key']) && $fields[$name]['key']) {
-                if ($value === 'NULL') {
-                    return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
-                        'key value '.$name.' may not be NULL', __FUNCTION__);
-                }
-                $keys++;
-            }
-        }
-        if ($keys == 0) {
-            return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
-                'not specified which fields are keys', __FUNCTION__);
-        }
-
-        $connection = $this->getConnection();
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-
-        $table = $this->quoteIdentifier($table, true);
-        $query = "REPLACE INTO $table ($query) VALUES ($values)";
-        $result =$this->_doQuery($query, true, $connection);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        return $this->_affectedRows($connection, $result);
-    }
-
-    // }}}
-    // {{{ nextID()
-
-    /**
-     * Returns the next free id of a sequence
-     *
-     * @param string $seq_name name of the sequence
-     * @param boolean $ondemand when true the sequence is
-     *                          automatic created, if it
-     *                          not exists
-     *
-     * @return mixed MDB2 Error Object or id
-     * @access public
-     */
-    function nextID($seq_name, $ondemand = true)
-    {
-        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
-        $seqcol_name = $this->options['seqcol_name'];
-        $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
-        $this->pushErrorHandling(PEAR_ERROR_RETURN);
-        $this->expectError(MDB2_ERROR_NOSUCHTABLE);
-        $result =$this->_doQuery($query, true);
-        $this->popExpect();
-        $this->popErrorHandling();
-        if (PEAR::isError($result)) {
-            if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
-                $this->loadModule('Manager', null, true);
-                $result = $this->manager->createSequence($seq_name);
-                if (PEAR::isError($result)) {
-                    return $this->raiseError($result, null, null,
-                        'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
-                } else {
-                    return $this->nextID($seq_name, false);
-                }
-            }
-            return $result;
-        }
-        $value = $this->lastInsertID();
-        if (is_numeric($value)) {
-            $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
-            $result =$this->_doQuery($query, true);
-            if (PEAR::isError($result)) {
-                $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
-            }
-        }
-        return $value;
-    }
-
-    // }}}
-    // {{{ lastInsertID()
-
-    /**
-     * Returns the autoincrement ID if supported or $id or fetches the current
-     * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
-     *
-     * @param string $table name of the table into which a new row was inserted
-     * @param string $field name of the field into which a new row was inserted
-     * @return mixed MDB2 Error Object or id
-     * @access public
-     */
-    function lastInsertID($table = null, $field = null)
-    {
-        $connection = $this->getConnection();
-        if (PEAR::isError($connection)) {
-            return $connection;
-        }
-        $value = @sqlite_last_insert_rowid($connection);
-        if (!$value) {
-            return $this->raiseError(null, null, null,
-                'Could not get last insert ID', __FUNCTION__);
-        }
-        return $value;
-    }
-
-    // }}}
-    // {{{ currID()
-
-    /**
-     * Returns the current id of a sequence
-     *
-     * @param string $seq_name name of the sequence
-     * @return mixed MDB2 Error Object or id
-     * @access public
-     */
-    function currID($seq_name)
-    {
-        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
-        $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
-        $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
-        return $this->queryOne($query, 'integer');
-    }
-}
-
-/**
- * MDB2 SQLite result driver
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Result_sqlite extends MDB2_Result_Common
-{
-    // }}}
-    // {{{ fetchRow()
-
-    /**
-     * Fetch a row and insert the data into an existing array.
-     *
-     * @param int       $fetchmode  how the array data should be indexed
-     * @param int    $rownum    number of the row where the data can be found
-     * @return int data array on success, a MDB2 error on failure
-     * @access public
-     */
-    function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
-    {
-        if (!is_null($rownum)) {
-            $seek = $this->seek($rownum);
-            if (PEAR::isError($seek)) {
-                return $seek;
-            }
-        }
-        if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
-            $fetchmode = $this->db->fetchmode;
-        }
-        if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
-            $row = @sqlite_fetch_array($this->result, SQLITE_ASSOC);
-            if (is_array($row)
-                && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
-            ) {
-                $row = array_change_key_case($row, $this->db->options['field_case']);
-            }
-        } else {
-           $row = @sqlite_fetch_array($this->result, SQLITE_NUM);
-        }
-        if (!$row) {
-            if ($this->result === false) {
-                $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                    'resultset has already been freed', __FUNCTION__);
-                return $err;
-            }
-            $null = null;
-            return $null;
-        }
-        $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
-        $rtrim = false;
-        if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
-            if (empty($this->types)) {
-                $mode += MDB2_PORTABILITY_RTRIM;
-            } else {
-                $rtrim = true;
-            }
-        }
-        if ($mode) {
-            $this->db->_fixResultArrayValues($row, $mode);
-        }
-        if (!empty($this->types)) {
-            $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
-        }
-        if (!empty($this->values)) {
-            $this->_assignBindColumns($row);
-        }
-        if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
-            $object_class = $this->db->options['fetch_class'];
-            if ($object_class == 'stdClass') {
-                $row = (object) $row;
-            } else {
-                $row = new $object_class($row);
-            }
-        }
-        ++$this->rownum;
-        return $row;
-    }
-
-    // }}}
-    // {{{ _getColumnNames()
-
-    /**
-     * Retrieve the names of columns returned by the DBMS in a query result.
-     *
-     * @return  mixed   Array variable that holds the names of columns as keys
-     *                  or an MDB2 error on failure.
-     *                  Some DBMS may not return any columns when the result set
-     *                  does not contain any rows.
-     * @access private
-     */
-    function _getColumnNames()
-    {
-        $columns = array();
-        $numcols = $this->numCols();
-        if (PEAR::isError($numcols)) {
-            return $numcols;
-        }
-        for ($column = 0; $column < $numcols; $column++) {
-            $column_name = @sqlite_field_name($this->result, $column);
-            $columns[$column_name] = $column;
-        }
-        if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
-            $columns = array_change_key_case($columns, $this->db->options['field_case']);
-        }
-        return $columns;
-    }
-
-    // }}}
-    // {{{ numCols()
-
-    /**
-     * Count the number of columns returned by the DBMS in a query result.
-     *
-     * @access public
-     * @return mixed integer value with the number of columns, a MDB2 error
-     *                       on failure
-     */
-    function numCols()
-    {
-        $cols = @sqlite_num_fields($this->result);
-        if (is_null($cols)) {
-            if ($this->result === false) {
-                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                    'resultset has already been freed', __FUNCTION__);
-            } elseif (is_null($this->result)) {
-                return count($this->types);
-            }
-            return $this->db->raiseError(null, null, null,
-                'Could not get column count', __FUNCTION__);
-        }
-        return $cols;
-    }
-}
-
-/**
- * MDB2 SQLite buffered result driver
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_BufferedResult_sqlite extends MDB2_Result_sqlite
-{
-    // {{{ seek()
-
-    /**
-     * Seek to a specific row in a result set
-     *
-     * @param int    $rownum    number of the row where the data can be found
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
-     */
-    function seek($rownum = 0)
-    {
-        if (!@sqlite_seek($this->result, $rownum)) {
-            if ($this->result === false) {
-                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                    'resultset has already been freed', __FUNCTION__);
-            } elseif (is_null($this->result)) {
-                return MDB2_OK;
-            }
-            return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
-                'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
-        }
-        $this->rownum = $rownum - 1;
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ valid()
-
-    /**
-     * Check if the end of the result set has been reached
-     *
-     * @return mixed true or false on sucess, a MDB2 error on failure
-     * @access public
-     */
-    function valid()
-    {
-        $numrows = $this->numRows();
-        if (PEAR::isError($numrows)) {
-            return $numrows;
-        }
-        return $this->rownum < ($numrows - 1);
-    }
-
-    // }}}
-    // {{{ numRows()
-
-    /**
-     * Returns the number of rows in a result object
-     *
-     * @return mixed MDB2 Error Object or the number of rows
-     * @access public
-     */
-    function numRows()
-    {
-        $rows = @sqlite_num_rows($this->result);
-        if (is_null($rows)) {
-            if ($this->result === false) {
-                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                    'resultset has already been freed', __FUNCTION__);
-            } elseif (is_null($this->result)) {
-                return 0;
-            }
-            return $this->db->raiseError(null, null, null,
-                'Could not get row count', __FUNCTION__);
-        }
-        return $rows;
-    }
-}
-
-/**
- * MDB2 SQLite statement driver
- *
- * @package MDB2
- * @category Database
- * @author  Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Statement_sqlite extends MDB2_Statement_Common
-{
-
-}
-
-?>
+<?php\r
+// vim: set et ts=4 sw=4 fdm=marker:\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: sqlite.php 295587 2010-02-28 17:16:38Z quipo $\r
+//\r
+\r
+/**\r
+ * MDB2 SQLite driver\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Driver_sqlite extends MDB2_Driver_Common\r
+{\r
+    // {{{ properties\r
+    var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => false);\r
+\r
+    var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');\r
+\r
+    var $_lasterror = '';\r
+\r
+    var $fix_assoc_fields_names = false;\r
+\r
+    // }}}\r
+    // {{{ constructor\r
+\r
+    /**\r
+     * Constructor\r
+     */\r
+    function __construct()\r
+    {\r
+        parent::__construct();\r
+\r
+        $this->phptype = 'sqlite';\r
+        $this->dbsyntax = 'sqlite';\r
+\r
+        $this->supported['sequences'] = 'emulated';\r
+        $this->supported['indexes'] = true;\r
+        $this->supported['affected_rows'] = true;\r
+        $this->supported['summary_functions'] = true;\r
+        $this->supported['order_by_text'] = true;\r
+        $this->supported['current_id'] = 'emulated';\r
+        $this->supported['limit_queries'] = true;\r
+        $this->supported['LOBs'] = true;\r
+        $this->supported['replace'] = true;\r
+        $this->supported['transactions'] = true;\r
+        $this->supported['savepoints'] = false;\r
+        $this->supported['sub_selects'] = true;\r
+        $this->supported['triggers'] = true;\r
+        $this->supported['auto_increment'] = true;\r
+        $this->supported['primary_key'] = false; // requires alter table implementation\r
+        $this->supported['result_introspection'] = false; // not implemented\r
+        $this->supported['prepared_statements'] = 'emulated';\r
+        $this->supported['identifier_quoting'] = true;\r
+        $this->supported['pattern_escaping'] = false;\r
+        $this->supported['new_link'] = false;\r
+\r
+        $this->options['DBA_username'] = false;\r
+        $this->options['DBA_password'] = false;\r
+        $this->options['base_transaction_name'] = '___php_MDB2_sqlite_auto_commit_off';\r
+        $this->options['fixed_float'] = 0;\r
+        $this->options['database_path'] = '';\r
+        $this->options['database_extension'] = '';\r
+        $this->options['server_version'] = '';\r
+        $this->options['max_identifiers_length'] = 128; //no real limit\r
+    }\r
+\r
+    // }}}\r
+    // {{{ errorInfo()\r
+\r
+    /**\r
+     * This method is used to collect information about an error\r
+     *\r
+     * @param integer $error\r
+     * @return array\r
+     * @access public\r
+     */\r
+    function errorInfo($error = null)\r
+    {\r
+        $native_code = null;\r
+        if ($this->connection) {\r
+            $native_code = @sqlite_last_error($this->connection);\r
+        }\r
+        $native_msg = $this->_lasterror\r
+            ? html_entity_decode($this->_lasterror) : @sqlite_error_string($native_code);\r
+            \r
+        // PHP 5.2+ prepends the function name to $php_errormsg, so we need\r
+        // this hack to work around it, per bug #9599.\r
+        $native_msg = preg_replace('/^sqlite[a-z_]+\(\)[^:]*: /', '', $native_msg);\r
+\r
+        if (null === $error) {\r
+            static $error_regexps;\r
+            if (empty($error_regexps)) {\r
+                $error_regexps = array(\r
+                    '/^no such table:/' => MDB2_ERROR_NOSUCHTABLE,\r
+                    '/^no such index:/' => MDB2_ERROR_NOT_FOUND,\r
+                    '/^(table|index) .* already exists$/' => MDB2_ERROR_ALREADY_EXISTS,\r
+                    '/PRIMARY KEY must be unique/i' => MDB2_ERROR_CONSTRAINT,\r
+                    '/is not unique/' => MDB2_ERROR_CONSTRAINT,\r
+                    '/columns .* are not unique/i' => MDB2_ERROR_CONSTRAINT,\r
+                    '/uniqueness constraint failed/' => MDB2_ERROR_CONSTRAINT,\r
+                    '/may not be NULL/' => MDB2_ERROR_CONSTRAINT_NOT_NULL,\r
+                    '/^no such column:/' => MDB2_ERROR_NOSUCHFIELD,\r
+                    '/no column named/' => MDB2_ERROR_NOSUCHFIELD,\r
+                    '/column not present in both tables/i' => MDB2_ERROR_NOSUCHFIELD,\r
+                    '/^near ".*": syntax error$/' => MDB2_ERROR_SYNTAX,\r
+                    '/[0-9]+ values for [0-9]+ columns/i' => MDB2_ERROR_VALUE_COUNT_ON_ROW,\r
+                 );\r
+            }\r
+            foreach ($error_regexps as $regexp => $code) {\r
+                if (preg_match($regexp, $native_msg)) {\r
+                    $error = $code;\r
+                    break;\r
+                }\r
+            }\r
+        }\r
+        return array($error, $native_code, $native_msg);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ escape()\r
+\r
+    /**\r
+     * Quotes a string so it can be safely used in a query. It will quote\r
+     * the text so it can safely be used within a query.\r
+     *\r
+     * @param   string  the input string to quote\r
+     * @param   bool    escape wildcards\r
+     *\r
+     * @return  string  quoted string\r
+     *\r
+     * @access  public\r
+     */\r
+    function escape($text, $escape_wildcards = false)\r
+    {\r
+        $text = @sqlite_escape_string($text);\r
+        return $text;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ beginTransaction()\r
+\r
+    /**\r
+     * Start a transaction or set a savepoint.\r
+     *\r
+     * @param   string  name of a savepoint to set\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function beginTransaction($savepoint = null)\r
+    {\r
+        $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));\r
+        if (null !== $savepoint) {\r
+            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'savepoints are not supported', __FUNCTION__);\r
+        }\r
+        if ($this->in_transaction) {\r
+            return MDB2_OK;  //nothing to do\r
+        }\r
+        if (!$this->destructor_registered && $this->opened_persistent) {\r
+            $this->destructor_registered = true;\r
+            register_shutdown_function('MDB2_closeOpenTransactions');\r
+        }\r
+        $query = 'BEGIN TRANSACTION '.$this->options['base_transaction_name'];\r
+        $result = $this->_doQuery($query, true);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        $this->in_transaction = true;\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ commit()\r
+\r
+    /**\r
+     * Commit the database changes done during a transaction that is in\r
+     * progress or release a savepoint. This function may only be called when\r
+     * auto-committing is disabled, otherwise it will fail. Therefore, a new\r
+     * transaction is implicitly started after committing the pending changes.\r
+     *\r
+     * @param   string  name of a savepoint to release\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function commit($savepoint = null)\r
+    {\r
+        $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));\r
+        if (!$this->in_transaction) {\r
+            return $this->raiseError(MDB2_ERROR_INVALID, null, null,\r
+                'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);\r
+        }\r
+        if (null !== $savepoint) {\r
+            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'savepoints are not supported', __FUNCTION__);\r
+        }\r
+\r
+        $query = 'COMMIT TRANSACTION '.$this->options['base_transaction_name'];\r
+        $result = $this->_doQuery($query, true);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        $this->in_transaction = false;\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{\r
+\r
+    /**\r
+     * Cancel any database changes done during a transaction or since a specific\r
+     * savepoint that is in progress. This function may only be called when\r
+     * auto-committing is disabled, otherwise it will fail. Therefore, a new\r
+     * transaction is implicitly started after canceling the pending changes.\r
+     *\r
+     * @param   string  name of a savepoint to rollback to\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     */\r
+    function rollback($savepoint = null)\r
+    {\r
+        $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));\r
+        if (!$this->in_transaction) {\r
+            return $this->raiseError(MDB2_ERROR_INVALID, null, null,\r
+                'rollback cannot be done changes are auto committed', __FUNCTION__);\r
+        }\r
+        if (null !== $savepoint) {\r
+            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'savepoints are not supported', __FUNCTION__);\r
+        }\r
+\r
+        $query = 'ROLLBACK TRANSACTION '.$this->options['base_transaction_name'];\r
+        $result = $this->_doQuery($query, true);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        $this->in_transaction = false;\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ function setTransactionIsolation()\r
+\r
+    /**\r
+     * Set the transacton isolation level.\r
+     *\r
+     * @param   string  standard isolation level\r
+     *                  READ UNCOMMITTED (allows dirty reads)\r
+     *                  READ COMMITTED (prevents dirty reads)\r
+     *                  REPEATABLE READ (prevents nonrepeatable reads)\r
+     *                  SERIALIZABLE (prevents phantom reads)\r
+     * @param   array some transaction options:\r
+     *                  'wait' => 'WAIT' | 'NO WAIT'\r
+     *                  'rw'   => 'READ WRITE' | 'READ ONLY'\r
+     *\r
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure\r
+     *\r
+     * @access  public\r
+     * @since   2.1.1\r
+     */\r
+    function setTransactionIsolation($isolation, $options = array())\r
+    {\r
+        $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));\r
+        switch ($isolation) {\r
+        case 'READ UNCOMMITTED':\r
+            $isolation = 0;\r
+            break;\r
+        case 'READ COMMITTED':\r
+        case 'REPEATABLE READ':\r
+        case 'SERIALIZABLE':\r
+            $isolation = 1;\r
+            break;\r
+        default:\r
+            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'isolation level is not supported: '.$isolation, __FUNCTION__);\r
+        }\r
+\r
+        $query = "PRAGMA read_uncommitted=$isolation";\r
+        return $this->_doQuery($query, true);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getDatabaseFile()\r
+\r
+    /**\r
+     * Builds the string with path+dbname+extension\r
+     *\r
+     * @return string full database path+file\r
+     * @access protected\r
+     */\r
+    function _getDatabaseFile($database_name)\r
+    {\r
+        if ($database_name === '' || $database_name === ':memory:') {\r
+            return $database_name;\r
+        }\r
+        return $this->options['database_path'].$database_name.$this->options['database_extension'];\r
+    }\r
+\r
+    // }}}\r
+    // {{{ connect()\r
+\r
+    /**\r
+     * Connect to the database\r
+     *\r
+     * @return true on success, MDB2 Error Object on failure\r
+     **/\r
+    function connect()\r
+    {\r
+        $database_file = $this->_getDatabaseFile($this->database_name);\r
+        if (is_resource($this->connection)) {\r
+            //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0\r
+            if (MDB2::areEquals($this->connected_dsn, $this->dsn)\r
+                && $this->connected_database_name == $database_file\r
+                && $this->opened_persistent == $this->options['persistent']\r
+            ) {\r
+                return MDB2_OK;\r
+            }\r
+            $this->disconnect(false);\r
+        }\r
+\r
+        if (!PEAR::loadExtension($this->phptype)) {\r
+            return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);\r
+        }\r
+\r
+        if (empty($this->database_name)) {\r
+            return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,\r
+            'unable to establish a connection', __FUNCTION__);\r
+        }\r
+\r
+        if ($database_file !== ':memory:') {\r
+            if (!file_exists($database_file)) {\r
+                if (!touch($database_file)) {\r
+                    return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                        'Could not create database file', __FUNCTION__);\r
+                }\r
+                if (!isset($this->dsn['mode'])\r
+                    || !is_numeric($this->dsn['mode'])\r
+                ) {\r
+                    $mode = 0644;\r
+                } else {\r
+                    $mode = octdec($this->dsn['mode']);\r
+                }\r
+                if (!chmod($database_file, $mode)) {\r
+                    return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                        'Could not be chmodded database file', __FUNCTION__);\r
+                }\r
+                if (!file_exists($database_file)) {\r
+                    return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,\r
+                        'Could not be found database file', __FUNCTION__);\r
+                }\r
+            }\r
+            if (!is_file($database_file)) {\r
+                return $this->raiseError(MDB2_ERROR_INVALID, null, null,\r
+                        'Database is a directory name', __FUNCTION__);\r
+            }\r
+            if (!is_readable($database_file)) {\r
+                return $this->raiseError(MDB2_ERROR_ACCESS_VIOLATION, null, null,\r
+                        'Could not read database file', __FUNCTION__);\r
+            }\r
+        }\r
+\r
+        $connect_function = ($this->options['persistent'] ? 'sqlite_popen' : 'sqlite_open');\r
+        $php_errormsg = '';\r
+        if (version_compare('5.1.0', PHP_VERSION, '>')) {\r
+            @ini_set('track_errors', true);\r
+            $connection = @$connect_function($database_file);\r
+            @ini_restore('track_errors');\r
+        } else {\r
+            $connection = @$connect_function($database_file, 0666, $php_errormsg);\r
+        }\r
+        $this->_lasterror = $php_errormsg;\r
+        if (!$connection) {\r
+            return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,\r
+            'unable to establish a connection', __FUNCTION__);\r
+        }\r
+\r
+        if ($this->fix_assoc_fields_names ||\r
+            $this->options['portability'] & MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES)\r
+        {\r
+            @sqlite_query("PRAGMA short_column_names = 1", $connection);\r
+            $this->fix_assoc_fields_names = true;\r
+        }\r
+\r
+        $this->connection = $connection;\r
+        $this->connected_dsn = $this->dsn;\r
+        $this->connected_database_name = $database_file;\r
+        $this->opened_persistent = $this->getoption('persistent');\r
+        $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;\r
+\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ databaseExists()\r
+\r
+    /**\r
+     * check if given database name is exists?\r
+     *\r
+     * @param string $name    name of the database that should be checked\r
+     *\r
+     * @return mixed true/false on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function databaseExists($name)\r
+    {\r
+        $database_file = $this->_getDatabaseFile($name);\r
+        $result = file_exists($database_file);\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ disconnect()\r
+\r
+    /**\r
+     * Log out and disconnect from the database.\r
+     *\r
+     * @param  boolean $force if the disconnect should be forced even if the\r
+     *                        connection is opened persistently\r
+     * @return mixed true on success, false if not connected and error\r
+     *                object on error\r
+     * @access public\r
+     */\r
+    function disconnect($force = true)\r
+    {\r
+        if (is_resource($this->connection)) {\r
+            if ($this->in_transaction) {\r
+                $dsn = $this->dsn;\r
+                $database_name = $this->database_name;\r
+                $persistent = $this->options['persistent'];\r
+                $this->dsn = $this->connected_dsn;\r
+                $this->database_name = $this->connected_database_name;\r
+                $this->options['persistent'] = $this->opened_persistent;\r
+                $this->rollback();\r
+                $this->dsn = $dsn;\r
+                $this->database_name = $database_name;\r
+                $this->options['persistent'] = $persistent;\r
+            }\r
+\r
+            if (!$this->opened_persistent || $force) {\r
+                @sqlite_close($this->connection);\r
+            }\r
+        } else {\r
+            return false;\r
+        }\r
+        return parent::disconnect($force);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _doQuery()\r
+\r
+    /**\r
+     * Execute a query\r
+     * @param string $query  query\r
+     * @param boolean $is_manip  if the query is a manipulation query\r
+     * @param resource $connection\r
+     * @param string $database_name\r
+     * @return result or error object\r
+     * @access protected\r
+     */\r
+    function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)\r
+    {\r
+        $this->last_query = $query;\r
+        $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));\r
+        if ($result) {\r
+            if (PEAR::isError($result)) {\r
+                return $result;\r
+            }\r
+            $query = $result;\r
+        }\r
+        if ($this->options['disable_query']) {\r
+            $result = $is_manip ? 0 : null;\r
+            return $result;\r
+        }\r
+\r
+        if (null === $connection) {\r
+            $connection = $this->getConnection();\r
+            if (PEAR::isError($connection)) {\r
+                return $connection;\r
+            }\r
+        }\r
+\r
+        $function = $this->options['result_buffering']\r
+            ? 'sqlite_query' : 'sqlite_unbuffered_query';\r
+        $php_errormsg = '';\r
+        if (version_compare('5.1.0', PHP_VERSION, '>')) {\r
+            @ini_set('track_errors', true);\r
+            do {\r
+                $result = @$function($query.';', $connection);\r
+            } while (sqlite_last_error($connection) == SQLITE_SCHEMA);\r
+            @ini_restore('track_errors');\r
+        } else {\r
+            do {\r
+                $result = @$function($query.';', $connection, SQLITE_BOTH, $php_errormsg);\r
+            } while (sqlite_last_error($connection) == SQLITE_SCHEMA);\r
+        }\r
+        $this->_lasterror = $php_errormsg;\r
+\r
+        if (!$result) {\r
+            $code = null;\r
+            if (0 === strpos($this->_lasterror, 'no such table')) {\r
+                $code = MDB2_ERROR_NOSUCHTABLE;\r
+            }\r
+            $err = $this->raiseError($code, null, null,\r
+                'Could not execute statement', __FUNCTION__);\r
+            return $err;\r
+        }\r
+\r
+        $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _affectedRows()\r
+\r
+    /**\r
+     * Returns the number of rows affected\r
+     *\r
+     * @param resource $result\r
+     * @param resource $connection\r
+     * @return mixed MDB2 Error Object or the number of rows affected\r
+     * @access private\r
+     */\r
+    function _affectedRows($connection, $result = null)\r
+    {\r
+        if (null === $connection) {\r
+            $connection = $this->getConnection();\r
+            if (PEAR::isError($connection)) {\r
+                return $connection;\r
+            }\r
+        }\r
+        return @sqlite_changes($connection);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _modifyQuery()\r
+\r
+    /**\r
+     * Changes a query string for various DBMS specific reasons\r
+     *\r
+     * @param string $query  query to modify\r
+     * @param boolean $is_manip  if it is a DML query\r
+     * @param integer $limit  limit the number of rows\r
+     * @param integer $offset  start reading from given offset\r
+     * @return string modified query\r
+     * @access protected\r
+     */\r
+    function _modifyQuery($query, $is_manip, $limit, $offset)\r
+    {\r
+        if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {\r
+            if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {\r
+                $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',\r
+                                      'DELETE FROM \1 WHERE 1=1', $query);\r
+            }\r
+        }\r
+        if ($limit > 0\r
+            && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)\r
+        ) {\r
+            $query = rtrim($query);\r
+            if (substr($query, -1) == ';') {\r
+                $query = substr($query, 0, -1);\r
+            }\r
+            if ($is_manip) {\r
+                $query.= " LIMIT $limit";\r
+            } else {\r
+                $query.= " LIMIT $offset,$limit";\r
+            }\r
+        }\r
+        return $query;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getServerVersion()\r
+\r
+    /**\r
+     * return version information about the server\r
+     *\r
+     * @param bool   $native  determines if the raw version string should be returned\r
+     * @return mixed array/string with version information or MDB2 error object\r
+     * @access public\r
+     */\r
+    function getServerVersion($native = false)\r
+    {\r
+        $server_info = false;\r
+        if ($this->connected_server_info) {\r
+            $server_info = $this->connected_server_info;\r
+        } elseif ($this->options['server_version']) {\r
+            $server_info = $this->options['server_version'];\r
+        } elseif (function_exists('sqlite_libversion')) {\r
+            $server_info = @sqlite_libversion();\r
+        }\r
+        if (!$server_info) {\r
+            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,\r
+                'Requires either the "server_version" option or the sqlite_libversion() function', __FUNCTION__);\r
+        }\r
+        // cache server_info\r
+        $this->connected_server_info = $server_info;\r
+        if (!$native) {\r
+            $tmp = explode('.', $server_info, 3);\r
+            $server_info = array(\r
+                'major' => isset($tmp[0]) ? $tmp[0] : null,\r
+                'minor' => isset($tmp[1]) ? $tmp[1] : null,\r
+                'patch' => isset($tmp[2]) ? $tmp[2] : null,\r
+                'extra' => null,\r
+                'native' => $server_info,\r
+            );\r
+        }\r
+        return $server_info;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ replace()\r
+\r
+    /**\r
+     * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT\r
+     * query, except that if there is already a row in the table with the same\r
+     * key field values, the old row is deleted before the new row is inserted.\r
+     *\r
+     * The REPLACE type of query does not make part of the SQL standards. Since\r
+     * practically only SQLite implements it natively, this type of query is\r
+     * emulated through this method for other DBMS using standard types of\r
+     * queries inside a transaction to assure the atomicity of the operation.\r
+     *\r
+     * @access public\r
+     *\r
+     * @param string $table name of the table on which the REPLACE query will\r
+     *  be executed.\r
+     * @param array $fields associative array that describes the fields and the\r
+     *  values that will be inserted or updated in the specified table. The\r
+     *  indexes of the array are the names of all the fields of the table. The\r
+     *  values of the array are also associative arrays that describe the\r
+     *  values and other properties of the table fields.\r
+     *\r
+     *  Here follows a list of field properties that need to be specified:\r
+     *\r
+     *    value:\r
+     *          Value to be assigned to the specified field. This value may be\r
+     *          of specified in database independent type format as this\r
+     *          function can perform the necessary datatype conversions.\r
+     *\r
+     *    Default:\r
+     *          this property is required unless the Null property\r
+     *          is set to 1.\r
+     *\r
+     *    type\r
+     *          Name of the type of the field. Currently, all types Metabase\r
+     *          are supported except for clob and blob.\r
+     *\r
+     *    Default: no type conversion\r
+     *\r
+     *    null\r
+     *          Boolean property that indicates that the value for this field\r
+     *          should be set to null.\r
+     *\r
+     *          The default value for fields missing in INSERT queries may be\r
+     *          specified the definition of a table. Often, the default value\r
+     *          is already null, but since the REPLACE may be emulated using\r
+     *          an UPDATE query, make sure that all fields of the table are\r
+     *          listed in this function argument array.\r
+     *\r
+     *    Default: 0\r
+     *\r
+     *    key\r
+     *          Boolean property that indicates that this field should be\r
+     *          handled as a primary key or at least as part of the compound\r
+     *          unique index of the table that will determine the row that will\r
+     *          updated if it exists or inserted a new row otherwise.\r
+     *\r
+     *          This function will fail if no key field is specified or if the\r
+     *          value of a key field is set to null because fields that are\r
+     *          part of unique index they may not be null.\r
+     *\r
+     *    Default: 0\r
+     *\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     */\r
+    function replace($table, $fields)\r
+    {\r
+        $count = count($fields);\r
+        $query = $values = '';\r
+        $keys = $colnum = 0;\r
+        for (reset($fields); $colnum < $count; next($fields), $colnum++) {\r
+            $name = key($fields);\r
+            if ($colnum > 0) {\r
+                $query .= ',';\r
+                $values.= ',';\r
+            }\r
+            $query.= $this->quoteIdentifier($name, true);\r
+            if (isset($fields[$name]['null']) && $fields[$name]['null']) {\r
+                $value = 'NULL';\r
+            } else {\r
+                $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;\r
+                $value = $this->quote($fields[$name]['value'], $type);\r
+                if (PEAR::isError($value)) {\r
+                    return $value;\r
+                }\r
+            }\r
+            $values.= $value;\r
+            if (isset($fields[$name]['key']) && $fields[$name]['key']) {\r
+                if ($value === 'NULL') {\r
+                    return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,\r
+                        'key value '.$name.' may not be NULL', __FUNCTION__);\r
+                }\r
+                $keys++;\r
+            }\r
+        }\r
+        if ($keys == 0) {\r
+            return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,\r
+                'not specified which fields are keys', __FUNCTION__);\r
+        }\r
+\r
+        $connection = $this->getConnection();\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+\r
+        $table = $this->quoteIdentifier($table, true);\r
+        $query = "REPLACE INTO $table ($query) VALUES ($values)";\r
+        $result = $this->_doQuery($query, true, $connection);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        return $this->_affectedRows($connection, $result);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ nextID()\r
+\r
+    /**\r
+     * Returns the next free id of a sequence\r
+     *\r
+     * @param string $seq_name name of the sequence\r
+     * @param boolean $ondemand when true the sequence is\r
+     *                          automatic created, if it\r
+     *                          not exists\r
+     *\r
+     * @return mixed MDB2 Error Object or id\r
+     * @access public\r
+     */\r
+    function nextID($seq_name, $ondemand = true)\r
+    {\r
+        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);\r
+        $seqcol_name = $this->options['seqcol_name'];\r
+        $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";\r
+        $this->pushErrorHandling(PEAR_ERROR_RETURN);\r
+        $this->expectError(MDB2_ERROR_NOSUCHTABLE);\r
+        $result = $this->_doQuery($query, true);\r
+        $this->popExpect();\r
+        $this->popErrorHandling();\r
+        if (PEAR::isError($result)) {\r
+            if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {\r
+                $this->loadModule('Manager', null, true);\r
+                $result = $this->manager->createSequence($seq_name);\r
+                if (PEAR::isError($result)) {\r
+                    return $this->raiseError($result, null, null,\r
+                        'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);\r
+                } else {\r
+                    return $this->nextID($seq_name, false);\r
+                }\r
+            }\r
+            return $result;\r
+        }\r
+        $value = $this->lastInsertID();\r
+        if (is_numeric($value)) {\r
+            $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";\r
+            $result = $this->_doQuery($query, true);\r
+            if (PEAR::isError($result)) {\r
+                $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;\r
+            }\r
+        }\r
+        return $value;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ lastInsertID()\r
+\r
+    /**\r
+     * Returns the autoincrement ID if supported or $id or fetches the current\r
+     * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)\r
+     *\r
+     * @param string $table name of the table into which a new row was inserted\r
+     * @param string $field name of the field into which a new row was inserted\r
+     * @return mixed MDB2 Error Object or id\r
+     * @access public\r
+     */\r
+    function lastInsertID($table = null, $field = null)\r
+    {\r
+        $connection = $this->getConnection();\r
+        if (PEAR::isError($connection)) {\r
+            return $connection;\r
+        }\r
+        $value = @sqlite_last_insert_rowid($connection);\r
+        if (!$value) {\r
+            return $this->raiseError(null, null, null,\r
+                'Could not get last insert ID', __FUNCTION__);\r
+        }\r
+        return $value;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ currID()\r
+\r
+    /**\r
+     * Returns the current id of a sequence\r
+     *\r
+     * @param string $seq_name name of the sequence\r
+     * @return mixed MDB2 Error Object or id\r
+     * @access public\r
+     */\r
+    function currID($seq_name)\r
+    {\r
+        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);\r
+        $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);\r
+        $query = "SELECT MAX($seqcol_name) FROM $sequence_name";\r
+        return $this->queryOne($query, 'integer');\r
+    }\r
+}\r
+\r
+/**\r
+ * MDB2 SQLite result driver\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Result_sqlite extends MDB2_Result_Common\r
+{\r
+    // }}}\r
+    // {{{ fetchRow()\r
+\r
+    /**\r
+     * Fetch a row and insert the data into an existing array.\r
+     *\r
+     * @param int       $fetchmode  how the array data should be indexed\r
+     * @param int    $rownum    number of the row where the data can be found\r
+     * @return int data array on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)\r
+    {\r
+        if (null !== $rownum) {\r
+            $seek = $this->seek($rownum);\r
+            if (PEAR::isError($seek)) {\r
+                return $seek;\r
+            }\r
+        }\r
+        if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {\r
+            $fetchmode = $this->db->fetchmode;\r
+        }\r
+        if ($fetchmode & MDB2_FETCHMODE_ASSOC) {\r
+            $row = @sqlite_fetch_array($this->result, SQLITE_ASSOC);\r
+            if (is_array($row)\r
+                && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE\r
+            ) {\r
+                $row = array_change_key_case($row, $this->db->options['field_case']);\r
+            }\r
+        } else {\r
+           $row = @sqlite_fetch_array($this->result, SQLITE_NUM);\r
+        }\r
+        if (!$row) {\r
+            if (false === $this->result) {\r
+                $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,\r
+                    'resultset has already been freed', __FUNCTION__);\r
+                return $err;\r
+            }\r
+            return null;\r
+        }\r
+        $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;\r
+        $rtrim = false;\r
+        if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {\r
+            if (empty($this->types)) {\r
+                $mode += MDB2_PORTABILITY_RTRIM;\r
+            } else {\r
+                $rtrim = true;\r
+            }\r
+        }\r
+        if ($mode) {\r
+            $this->db->_fixResultArrayValues($row, $mode);\r
+        }\r
+        if (!empty($this->types)) {\r
+            $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);\r
+        }\r
+        if (!empty($this->values)) {\r
+            $this->_assignBindColumns($row);\r
+        }\r
+        if ($fetchmode === MDB2_FETCHMODE_OBJECT) {\r
+            $object_class = $this->db->options['fetch_class'];\r
+            if ($object_class == 'stdClass') {\r
+                $row = (object) $row;\r
+            } else {\r
+                $rowObj = new $object_class($row);\r
+                $row = $rowObj;\r
+            }\r
+        }\r
+        ++$this->rownum;\r
+        return $row;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ _getColumnNames()\r
+\r
+    /**\r
+     * Retrieve the names of columns returned by the DBMS in a query result.\r
+     *\r
+     * @return  mixed   Array variable that holds the names of columns as keys\r
+     *                  or an MDB2 error on failure.\r
+     *                  Some DBMS may not return any columns when the result set\r
+     *                  does not contain any rows.\r
+     * @access private\r
+     */\r
+    function _getColumnNames()\r
+    {\r
+        $columns = array();\r
+        $numcols = $this->numCols();\r
+        if (PEAR::isError($numcols)) {\r
+            return $numcols;\r
+        }\r
+        for ($column = 0; $column < $numcols; $column++) {\r
+            $column_name = @sqlite_field_name($this->result, $column);\r
+            $columns[$column_name] = $column;\r
+        }\r
+        if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {\r
+            $columns = array_change_key_case($columns, $this->db->options['field_case']);\r
+        }\r
+        return $columns;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ numCols()\r
+\r
+    /**\r
+     * Count the number of columns returned by the DBMS in a query result.\r
+     *\r
+     * @access public\r
+     * @return mixed integer value with the number of columns, a MDB2 error\r
+     *                       on failure\r
+     */\r
+    function numCols()\r
+    {\r
+        $cols = @sqlite_num_fields($this->result);\r
+        if (null === $cols) {\r
+            if (false === $this->result) {\r
+                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,\r
+                    'resultset has already been freed', __FUNCTION__);\r
+            }\r
+            if (null === $this->result) {\r
+                return count($this->types);\r
+            }\r
+            return $this->db->raiseError(null, null, null,\r
+                'Could not get column count', __FUNCTION__);\r
+        }\r
+        return $cols;\r
+    }\r
+}\r
+\r
+/**\r
+ * MDB2 SQLite buffered result driver\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_BufferedResult_sqlite extends MDB2_Result_sqlite\r
+{\r
+    // {{{ seek()\r
+\r
+    /**\r
+     * Seek to a specific row in a result set\r
+     *\r
+     * @param int    $rownum    number of the row where the data can be found\r
+     * @return mixed MDB2_OK on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function seek($rownum = 0)\r
+    {\r
+        if (!@sqlite_seek($this->result, $rownum)) {\r
+            if (false === $this->result) {\r
+                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,\r
+                    'resultset has already been freed', __FUNCTION__);\r
+            }\r
+            if (null === $this->result) {\r
+                return MDB2_OK;\r
+            }\r
+            return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,\r
+                'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);\r
+        }\r
+        $this->rownum = $rownum - 1;\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ valid()\r
+\r
+    /**\r
+     * Check if the end of the result set has been reached\r
+     *\r
+     * @return mixed true or false on sucess, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function valid()\r
+    {\r
+        $numrows = $this->numRows();\r
+        if (PEAR::isError($numrows)) {\r
+            return $numrows;\r
+        }\r
+        return $this->rownum < ($numrows - 1);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ numRows()\r
+\r
+    /**\r
+     * Returns the number of rows in a result object\r
+     *\r
+     * @return mixed MDB2 Error Object or the number of rows\r
+     * @access public\r
+     */\r
+    function numRows()\r
+    {\r
+        $rows = @sqlite_num_rows($this->result);\r
+        if (null === $rows) {\r
+            if (false === $this->result) {\r
+                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,\r
+                    'resultset has already been freed', __FUNCTION__);\r
+            }\r
+            if (null === $this->result) {\r
+                return 0;\r
+            }\r
+            return $this->db->raiseError(null, null, null,\r
+                'Could not get row count', __FUNCTION__);\r
+        }\r
+        return $rows;\r
+    }\r
+}\r
+\r
+/**\r
+ * MDB2 SQLite statement driver\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author  Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Statement_sqlite extends MDB2_Statement_Common\r
+{\r
+\r
+}\r
+?>
\ No newline at end of file
index 864ab9235432bd0e839d6093269b627062d27f8d..fed82f965981bbf86c05013a4c205d67c26e9acb 100644 (file)
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5                                                 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: Extended.php,v 1.60 2007/11/28 19:49:34 quipo Exp $
-
-/**
- * @package  MDB2
- * @category Database
- * @author   Lukas Smith <smith@pooteeweet.org>
- */
-
-/**
- * Used by autoPrepare()
- */
-define('MDB2_AUTOQUERY_INSERT', 1);
-define('MDB2_AUTOQUERY_UPDATE', 2);
-define('MDB2_AUTOQUERY_DELETE', 3);
-define('MDB2_AUTOQUERY_SELECT', 4);
-
-/**
- * MDB2_Extended: class which adds several high level methods to MDB2
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Extended extends MDB2_Module_Common
-{
-    // {{{ autoPrepare()
-
-    /**
-     * Generate an insert, update or delete query and call prepare() on it
-     *
-     * @param string table
-     * @param array the fields names
-     * @param int type of query to build
-     *                          MDB2_AUTOQUERY_INSERT
-     *                          MDB2_AUTOQUERY_UPDATE
-     *                          MDB2_AUTOQUERY_DELETE
-     *                          MDB2_AUTOQUERY_SELECT
-     * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
-     * @param array that contains the types of the placeholders
-     * @param mixed array that contains the types of the columns in
-     *                        the result set or MDB2_PREPARE_RESULT, if set to
-     *                        MDB2_PREPARE_MANIP the query is handled as a manipulation query
-     *
-     * @return resource handle for the query
-     * @see buildManipSQL
-     * @access public
-     */
-    function autoPrepare($table, $table_fields, $mode = MDB2_AUTOQUERY_INSERT,
-        $where = false, $types = null, $result_types = MDB2_PREPARE_MANIP)
-    {
-        $query = $this->buildManipSQL($table, $table_fields, $mode, $where);
-        if (PEAR::isError($query)) {
-            return $query;
-        }
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-        $lobs = array();
-        foreach ((array)$types as $param => $type) {
-            if (($type == 'clob') || ($type == 'blob')) {
-                $lobs[$param] = $table_fields[$param];
-            }
-        }
-        return $db->prepare($query, $types, $result_types, $lobs);
-    }
-
-    // }}}
-    // {{{ autoExecute()
-
-    /**
-     * Generate an insert, update or delete query and call prepare() and execute() on it
-     *
-     * @param string name of the table
-     * @param array assoc ($key=>$value) where $key is a field name and $value its value
-     * @param int type of query to build
-     *                          MDB2_AUTOQUERY_INSERT
-     *                          MDB2_AUTOQUERY_UPDATE
-     *                          MDB2_AUTOQUERY_DELETE
-     *                          MDB2_AUTOQUERY_SELECT
-     * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
-     * @param array that contains the types of the placeholders
-     * @param string which specifies which result class to use
-     * @param mixed  array that contains the types of the columns in
-     *                        the result set or MDB2_PREPARE_RESULT, if set to
-     *                        MDB2_PREPARE_MANIP the query is handled as a manipulation query
-     *
-     * @return bool|MDB2_Error true on success, a MDB2 error on failure
-     * @see buildManipSQL
-     * @see autoPrepare
-     * @access public
-    */
-    function &autoExecute($table, $fields_values, $mode = MDB2_AUTOQUERY_INSERT,
-        $where = false, $types = null, $result_class = true, $result_types = MDB2_PREPARE_MANIP)
-    {
-        $fields_values = (array)$fields_values;
-        if ($mode == MDB2_AUTOQUERY_SELECT) {
-            if (is_array($result_types)) {
-                $keys = array_keys($result_types);
-            } elseif (!empty($fields_values)) {
-                $keys = $fields_values;
-            } else {
-                $keys = array();
-            }
-        } else {
-            $keys = array_keys($fields_values);
-        }
-        $params = array_values($fields_values);
-        if (empty($params)) {
-            $query = $this->buildManipSQL($table, $keys, $mode, $where);
-
-            $db =& $this->getDBInstance();
-            if (PEAR::isError($db)) {
-                return $db;
-            }
-            if ($mode == MDB2_AUTOQUERY_SELECT) {
-                $result =& $db->query($query, $result_types, $result_class);
-            } else {
-                $result = $db->exec($query);
-            }
-        } else {
-            $stmt = $this->autoPrepare($table, $keys, $mode, $where, $types, $result_types);
-            if (PEAR::isError($stmt)) {
-                return $stmt;
-            }
-            $result =& $stmt->execute($params, $result_class);
-            $stmt->free();
-        }
-        return $result;
-    }
-
-    // }}}
-    // {{{ buildManipSQL()
-
-    /**
-     * Make automaticaly an sql query for prepare()
-     *
-     * Example : buildManipSQL('table_sql', array('field1', 'field2', 'field3'), MDB2_AUTOQUERY_INSERT)
-     *           will return the string : INSERT INTO table_sql (field1,field2,field3) VALUES (?,?,?)
-     * NB : - This belongs more to a SQL Builder class, but this is a simple facility
-     *      - Be carefull ! If you don't give a $where param with an UPDATE/DELETE query, all
-     *        the records of the table will be updated/deleted !
-     *
-     * @param string name of the table
-     * @param ordered array containing the fields names
-     * @param int type of query to build
-     *                          MDB2_AUTOQUERY_INSERT
-     *                          MDB2_AUTOQUERY_UPDATE
-     *                          MDB2_AUTOQUERY_DELETE
-     *                          MDB2_AUTOQUERY_SELECT
-     * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
-     *
-     * @return string sql query for prepare()
-     * @access public
-     */
-    function buildManipSQL($table, $table_fields, $mode, $where = false)
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        if ($db->options['quote_identifier']) {
-            $table = $db->quoteIdentifier($table);
-        }
-
-        if (!empty($table_fields) && $db->options['quote_identifier']) {
-            foreach ($table_fields as $key => $field) {
-                $table_fields[$key] = $db->quoteIdentifier($field);
-            }
-        }
-
-        if ($where !== false && !is_null($where)) {
-            if (is_array($where)) {
-                $where = implode(' AND ', $where);
-            }
-            $where = ' WHERE '.$where;
-        }
-
-        switch ($mode) {
-        case MDB2_AUTOQUERY_INSERT:
-            if (empty($table_fields)) {
-                return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                'Insert requires table fields', __FUNCTION__);
-            }
-            $cols = implode(', ', $table_fields);
-            $values = '?'.str_repeat(', ?', (count($table_fields) - 1));
-            return 'INSERT INTO '.$table.' ('.$cols.') VALUES ('.$values.')';
-            break;
-        case MDB2_AUTOQUERY_UPDATE:
-            if (empty($table_fields)) {
-                return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                'Update requires table fields', __FUNCTION__);
-            }
-            $set = implode(' = ?, ', $table_fields).' = ?';
-            $sql = 'UPDATE '.$table.' SET '.$set.$where;
-            return $sql;
-            break;
-        case MDB2_AUTOQUERY_DELETE:
-            $sql = 'DELETE FROM '.$table.$where;
-            return $sql;
-            break;
-        case MDB2_AUTOQUERY_SELECT:
-            $cols = !empty($table_fields) ? implode(', ', $table_fields) : '*';
-            $sql = 'SELECT '.$cols.' FROM '.$table.$where;
-            return $sql;
-            break;
-        }
-        return $db->raiseError(MDB2_ERROR_SYNTAX, null, null,
-                'Non existant mode', __FUNCTION__);
-    }
-
-    // }}}
-    // {{{ limitQuery()
-
-    /**
-     * Generates a limited query
-     *
-     * @param string query
-     * @param array that contains the types of the columns in the result set
-     * @param integer the numbers of rows to fetch
-     * @param integer the row to start to fetching
-     * @param string which specifies which result class to use
-     * @param mixed   string which specifies which class to wrap results in
-     *
-     * @return MDB2_Result|MDB2_Error result set on success, a MDB2 error on failure
-     * @access public
-     */
-    function &limitQuery($query, $types, $limit, $offset = 0, $result_class = true,
-        $result_wrap_class = false)
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        $result = $db->setLimit($limit, $offset);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-        $result =& $db->query($query, $types, $result_class, $result_wrap_class);
-        return $result;
-    }
-
-    // }}}
-    // {{{ execParam()
-
-    /**
-     * Execute a parameterized DML statement.
-     *
-     * @param string the SQL query
-     * @param array if supplied, prepare/execute will be used
-     *       with this array as execute parameters
-     * @param array that contains the types of the values defined in $params
-     *
-     * @return int|MDB2_Error affected rows on success, a MDB2 error on failure
-     * @access public
-     */
-    function execParam($query, $params = array(), $param_types = null)
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        settype($params, 'array');
-        if (empty($params)) {
-            return $db->exec($query);
-        }
-
-        $stmt = $db->prepare($query, $param_types, MDB2_PREPARE_MANIP);
-        if (PEAR::isError($stmt)) {
-            return $stmt;
-        }
-
-        $result = $stmt->execute($params);
-        if (PEAR::isError($result)) {
-            return $result;
-        }
-
-        $stmt->free();
-        return $result;
-    }
-
-    // }}}
-    // {{{ getOne()
-
-    /**
-     * Fetch the first column of the first row of data returned from a query.
-     * Takes care of doing the query and freeing the results when finished.
-     *
-     * @param string the SQL query
-     * @param string that contains the type of the column in the result set
-     * @param array if supplied, prepare/execute will be used
-     *       with this array as execute parameters
-     * @param array that contains the types of the values defined in $params
-     * @param int|string which column to return
-     *
-     * @return scalar|MDB2_Error data on success, a MDB2 error on failure
-     * @access public
-     */
-    function getOne($query, $type = null, $params = array(),
-        $param_types = null, $colnum = 0)
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        settype($params, 'array');
-        settype($type, 'array');
-        if (empty($params)) {
-            return $db->queryOne($query, $type, $colnum);
-        }
-
-        $stmt = $db->prepare($query, $param_types, $type);
-        if (PEAR::isError($stmt)) {
-            return $stmt;
-        }
-
-        $result = $stmt->execute($params);
-        if (!MDB2::isResultCommon($result)) {
-            return $result;
-        }
-
-        $one = $result->fetchOne($colnum);
-        $stmt->free();
-        $result->free();
-        return $one;
-    }
-
-    // }}}
-    // {{{ getRow()
-
-    /**
-     * Fetch the first row of data returned from a query.  Takes care
-     * of doing the query and freeing the results when finished.
-     *
-     * @param string the SQL query
-     * @param array that contains the types of the columns in the result set
-     * @param array if supplied, prepare/execute will be used
-     *       with this array as execute parameters
-     * @param array that contains the types of the values defined in $params
-     * @param int the fetch mode to use
-     *
-     * @return array|MDB2_Error data on success, a MDB2 error on failure
-     * @access public
-     */
-    function getRow($query, $types = null, $params = array(),
-        $param_types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        settype($params, 'array');
-        if (empty($params)) {
-            return $db->queryRow($query, $types, $fetchmode);
-        }
-
-        $stmt = $db->prepare($query, $param_types, $types);
-        if (PEAR::isError($stmt)) {
-            return $stmt;
-        }
-
-        $result = $stmt->execute($params);
-        if (!MDB2::isResultCommon($result)) {
-            return $result;
-        }
-
-        $row = $result->fetchRow($fetchmode);
-        $stmt->free();
-        $result->free();
-        return $row;
-    }
-
-    // }}}
-    // {{{ getCol()
-
-    /**
-     * Fetch a single column from a result set and return it as an
-     * indexed array.
-     *
-     * @param string the SQL query
-     * @param string that contains the type of the column in the result set
-     * @param array if supplied, prepare/execute will be used
-     *       with this array as execute parameters
-     * @param array that contains the types of the values defined in $params
-     * @param int|string which column to return
-     *
-     * @return array|MDB2_Error data on success, a MDB2 error on failure
-     * @access public
-     */
-    function getCol($query, $type = null, $params = array(),
-        $param_types = null, $colnum = 0)
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        settype($params, 'array');
-        settype($type, 'array');
-        if (empty($params)) {
-            return $db->queryCol($query, $type, $colnum);
-        }
-
-        $stmt = $db->prepare($query, $param_types, $type);
-        if (PEAR::isError($stmt)) {
-            return $stmt;
-        }
-
-        $result = $stmt->execute($params);
-        if (!MDB2::isResultCommon($result)) {
-            return $result;
-        }
-
-        $col = $result->fetchCol($colnum);
-        $stmt->free();
-        $result->free();
-        return $col;
-    }
-
-    // }}}
-    // {{{ getAll()
-
-    /**
-     * Fetch all the rows returned from a query.
-     *
-     * @param string the SQL query
-     * @param array that contains the types of the columns in the result set
-     * @param array if supplied, prepare/execute will be used
-     *       with this array as execute parameters
-     * @param array that contains the types of the values defined in $params
-     * @param int the fetch mode to use
-     * @param bool if set to true, the $all will have the first
-     *       column as its first dimension
-     * @param bool $force_array used only when the query returns exactly
-     *       two columns. If true, the values of the returned array will be
-     *       one-element arrays instead of scalars.
-     * @param bool $group if true, the values of the returned array is
-     *       wrapped in another array.  If the same key value (in the first
-     *       column) repeats itself, the values will be appended to this array
-     *       instead of overwriting the existing values.
-     *
-     * @return array|MDB2_Error data on success, a MDB2 error on failure
-     * @access public
-     */
-    function getAll($query, $types = null, $params = array(),
-        $param_types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT,
-        $rekey = false, $force_array = false, $group = false)
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        settype($params, 'array');
-        if (empty($params)) {
-            return $db->queryAll($query, $types, $fetchmode, $rekey, $force_array, $group);
-        }
-
-        $stmt = $db->prepare($query, $param_types, $types);
-        if (PEAR::isError($stmt)) {
-            return $stmt;
-        }
-
-        $result = $stmt->execute($params);
-        if (!MDB2::isResultCommon($result)) {
-            return $result;
-        }
-
-        $all = $result->fetchAll($fetchmode, $rekey, $force_array, $group);
-        $stmt->free();
-        $result->free();
-        return $all;
-    }
-
-    // }}}
-    // {{{ getAssoc()
-
-    /**
-     * Fetch the entire result set of a query and return it as an
-     * associative array using the first column as the key.
-     *
-     * If the result set contains more than two columns, the value
-     * will be an array of the values from column 2-n.  If the result
-     * set contains only two columns, the returned value will be a
-     * scalar with the value of the second column (unless forced to an
-     * array with the $force_array parameter).  A MDB2 error code is
-     * returned on errors.  If the result set contains fewer than two
-     * columns, a MDB2_ERROR_TRUNCATED error is returned.
-     *
-     * For example, if the table 'mytable' contains:
-     * <pre>
-     *   ID      TEXT       DATE
-     * --------------------------------
-     *   1       'one'      944679408
-     *   2       'two'      944679408
-     *   3       'three'    944679408
-     * </pre>
-     * Then the call getAssoc('SELECT id,text FROM mytable') returns:
-     * <pre>
-     *    array(
-     *      '1' => 'one',
-     *      '2' => 'two',
-     *      '3' => 'three',
-     *    )
-     * </pre>
-     * ...while the call getAssoc('SELECT id,text,date FROM mytable') returns:
-     * <pre>
-     *    array(
-     *      '1' => array('one', '944679408'),
-     *      '2' => array('two', '944679408'),
-     *      '3' => array('three', '944679408')
-     *    )
-     * </pre>
-     *
-     * If the more than one row occurs with the same value in the
-     * first column, the last row overwrites all previous ones by
-     * default.  Use the $group parameter if you don't want to
-     * overwrite like this.  Example:
-     * <pre>
-     * getAssoc('SELECT category,id,name FROM mytable', null, null
-     *           MDB2_FETCHMODE_ASSOC, false, true) returns:
-     *    array(
-     *      '1' => array(array('id' => '4', 'name' => 'number four'),
-     *                   array('id' => '6', 'name' => 'number six')
-     *             ),
-     *      '9' => array(array('id' => '4', 'name' => 'number four'),
-     *                   array('id' => '6', 'name' => 'number six')
-     *             )
-     *    )
-     * </pre>
-     *
-     * Keep in mind that database functions in PHP usually return string
-     * values for results regardless of the database's internal type.
-     *
-     * @param string the SQL query
-     * @param array that contains the types of the columns in the result set
-     * @param array if supplied, prepare/execute will be used
-     *       with this array as execute parameters
-     * @param array that contains the types of the values defined in $params
-     * @param bool $force_array used only when the query returns
-     * exactly two columns.  If TRUE, the values of the returned array
-     * will be one-element arrays instead of scalars.
-     * @param bool $group if TRUE, the values of the returned array
-     *       is wrapped in another array.  If the same key value (in the first
-     *       column) repeats itself, the values will be appended to this array
-     *       instead of overwriting the existing values.
-     *
-     * @return array|MDB2_Error data on success, a MDB2 error on failure
-     * @access public
-     */
-    function getAssoc($query, $types = null, $params = array(), $param_types = null,
-        $fetchmode = MDB2_FETCHMODE_DEFAULT, $force_array = false, $group = false)
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        settype($params, 'array');
-        if (empty($params)) {
-            return $db->queryAll($query, $types, $fetchmode, true, $force_array, $group);
-        }
-
-        $stmt = $db->prepare($query, $param_types, $types);
-        if (PEAR::isError($stmt)) {
-            return $stmt;
-        }
-
-        $result = $stmt->execute($params);
-        if (!MDB2::isResultCommon($result)) {
-            return $result;
-        }
-
-        $all = $result->fetchAll($fetchmode, true, $force_array, $group);
-        $stmt->free();
-        $result->free();
-        return $all;
-    }
-
-    // }}}
-    // {{{ executeMultiple()
-
-    /**
-     * This function does several execute() calls on the same statement handle.
-     * $params must be an array indexed numerically from 0, one execute call is
-     * done for every 'row' in the array.
-     *
-     * If an error occurs during execute(), executeMultiple() does not execute
-     * the unfinished rows, but rather returns that error.
-     *
-     * @param resource query handle from prepare()
-     * @param array numeric array containing the data to insert into the query
-     *
-     * @return bool|MDB2_Error true on success, a MDB2 error on failure
-     * @access public
-     * @see prepare(), execute()
-     */
-    function executeMultiple(&$stmt, $params = null)
-    {
-        for ($i = 0, $j = count($params); $i < $j; $i++) {
-            $result = $stmt->execute($params[$i]);
-            if (PEAR::isError($result)) {
-                return $result;
-            }
-        }
-        return MDB2_OK;
-    }
-
-    // }}}
-    // {{{ getBeforeID()
-
-    /**
-     * Returns the next free id of a sequence if the RDBMS
-     * does not support auto increment
-     *
-     * @param string name of the table into which a new row was inserted
-     * @param string name of the field into which a new row was inserted
-     * @param bool when true the sequence is automatic created, if it not exists
-     * @param bool if the returned value should be quoted
-     *
-     * @return int|MDB2_Error id on success, a MDB2 error on failure
-     * @access public
-     */
-    function getBeforeID($table, $field = null, $ondemand = true, $quote = true)
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        if ($db->supports('auto_increment') !== true) {
-            $seq = $table.(empty($field) ? '' : '_'.$field);
-            $id = $db->nextID($seq, $ondemand);
-            if (!$quote || PEAR::isError($id)) {
-                return $id;
-            }
-            return $db->quote($id, 'integer');
-        } elseif (!$quote) {
-            return null;
-        }
-        return 'NULL';
-    }
-
-    // }}}
-    // {{{ getAfterID()
-
-    /**
-     * Returns the autoincrement ID if supported or $id
-     *
-     * @param mixed value as returned by getBeforeId()
-     * @param string name of the table into which a new row was inserted
-     * @param string name of the field into which a new row was inserted
-     *
-     * @return int|MDB2_Error id on success, a MDB2 error on failure
-     * @access public
-     */
-    function getAfterID($id, $table, $field = null)
-    {
-        $db =& $this->getDBInstance();
-        if (PEAR::isError($db)) {
-            return $db;
-        }
-
-        if ($db->supports('auto_increment') !== true) {
-            return $id;
-        }
-        return $db->lastInsertID($table, $field);
-    }
-
-    // }}}
-}
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP versions 4 and 5                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: Extended.php 302784 2010-08-25 23:29:16Z quipo $\r
+\r
+/**\r
+ * @package  MDB2\r
+ * @category Database\r
+ * @author   Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+\r
+/**\r
+ * Used by autoPrepare()\r
+ */\r
+define('MDB2_AUTOQUERY_INSERT', 1);\r
+define('MDB2_AUTOQUERY_UPDATE', 2);\r
+define('MDB2_AUTOQUERY_DELETE', 3);\r
+define('MDB2_AUTOQUERY_SELECT', 4);\r
+\r
+/**\r
+ * MDB2_Extended: class which adds several high level methods to MDB2\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Extended extends MDB2_Module_Common\r
+{\r
+    // {{{ autoPrepare()\r
+\r
+    /**\r
+     * Generate an insert, update or delete query and call prepare() on it\r
+     *\r
+     * @param string table\r
+     * @param array the fields names\r
+     * @param int type of query to build\r
+     *                          MDB2_AUTOQUERY_INSERT\r
+     *                          MDB2_AUTOQUERY_UPDATE\r
+     *                          MDB2_AUTOQUERY_DELETE\r
+     *                          MDB2_AUTOQUERY_SELECT\r
+     * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)\r
+     * @param array that contains the types of the placeholders\r
+     * @param mixed array that contains the types of the columns in\r
+     *                        the result set or MDB2_PREPARE_RESULT, if set to\r
+     *                        MDB2_PREPARE_MANIP the query is handled as a manipulation query\r
+     *\r
+     * @return resource handle for the query\r
+     * @see buildManipSQL\r
+     * @access public\r
+     */\r
+    function autoPrepare($table, $table_fields, $mode = MDB2_AUTOQUERY_INSERT,\r
+        $where = false, $types = null, $result_types = MDB2_PREPARE_MANIP)\r
+    {\r
+        $query = $this->buildManipSQL($table, $table_fields, $mode, $where);\r
+        if (PEAR::isError($query)) {\r
+            return $query;\r
+        }\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+        $lobs = array();\r
+        foreach ((array)$types as $param => $type) {\r
+            if (($type == 'clob') || ($type == 'blob')) {\r
+                $lobs[$param] = $table_fields[$param];\r
+            }\r
+        }\r
+        return $db->prepare($query, $types, $result_types, $lobs);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ autoExecute()\r
+\r
+    /**\r
+     * Generate an insert, update or delete query and call prepare() and execute() on it\r
+     *\r
+     * @param string name of the table\r
+     * @param array assoc ($key=>$value) where $key is a field name and $value its value\r
+     * @param int type of query to build\r
+     *                          MDB2_AUTOQUERY_INSERT\r
+     *                          MDB2_AUTOQUERY_UPDATE\r
+     *                          MDB2_AUTOQUERY_DELETE\r
+     *                          MDB2_AUTOQUERY_SELECT\r
+     * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)\r
+     * @param array that contains the types of the placeholders\r
+     * @param string which specifies which result class to use\r
+     * @param mixed  array that contains the types of the columns in\r
+     *                        the result set or MDB2_PREPARE_RESULT, if set to\r
+     *                        MDB2_PREPARE_MANIP the query is handled as a manipulation query\r
+     *\r
+     * @return bool|MDB2_Error true on success, a MDB2 error on failure\r
+     * @see buildManipSQL\r
+     * @see autoPrepare\r
+     * @access public\r
+    */\r
+    function autoExecute($table, $fields_values, $mode = MDB2_AUTOQUERY_INSERT,\r
+        $where = false, $types = null, $result_class = true, $result_types = MDB2_PREPARE_MANIP)\r
+    {\r
+        $fields_values = (array)$fields_values;\r
+        if ($mode == MDB2_AUTOQUERY_SELECT) {\r
+            if (is_array($result_types)) {\r
+                $keys = array_keys($result_types);\r
+            } elseif (!empty($fields_values)) {\r
+                $keys = $fields_values;\r
+            } else {\r
+                $keys = array();\r
+            }\r
+        } else {\r
+            $keys = array_keys($fields_values);\r
+        }\r
+        $params = array_values($fields_values);\r
+        if (empty($params)) {\r
+            $query = $this->buildManipSQL($table, $keys, $mode, $where);\r
+\r
+            $db = $this->getDBInstance();\r
+            if (PEAR::isError($db)) {\r
+                return $db;\r
+            }\r
+            if ($mode == MDB2_AUTOQUERY_SELECT) {\r
+                $result = $db->query($query, $result_types, $result_class);\r
+            } else {\r
+                $result = $db->exec($query);\r
+            }\r
+        } else {\r
+            $stmt = $this->autoPrepare($table, $keys, $mode, $where, $types, $result_types);\r
+            if (PEAR::isError($stmt)) {\r
+                return $stmt;\r
+            }\r
+            $result = $stmt->execute($params, $result_class);\r
+            $stmt->free();\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ buildManipSQL()\r
+\r
+    /**\r
+     * Make automaticaly an sql query for prepare()\r
+     *\r
+     * Example : buildManipSQL('table_sql', array('field1', 'field2', 'field3'), MDB2_AUTOQUERY_INSERT)\r
+     *           will return the string : INSERT INTO table_sql (field1,field2,field3) VALUES (?,?,?)\r
+     * NB : - This belongs more to a SQL Builder class, but this is a simple facility\r
+     *      - Be carefull ! If you don't give a $where param with an UPDATE/DELETE query, all\r
+     *        the records of the table will be updated/deleted !\r
+     *\r
+     * @param string name of the table\r
+     * @param ordered array containing the fields names\r
+     * @param int type of query to build\r
+     *                          MDB2_AUTOQUERY_INSERT\r
+     *                          MDB2_AUTOQUERY_UPDATE\r
+     *                          MDB2_AUTOQUERY_DELETE\r
+     *                          MDB2_AUTOQUERY_SELECT\r
+     * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)\r
+     *\r
+     * @return string sql query for prepare()\r
+     * @access public\r
+     */\r
+    function buildManipSQL($table, $table_fields, $mode, $where = false)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        if ($db->options['quote_identifier']) {\r
+            $table = $db->quoteIdentifier($table);\r
+        }\r
+\r
+        if (!empty($table_fields) && $db->options['quote_identifier']) {\r
+            foreach ($table_fields as $key => $field) {\r
+                $table_fields[$key] = $db->quoteIdentifier($field);\r
+            }\r
+        }\r
+\r
+        if ((false !== $where) && (null !== $where)) {\r
+            if (is_array($where)) {\r
+                $where = implode(' AND ', $where);\r
+            }\r
+            $where = ' WHERE '.$where;\r
+        }\r
+\r
+        switch ($mode) {\r
+        case MDB2_AUTOQUERY_INSERT:\r
+            if (empty($table_fields)) {\r
+                return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,\r
+                'Insert requires table fields', __FUNCTION__);\r
+            }\r
+            $cols = implode(', ', $table_fields);\r
+            $values = '?'.str_repeat(', ?', (count($table_fields) - 1));\r
+            return 'INSERT INTO '.$table.' ('.$cols.') VALUES ('.$values.')';\r
+            break;\r
+        case MDB2_AUTOQUERY_UPDATE:\r
+            if (empty($table_fields)) {\r
+                return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,\r
+                'Update requires table fields', __FUNCTION__);\r
+            }\r
+            $set = implode(' = ?, ', $table_fields).' = ?';\r
+            $sql = 'UPDATE '.$table.' SET '.$set.$where;\r
+            return $sql;\r
+            break;\r
+        case MDB2_AUTOQUERY_DELETE:\r
+            $sql = 'DELETE FROM '.$table.$where;\r
+            return $sql;\r
+            break;\r
+        case MDB2_AUTOQUERY_SELECT:\r
+            $cols = !empty($table_fields) ? implode(', ', $table_fields) : '*';\r
+            $sql = 'SELECT '.$cols.' FROM '.$table.$where;\r
+            return $sql;\r
+            break;\r
+        }\r
+        return $db->raiseError(MDB2_ERROR_SYNTAX, null, null,\r
+                'Non existant mode', __FUNCTION__);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ limitQuery()\r
+\r
+    /**\r
+     * Generates a limited query\r
+     *\r
+     * @param string query\r
+     * @param array that contains the types of the columns in the result set\r
+     * @param integer the numbers of rows to fetch\r
+     * @param integer the row to start to fetching\r
+     * @param string which specifies which result class to use\r
+     * @param mixed   string which specifies which class to wrap results in\r
+     *\r
+     * @return MDB2_Result|MDB2_Error result set on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function limitQuery($query, $types, $limit, $offset = 0, $result_class = true,\r
+        $result_wrap_class = false)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        $result = $db->setLimit($limit, $offset);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+        return $db->query($query, $types, $result_class, $result_wrap_class);\r
+    }\r
+\r
+    // }}}\r
+    // {{{ execParam()\r
+\r
+    /**\r
+     * Execute a parameterized DML statement.\r
+     *\r
+     * @param string the SQL query\r
+     * @param array if supplied, prepare/execute will be used\r
+     *       with this array as execute parameters\r
+     * @param array that contains the types of the values defined in $params\r
+     *\r
+     * @return int|MDB2_Error affected rows on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function execParam($query, $params = array(), $param_types = null)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        settype($params, 'array');\r
+        if (empty($params)) {\r
+            return $db->exec($query);\r
+        }\r
+\r
+        $stmt = $db->prepare($query, $param_types, MDB2_PREPARE_MANIP);\r
+        if (PEAR::isError($stmt)) {\r
+            return $stmt;\r
+        }\r
+\r
+        $result = $stmt->execute($params);\r
+        if (PEAR::isError($result)) {\r
+            return $result;\r
+        }\r
+\r
+        $stmt->free();\r
+        return $result;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getOne()\r
+\r
+    /**\r
+     * Fetch the first column of the first row of data returned from a query.\r
+     * Takes care of doing the query and freeing the results when finished.\r
+     *\r
+     * @param string the SQL query\r
+     * @param string that contains the type of the column in the result set\r
+     * @param array if supplied, prepare/execute will be used\r
+     *       with this array as execute parameters\r
+     * @param array that contains the types of the values defined in $params\r
+     * @param int|string which column to return\r
+     *\r
+     * @return scalar|MDB2_Error data on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function getOne($query, $type = null, $params = array(),\r
+        $param_types = null, $colnum = 0)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        settype($params, 'array');\r
+        settype($type, 'array');\r
+        if (empty($params)) {\r
+            return $db->queryOne($query, $type, $colnum);\r
+        }\r
+\r
+        $stmt = $db->prepare($query, $param_types, $type);\r
+        if (PEAR::isError($stmt)) {\r
+            return $stmt;\r
+        }\r
+\r
+        $result = $stmt->execute($params);\r
+        if (!MDB2::isResultCommon($result)) {\r
+            return $result;\r
+        }\r
+\r
+        $one = $result->fetchOne($colnum);\r
+        $stmt->free();\r
+        $result->free();\r
+        return $one;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getRow()\r
+\r
+    /**\r
+     * Fetch the first row of data returned from a query.  Takes care\r
+     * of doing the query and freeing the results when finished.\r
+     *\r
+     * @param string the SQL query\r
+     * @param array that contains the types of the columns in the result set\r
+     * @param array if supplied, prepare/execute will be used\r
+     *       with this array as execute parameters\r
+     * @param array that contains the types of the values defined in $params\r
+     * @param int the fetch mode to use\r
+     *\r
+     * @return array|MDB2_Error data on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function getRow($query, $types = null, $params = array(),\r
+        $param_types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        settype($params, 'array');\r
+        if (empty($params)) {\r
+            return $db->queryRow($query, $types, $fetchmode);\r
+        }\r
+\r
+        $stmt = $db->prepare($query, $param_types, $types);\r
+        if (PEAR::isError($stmt)) {\r
+            return $stmt;\r
+        }\r
+\r
+        $result = $stmt->execute($params);\r
+        if (!MDB2::isResultCommon($result)) {\r
+            return $result;\r
+        }\r
+\r
+        $row = $result->fetchRow($fetchmode);\r
+        $stmt->free();\r
+        $result->free();\r
+        return $row;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getCol()\r
+\r
+    /**\r
+     * Fetch a single column from a result set and return it as an\r
+     * indexed array.\r
+     *\r
+     * @param string the SQL query\r
+     * @param string that contains the type of the column in the result set\r
+     * @param array if supplied, prepare/execute will be used\r
+     *       with this array as execute parameters\r
+     * @param array that contains the types of the values defined in $params\r
+     * @param int|string which column to return\r
+     *\r
+     * @return array|MDB2_Error data on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function getCol($query, $type = null, $params = array(),\r
+        $param_types = null, $colnum = 0)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        settype($params, 'array');\r
+        settype($type, 'array');\r
+        if (empty($params)) {\r
+            return $db->queryCol($query, $type, $colnum);\r
+        }\r
+\r
+        $stmt = $db->prepare($query, $param_types, $type);\r
+        if (PEAR::isError($stmt)) {\r
+            return $stmt;\r
+        }\r
+\r
+        $result = $stmt->execute($params);\r
+        if (!MDB2::isResultCommon($result)) {\r
+            return $result;\r
+        }\r
+\r
+        $col = $result->fetchCol($colnum);\r
+        $stmt->free();\r
+        $result->free();\r
+        return $col;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getAll()\r
+\r
+    /**\r
+     * Fetch all the rows returned from a query.\r
+     *\r
+     * @param string the SQL query\r
+     * @param array that contains the types of the columns in the result set\r
+     * @param array if supplied, prepare/execute will be used\r
+     *       with this array as execute parameters\r
+     * @param array that contains the types of the values defined in $params\r
+     * @param int the fetch mode to use\r
+     * @param bool if set to true, the $all will have the first\r
+     *       column as its first dimension\r
+     * @param bool $force_array used only when the query returns exactly\r
+     *       two columns. If true, the values of the returned array will be\r
+     *       one-element arrays instead of scalars.\r
+     * @param bool $group if true, the values of the returned array is\r
+     *       wrapped in another array.  If the same key value (in the first\r
+     *       column) repeats itself, the values will be appended to this array\r
+     *       instead of overwriting the existing values.\r
+     *\r
+     * @return array|MDB2_Error data on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function getAll($query, $types = null, $params = array(),\r
+        $param_types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT,\r
+        $rekey = false, $force_array = false, $group = false)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        settype($params, 'array');\r
+        if (empty($params)) {\r
+            return $db->queryAll($query, $types, $fetchmode, $rekey, $force_array, $group);\r
+        }\r
+\r
+        $stmt = $db->prepare($query, $param_types, $types);\r
+        if (PEAR::isError($stmt)) {\r
+            return $stmt;\r
+        }\r
+\r
+        $result = $stmt->execute($params);\r
+        if (!MDB2::isResultCommon($result)) {\r
+            return $result;\r
+        }\r
+\r
+        $all = $result->fetchAll($fetchmode, $rekey, $force_array, $group);\r
+        $stmt->free();\r
+        $result->free();\r
+        return $all;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getAssoc()\r
+\r
+    /**\r
+     * Fetch the entire result set of a query and return it as an\r
+     * associative array using the first column as the key.\r
+     *\r
+     * If the result set contains more than two columns, the value\r
+     * will be an array of the values from column 2-n.  If the result\r
+     * set contains only two columns, the returned value will be a\r
+     * scalar with the value of the second column (unless forced to an\r
+     * array with the $force_array parameter).  A MDB2 error code is\r
+     * returned on errors.  If the result set contains fewer than two\r
+     * columns, a MDB2_ERROR_TRUNCATED error is returned.\r
+     *\r
+     * For example, if the table 'mytable' contains:\r
+     * <pre>\r
+     *   ID      TEXT       DATE\r
+     * --------------------------------\r
+     *   1       'one'      944679408\r
+     *   2       'two'      944679408\r
+     *   3       'three'    944679408\r
+     * </pre>\r
+     * Then the call getAssoc('SELECT id,text FROM mytable') returns:\r
+     * <pre>\r
+     *    array(\r
+     *      '1' => 'one',\r
+     *      '2' => 'two',\r
+     *      '3' => 'three',\r
+     *    )\r
+     * </pre>\r
+     * ...while the call getAssoc('SELECT id,text,date FROM mytable') returns:\r
+     * <pre>\r
+     *    array(\r
+     *      '1' => array('one', '944679408'),\r
+     *      '2' => array('two', '944679408'),\r
+     *      '3' => array('three', '944679408')\r
+     *    )\r
+     * </pre>\r
+     *\r
+     * If the more than one row occurs with the same value in the\r
+     * first column, the last row overwrites all previous ones by\r
+     * default.  Use the $group parameter if you don't want to\r
+     * overwrite like this.  Example:\r
+     * <pre>\r
+     * getAssoc('SELECT category,id,name FROM mytable', null, null\r
+     *           MDB2_FETCHMODE_ASSOC, false, true) returns:\r
+     *    array(\r
+     *      '1' => array(array('id' => '4', 'name' => 'number four'),\r
+     *                   array('id' => '6', 'name' => 'number six')\r
+     *             ),\r
+     *      '9' => array(array('id' => '4', 'name' => 'number four'),\r
+     *                   array('id' => '6', 'name' => 'number six')\r
+     *             )\r
+     *    )\r
+     * </pre>\r
+     *\r
+     * Keep in mind that database functions in PHP usually return string\r
+     * values for results regardless of the database's internal type.\r
+     *\r
+     * @param string the SQL query\r
+     * @param array that contains the types of the columns in the result set\r
+     * @param array if supplied, prepare/execute will be used\r
+     *       with this array as execute parameters\r
+     * @param array that contains the types of the values defined in $params\r
+     * @param bool $force_array used only when the query returns\r
+     * exactly two columns.  If TRUE, the values of the returned array\r
+     * will be one-element arrays instead of scalars.\r
+     * @param bool $group if TRUE, the values of the returned array\r
+     *       is wrapped in another array.  If the same key value (in the first\r
+     *       column) repeats itself, the values will be appended to this array\r
+     *       instead of overwriting the existing values.\r
+     *\r
+     * @return array|MDB2_Error data on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function getAssoc($query, $types = null, $params = array(), $param_types = null,\r
+        $fetchmode = MDB2_FETCHMODE_DEFAULT, $force_array = false, $group = false)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        settype($params, 'array');\r
+        if (empty($params)) {\r
+            return $db->queryAll($query, $types, $fetchmode, true, $force_array, $group);\r
+        }\r
+\r
+        $stmt = $db->prepare($query, $param_types, $types);\r
+        if (PEAR::isError($stmt)) {\r
+            return $stmt;\r
+        }\r
+\r
+        $result = $stmt->execute($params);\r
+        if (!MDB2::isResultCommon($result)) {\r
+            return $result;\r
+        }\r
+\r
+        $all = $result->fetchAll($fetchmode, true, $force_array, $group);\r
+        $stmt->free();\r
+        $result->free();\r
+        return $all;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ executeMultiple()\r
+\r
+    /**\r
+     * This function does several execute() calls on the same statement handle.\r
+     * $params must be an array indexed numerically from 0, one execute call is\r
+     * done for every 'row' in the array.\r
+     *\r
+     * If an error occurs during execute(), executeMultiple() does not execute\r
+     * the unfinished rows, but rather returns that error.\r
+     *\r
+     * @param resource query handle from prepare()\r
+     * @param array numeric array containing the data to insert into the query\r
+     *\r
+     * @return bool|MDB2_Error true on success, a MDB2 error on failure\r
+     * @access public\r
+     * @see prepare(), execute()\r
+     */\r
+    function executeMultiple($stmt, $params = null)\r
+    {\r
+        for ($i = 0, $j = count($params); $i < $j; $i++) {\r
+            $result = $stmt->execute($params[$i]);\r
+            if (PEAR::isError($result)) {\r
+                return $result;\r
+            }\r
+        }\r
+        return MDB2_OK;\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getBeforeID()\r
+\r
+    /**\r
+     * Returns the next free id of a sequence if the RDBMS\r
+     * does not support auto increment\r
+     *\r
+     * @param string name of the table into which a new row was inserted\r
+     * @param string name of the field into which a new row was inserted\r
+     * @param bool when true the sequence is automatic created, if it not exists\r
+     * @param bool if the returned value should be quoted\r
+     *\r
+     * @return int|MDB2_Error id on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function getBeforeID($table, $field = null, $ondemand = true, $quote = true)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        if ($db->supports('auto_increment') !== true) {\r
+            $seq = $table.(empty($field) ? '' : '_'.$field);\r
+            $id = $db->nextID($seq, $ondemand);\r
+            if (!$quote || PEAR::isError($id)) {\r
+                return $id;\r
+            }\r
+            return $db->quote($id, 'integer');\r
+        } elseif (!$quote) {\r
+            return null;\r
+        }\r
+        return 'NULL';\r
+    }\r
+\r
+    // }}}\r
+    // {{{ getAfterID()\r
+\r
+    /**\r
+     * Returns the autoincrement ID if supported or $id\r
+     *\r
+     * @param mixed value as returned by getBeforeId()\r
+     * @param string name of the table into which a new row was inserted\r
+     * @param string name of the field into which a new row was inserted\r
+     *\r
+     * @return int|MDB2_Error id on success, a MDB2 error on failure\r
+     * @access public\r
+     */\r
+    function getAfterID($id, $table, $field = null)\r
+    {\r
+        $db = $this->getDBInstance();\r
+        if (PEAR::isError($db)) {\r
+            return $db;\r
+        }\r
+\r
+        if ($db->supports('auto_increment') !== true) {\r
+            return $id;\r
+        }\r
+        return $db->lastInsertID($table, $field);\r
+    }\r
+\r
+    // }}}\r
+}\r
 ?>
\ No newline at end of file
index ca5e7b69c27df7091c4b01483ada57d2435f2440..8d31919b6deff679bd3c8233c874cd512488de74 100644 (file)
-<?php
-// +----------------------------------------------------------------------+
-// | PHP version 5                                                        |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: Iterator.php,v 1.22 2006/05/06 14:03:41 lsmith Exp $
-
-/**
- * PHP5 Iterator
- *
- * @package  MDB2
- * @category Database
- * @author   Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Iterator implements Iterator
-{
-    protected $fetchmode;
-    protected $result;
-    protected $row;
-
-    // {{{ constructor
-
-    /**
-     * Constructor
-     */
-    public function __construct($result, $fetchmode = MDB2_FETCHMODE_DEFAULT)
-    {
-        $this->result = $result;
-        $this->fetchmode = $fetchmode;
-    }
-    // }}}
-
-    // {{{ seek()
-
-    /**
-     * Seek forward to a specific row in a result set
-     *
-     * @param int number of the row where the data can be found
-     *
-     * @return void
-     * @access public
-     */
-    public function seek($rownum)
-    {
-        $this->row = null;
-        if ($this->result) {
-            $this->result->seek($rownum);
-        }
-    }
-    // }}}
-
-    // {{{ next()
-
-    /**
-     * Fetch next row of data
-     *
-     * @return void
-     * @access public
-     */
-    public function next()
-    {
-        $this->row = null;
-    }
-    // }}}
-
-    // {{{ current()
-
-    /**
-     * return a row of data
-     *
-     * @return void
-     * @access public
-     */
-    public function current()
-    {
-        if (is_null($this->row)) {
-            $row = $this->result->fetchRow($this->fetchmode);
-            if (PEAR::isError($row)) {
-                $row = false;
-            }
-            $this->row = $row;
-        }
-        return $this->row;
-    }
-    // }}}
-
-    // {{{ valid()
-
-    /**
-     * Check if the end of the result set has been reached
-     *
-     * @return bool true/false, false is also returned on failure
-     * @access public
-     */
-    public function valid()
-    {
-        return (bool)$this->current();
-    }
-    // }}}
-
-    // {{{ free()
-
-    /**
-     * Free the internal resources associated with result.
-     *
-     * @return bool|MDB2_Error true on success, false|MDB2_Error if result is invalid
-     * @access public
-     */
-    public function free()
-    {
-        if ($this->result) {
-            return $this->result->free();
-        }
-        $this->result = false;
-        $this->row = null;
-        return false;
-    }
-    // }}}
-
-    // {{{ key()
-
-    /**
-     * Returns the row number
-     *
-     * @return int|bool|MDB2_Error true on success, false|MDB2_Error if result is invalid
-     * @access public
-     */
-    public function key()
-    {
-        if ($this->result) {
-            return $this->result->rowCount();
-        }
-        return false;
-    }
-    // }}}
-
-    // {{{ rewind()
-
-    /**
-     * Seek to the first row in a result set
-     *
-     * @return void
-     * @access public
-     */
-    public function rewind()
-    {
-    }
-    // }}}
-
-    // {{{ destructor
-
-    /**
-     * Destructor
-     */
-    public function __destruct()
-    {
-        $this->free();
-    }
-    // }}}
-}
-
-/**
- * PHP5 buffered Iterator
- *
- * @package  MDB2
- * @category Database
- * @author   Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_BufferedIterator extends MDB2_Iterator implements SeekableIterator
-{
-    // {{{ valid()
-
-    /**
-     * Check if the end of the result set has been reached
-     *
-     * @return bool|MDB2_Error true on success, false|MDB2_Error if result is invalid
-     * @access public
-     */
-    public function valid()
-    {
-        if ($this->result) {
-            return $this->result->valid();
-        }
-        return false;
-    }
-    // }}}
-
-    // {{{count()
-
-    /**
-     * Returns the number of rows in a result object
-     *
-     * @return int|MDB2_Error number of rows, false|MDB2_Error if result is invalid
-     * @access public
-     */
-    public function count()
-    {
-        if ($this->result) {
-            return $this->result->numRows();
-        }
-        return false;
-    }
-    // }}}
-
-    // {{{ rewind()
-
-    /**
-     * Seek to the first row in a result set
-     *
-     * @return void
-     * @access public
-     */
-    public function rewind()
-    {
-        $this->seek(0);
-    }
-    // }}}
-}
-
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP version 5                                                        |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: Iterator.php 295586 2010-02-28 17:04:17Z quipo $\r
+\r
+/**\r
+ * PHP5 Iterator\r
+ *\r
+ * @package  MDB2\r
+ * @category Database\r
+ * @author   Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_Iterator implements Iterator\r
+{\r
+    protected $fetchmode;\r
+    protected $result;\r
+    protected $row;\r
+\r
+    // {{{ constructor\r
+\r
+    /**\r
+     * Constructor\r
+     */\r
+    public function __construct($result, $fetchmode = MDB2_FETCHMODE_DEFAULT)\r
+    {\r
+        $this->result = $result;\r
+        $this->fetchmode = $fetchmode;\r
+    }\r
+    // }}}\r
+\r
+    // {{{ seek()\r
+\r
+    /**\r
+     * Seek forward to a specific row in a result set\r
+     *\r
+     * @param int number of the row where the data can be found\r
+     *\r
+     * @return void\r
+     * @access public\r
+     */\r
+    public function seek($rownum)\r
+    {\r
+        $this->row = null;\r
+        if ($this->result) {\r
+            $this->result->seek($rownum);\r
+        }\r
+    }\r
+    // }}}\r
+\r
+    // {{{ next()\r
+\r
+    /**\r
+     * Fetch next row of data\r
+     *\r
+     * @return void\r
+     * @access public\r
+     */\r
+    public function next()\r
+    {\r
+        $this->row = null;\r
+    }\r
+    // }}}\r
+\r
+    // {{{ current()\r
+\r
+    /**\r
+     * return a row of data\r
+     *\r
+     * @return void\r
+     * @access public\r
+     */\r
+    public function current()\r
+    {\r
+        if (null === $this->row) {\r
+            $row = $this->result->fetchRow($this->fetchmode);\r
+            if (PEAR::isError($row)) {\r
+                $row = false;\r
+            }\r
+            $this->row = $row;\r
+        }\r
+        return $this->row;\r
+    }\r
+    // }}}\r
+\r
+    // {{{ valid()\r
+\r
+    /**\r
+     * Check if the end of the result set has been reached\r
+     *\r
+     * @return bool true/false, false is also returned on failure\r
+     * @access public\r
+     */\r
+    public function valid()\r
+    {\r
+        return (bool)$this->current();\r
+    }\r
+    // }}}\r
+\r
+    // {{{ free()\r
+\r
+    /**\r
+     * Free the internal resources associated with result.\r
+     *\r
+     * @return bool|MDB2_Error true on success, false|MDB2_Error if result is invalid\r
+     * @access public\r
+     */\r
+    public function free()\r
+    {\r
+        if ($this->result) {\r
+            return $this->result->free();\r
+        }\r
+        $this->result = false;\r
+        $this->row = null;\r
+        return false;\r
+    }\r
+    // }}}\r
+\r
+    // {{{ key()\r
+\r
+    /**\r
+     * Returns the row number\r
+     *\r
+     * @return int|bool|MDB2_Error true on success, false|MDB2_Error if result is invalid\r
+     * @access public\r
+     */\r
+    public function key()\r
+    {\r
+        if ($this->result) {\r
+            return $this->result->rowCount();\r
+        }\r
+        return false;\r
+    }\r
+    // }}}\r
+\r
+    // {{{ rewind()\r
+\r
+    /**\r
+     * Seek to the first row in a result set\r
+     *\r
+     * @return void\r
+     * @access public\r
+     */\r
+    public function rewind()\r
+    {\r
+    }\r
+    // }}}\r
+\r
+    // {{{ destructor\r
+\r
+    /**\r
+     * Destructor\r
+     */\r
+    public function __destruct()\r
+    {\r
+        $this->free();\r
+    }\r
+    // }}}\r
+}\r
+\r
+/**\r
+ * PHP5 buffered Iterator\r
+ *\r
+ * @package  MDB2\r
+ * @category Database\r
+ * @author   Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_BufferedIterator extends MDB2_Iterator implements SeekableIterator\r
+{\r
+    // {{{ valid()\r
+\r
+    /**\r
+     * Check if the end of the result set has been reached\r
+     *\r
+     * @return bool|MDB2_Error true on success, false|MDB2_Error if result is invalid\r
+     * @access public\r
+     */\r
+    public function valid()\r
+    {\r
+        if ($this->result) {\r
+            return $this->result->valid();\r
+        }\r
+        return false;\r
+    }\r
+    // }}}\r
+\r
+    // {{{count()\r
+\r
+    /**\r
+     * Returns the number of rows in a result object\r
+     *\r
+     * @return int|MDB2_Error number of rows, false|MDB2_Error if result is invalid\r
+     * @access public\r
+     */\r
+    public function count()\r
+    {\r
+        if ($this->result) {\r
+            return $this->result->numRows();\r
+        }\r
+        return false;\r
+    }\r
+    // }}}\r
+\r
+    // {{{ rewind()\r
+\r
+    /**\r
+     * Seek to the first row in a result set\r
+     *\r
+     * @return void\r
+     * @access public\r
+     */\r
+    public function rewind()\r
+    {\r
+        $this->seek(0);\r
+    }\r
+    // }}}\r
+}\r
+\r
 ?>
\ No newline at end of file
index ae67224020e84d944a450b5e1c6be5010d1c3893..f7df13dc4782c31c8e92d0bfca15e7b1775efcd7 100644 (file)
-<?php
-// +----------------------------------------------------------------------+
-// | PHP version 5                                                        |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |
-// | Stig. S. Bakken, Lukas Smith                                         |
-// | All rights reserved.                                                 |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
-// | API as well as database abstraction for PHP applications.            |
-// | This LICENSE is in the BSD license style.                            |
-// |                                                                      |
-// | Redistribution and use in source and binary forms, with or without   |
-// | modification, are permitted provided that the following conditions   |
-// | are met:                                                             |
-// |                                                                      |
-// | Redistributions of source code must retain the above copyright       |
-// | notice, this list of conditions and the following disclaimer.        |
-// |                                                                      |
-// | Redistributions in binary form must reproduce the above copyright    |
-// | notice, this list of conditions and the following disclaimer in the  |
-// | documentation and/or other materials provided with the distribution. |
-// |                                                                      |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission.                                                  |
-// |                                                                      |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
-// | POSSIBILITY OF SUCH DAMAGE.                                          |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org>                           |
-// +----------------------------------------------------------------------+
-//
-// $Id: LOB.php,v 1.34 2006/10/25 11:52:21 lsmith Exp $
-
-/**
- * @package  MDB2
- * @category Database
- * @author   Lukas Smith <smith@pooteeweet.org>
- */
-
-require_once('MDB2.php');
-
-/**
- * MDB2_LOB: user land stream wrapper implementation for LOB support
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_LOB
-{
-    /**
-     * contains the key to the global MDB2 instance array of the associated
-     * MDB2 instance
-     *
-     * @var integer
-     * @access protected
-     */
-    var $db_index;
-
-    /**
-     * contains the key to the global MDB2_LOB instance array of the associated
-     * MDB2_LOB instance
-     *
-     * @var integer
-     * @access protected
-     */
-    var $lob_index;
-
-    // {{{ stream_open()
-
-    /**
-     * open stream
-     *
-     * @param string specifies the URL that was passed to fopen()
-     * @param string the mode used to open the file
-     * @param int holds additional flags set by the streams API
-     * @param string not used
-     *
-     * @return bool
-     * @access public
-     */
-    function stream_open($path, $mode, $options, &$opened_path)
-    {
-        if (!preg_match('/^rb?\+?$/', $mode)) {
-            return false;
-        }
-        $url = parse_url($path);
-        if (empty($url['host'])) {
-            return false;
-        }
-        $this->db_index = (int)$url['host'];
-        if (!isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
-            return false;
-        }
-        $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
-        $this->lob_index = (int)$url['user'];
-        if (!isset($db->datatype->lobs[$this->lob_index])) {
-            return false;
-        }
-        return true;
-    }
-    // }}}
-
-    // {{{ stream_read()
-
-    /**
-     * read stream
-     *
-     * @param int number of bytes to read
-     *
-     * @return string
-     * @access public
-     */
-    function stream_read($count)
-    {
-        if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
-            $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
-            $db->datatype->_retrieveLOB($db->datatype->lobs[$this->lob_index]);
-
-            $data = $db->datatype->_readLOB($db->datatype->lobs[$this->lob_index], $count);
-            $length = strlen($data);
-            if ($length == 0) {
-                $db->datatype->lobs[$this->lob_index]['endOfLOB'] = true;
-            }
-            $db->datatype->lobs[$this->lob_index]['position'] += $length;
-            return $data;
-        }
-    }
-    // }}}
-
-    // {{{ stream_write()
-
-    /**
-     * write stream, note implemented
-     *
-     * @param string data
-     *
-     * @return int
-     * @access public
-     */
-    function stream_write($data)
-    {
-        return 0;
-    }
-    // }}}
-
-    // {{{ stream_tell()
-
-    /**
-     * return the current position
-     *
-     * @return int current position
-     * @access public
-     */
-    function stream_tell()
-    {
-        if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
-            $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
-            return $db->datatype->lobs[$this->lob_index]['position'];
-        }
-    }
-    // }}}
-
-    // {{{ stream_eof()
-
-    /**
-     * Check if stream reaches EOF
-     *
-     * @return bool
-     * @access public
-     */
-    function stream_eof()
-    {
-        if (!isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
-            return true;
-        }
-
-        $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
-        $result = $db->datatype->_endOfLOB($db->datatype->lobs[$this->lob_index]);
-        if (version_compare(phpversion(), "5.0", ">=")
-            && version_compare(phpversion(), "5.1", "<")
-        ) {
-            return !$result;
-        }
-        return $result;
-    }
-    // }}}
-
-    // {{{ stream_seek()
-
-    /**
-     * Seek stream, not implemented
-     *
-     * @param int offset
-     * @param int whence
-     *
-     * @return bool
-     * @access public
-     */
-    function stream_seek($offset, $whence)
-    {
-        return false;
-    }
-    // }}}
-
-    // {{{ stream_stat()
-
-    /**
-     * return information about stream
-     *
-     * @access public
-     */
-    function stream_stat()
-    {
-        if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
-            $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
-            return array(
-              'db_index' => $this->db_index,
-              'lob_index' => $this->lob_index,
-            );
-        }
-    }
-    // }}}
-
-    // {{{ stream_close()
-
-    /**
-     * close stream
-     *
-     * @access public
-     */
-    function stream_close()
-    {
-        if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
-            $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
-            if (isset($db->datatype->lobs[$this->lob_index])) {
-                $db->datatype->_destroyLOB($db->datatype->lobs[$this->lob_index]);
-                unset($db->datatype->lobs[$this->lob_index]);
-            }
-        }
-    }
-    // }}}
-}
-
-// register streams wrapper
-if (!stream_wrapper_register("MDB2LOB", "MDB2_LOB")) {
-    MDB2::raiseError();
-    return false;
-}
-
-?>
+<?php\r
+// +----------------------------------------------------------------------+\r
+// | PHP version 5                                                        |\r
+// +----------------------------------------------------------------------+\r
+// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |\r
+// | Stig. S. Bakken, Lukas Smith                                         |\r
+// | All rights reserved.                                                 |\r
+// +----------------------------------------------------------------------+\r
+// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |\r
+// | API as well as database abstraction for PHP applications.            |\r
+// | This LICENSE is in the BSD license style.                            |\r
+// |                                                                      |\r
+// | Redistribution and use in source and binary forms, with or without   |\r
+// | modification, are permitted provided that the following conditions   |\r
+// | are met:                                                             |\r
+// |                                                                      |\r
+// | Redistributions of source code must retain the above copyright       |\r
+// | notice, this list of conditions and the following disclaimer.        |\r
+// |                                                                      |\r
+// | Redistributions in binary form must reproduce the above copyright    |\r
+// | notice, this list of conditions and the following disclaimer in the  |\r
+// | documentation and/or other materials provided with the distribution. |\r
+// |                                                                      |\r
+// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |\r
+// | Lukas Smith nor the names of his contributors may be used to endorse |\r
+// | or promote products derived from this software without specific prior|\r
+// | written permission.                                                  |\r
+// |                                                                      |\r
+// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |\r
+// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |\r
+// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |\r
+// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |\r
+// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |\r
+// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |\r
+// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|\r
+// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |\r
+// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |\r
+// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|\r
+// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |\r
+// | POSSIBILITY OF SUCH DAMAGE.                                          |\r
+// +----------------------------------------------------------------------+\r
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |\r
+// +----------------------------------------------------------------------+\r
+//\r
+// $Id: LOB.php 222350 2006-10-25 11:52:21Z lsmith $\r
+\r
+/**\r
+ * @package  MDB2\r
+ * @category Database\r
+ * @author   Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+\r
+require_once 'MDB2.php';\r
+\r
+/**\r
+ * MDB2_LOB: user land stream wrapper implementation for LOB support\r
+ *\r
+ * @package MDB2\r
+ * @category Database\r
+ * @author Lukas Smith <smith@pooteeweet.org>\r
+ */\r
+class MDB2_LOB\r
+{\r
+    /**\r
+     * contains the key to the global MDB2 instance array of the associated\r
+     * MDB2 instance\r
+     *\r
+     * @var integer\r
+     * @access protected\r
+     */\r
+    var $db_index;\r
+\r
+    /**\r
+     * contains the key to the global MDB2_LOB instance array of the associated\r
+     * MDB2_LOB instance\r
+     *\r
+     * @var integer\r
+     * @access protected\r
+     */\r
+    var $lob_index;\r
+\r
+    // {{{ stream_open()\r
+\r
+    /**\r
+     * open stream\r
+     *\r
+     * @param string specifies the URL that was passed to fopen()\r
+     * @param string the mode used to open the file\r
+     * @param int holds additional flags set by the streams API\r
+     * @param string not used\r
+     *\r
+     * @return bool\r
+     * @access public\r
+     */\r
+    function stream_open($path, $mode, $options, &$opened_path)\r
+    {\r
+        if (!preg_match('/^rb?\+?$/', $mode)) {\r
+            return false;\r
+        }\r
+        $url = parse_url($path);\r
+        if (empty($url['host'])) {\r
+            return false;\r
+        }\r
+        $this->db_index = (int)$url['host'];\r
+        if (!isset($GLOBALS['_MDB2_databases'][$this->db_index])) {\r
+            return false;\r
+        }\r
+        $db =& $GLOBALS['_MDB2_databases'][$this->db_index];\r
+        $this->lob_index = (int)$url['user'];\r
+        if (!isset($db->datatype->lobs[$this->lob_index])) {\r
+            return false;\r
+        }\r
+        return true;\r
+    }\r
+    // }}}\r
+\r
+    // {{{ stream_read()\r
+\r
+    /**\r
+     * read stream\r
+     *\r
+     * @param int number of bytes to read\r
+     *\r
+     * @return string\r
+     * @access public\r
+     */\r
+    function stream_read($count)\r
+    {\r
+        if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {\r
+            $db =& $GLOBALS['_MDB2_databases'][$this->db_index];\r
+            $db->datatype->_retrieveLOB($db->datatype->lobs[$this->lob_index]);\r
+\r
+            $data = $db->datatype->_readLOB($db->datatype->lobs[$this->lob_index], $count);\r
+            $length = strlen($data);\r
+            if ($length == 0) {\r
+                $db->datatype->lobs[$this->lob_index]['endOfLOB'] = true;\r
+            }\r
+            $db->datatype->lobs[$this->lob_index]['position'] += $length;\r
+            return $data;\r
+        }\r
+    }\r
+    // }}}\r
+\r
+    // {{{ stream_write()\r
+\r
+    /**\r
+     * write stream, note implemented\r
+     *\r
+     * @param string data\r
+     *\r
+     * @return int\r
+     * @access public\r
+     */\r
+    function stream_write($data)\r
+    {\r
+        return 0;\r
+    }\r
+    // }}}\r
+\r
+    // {{{ stream_tell()\r
+\r
+    /**\r
+     * return the current position\r
+     *\r
+     * @return int current position\r
+     * @access public\r
+     */\r
+    function stream_tell()\r
+    {\r
+        if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {\r
+            $db =& $GLOBALS['_MDB2_databases'][$this->db_index];\r
+            return $db->datatype->lobs[$this->lob_index]['position'];\r
+        }\r
+    }\r
+    // }}}\r
+\r
+    // {{{ stream_eof()\r
+\r
+    /**\r
+     * Check if stream reaches EOF\r
+     *\r
+     * @return bool\r
+     * @access public\r
+     */\r
+    function stream_eof()\r
+    {\r
+        if (!isset($GLOBALS['_MDB2_databases'][$this->db_index])) {\r
+            return true;\r
+        }\r
+\r
+        $db =& $GLOBALS['_MDB2_databases'][$this->db_index];\r
+        $result = $db->datatype->_endOfLOB($db->datatype->lobs[$this->lob_index]);\r
+        if (version_compare(phpversion(), "5.0", ">=")\r
+            && version_compare(phpversion(), "5.1", "<")\r
+        ) {\r
+            return !$result;\r
+        }\r
+        return $result;\r
+    }\r
+    // }}}\r
+\r
+    // {{{ stream_seek()\r
+\r
+    /**\r
+     * Seek stream, not implemented\r
+     *\r
+     * @param int offset\r
+     * @param int whence\r
+     *\r
+     * @return bool\r
+     * @access public\r
+     */\r
+    function stream_seek($offset, $whence)\r
+    {\r
+        return false;\r
+    }\r
+    // }}}\r
+\r
+    // {{{ stream_stat()\r
+\r
+    /**\r
+     * return information about stream\r
+     *\r
+     * @access public\r
+     */\r
+    function stream_stat()\r
+    {\r
+        if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {\r
+            $db =& $GLOBALS['_MDB2_databases'][$this->db_index];\r
+            return array(\r
+              'db_index' => $this->db_index,\r
+              'lob_index' => $this->lob_index,\r
+            );\r
+        }\r
+    }\r
+    // }}}\r
+\r
+    // {{{ stream_close()\r
+\r
+    /**\r
+     * close stream\r
+     *\r
+     * @access public\r
+     */\r
+    function stream_close()\r
+    {\r
+        if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {\r
+            $db =& $GLOBALS['_MDB2_databases'][$this->db_index];\r
+            if (isset($db->datatype->lobs[$this->lob_index])) {\r
+                $db->datatype->_destroyLOB($db->datatype->lobs[$this->lob_index]);\r
+                unset($db->datatype->lobs[$this->lob_index]);\r
+            }\r
+        }\r
+    }\r
+    // }}}\r
+}\r
+\r
+// register streams wrapper\r
+if (!stream_wrapper_register("MDB2LOB", "MDB2_LOB")) {\r
+    MDB2::raiseError();\r
+    return false;\r
+}\r
+\r
+?>\r
index 25818460a629b6a37f9d5c884429c2bbbb08d34b..037397018135680fafb6888dc73984f9e0a78677 100644 (file)
@@ -51,7 +51,7 @@
  * @link     http://pear.php.net/packages/MDB2_Schema
  */
 
-// require_once('MDB2.php');
+require_once 'MDB2.php';
 
 define('MDB2_SCHEMA_DUMP_ALL',       0);
 define('MDB2_SCHEMA_DUMP_STRUCTURE', 1);
@@ -237,9 +237,10 @@ class MDB2_Schema extends PEAR
      * @access public
      * @see     MDB2::parseDSN
      */
-    static function factory(&$db, $options = array())
+    function &factory(&$db, $options = array())
     {
-        $obj =new MDB2_Schema();
+        $obj =& new MDB2_Schema();
+
         $result = $obj->connect($db, $options);
         if (PEAR::isError($result)) {
             return $result;
@@ -280,14 +281,16 @@ class MDB2_Schema extends PEAR
                 }
             }
         }
+
         $this->disconnect();
         if (!MDB2::isConnection($db)) {
-            $db =MDB2::factory($db, $db_options);
+            $db =MDB2::factory($db, $db_options);
         }
 
         if (PEAR::isError($db)) {
             return $db;
         }
+
         $this->db =& $db;
         $this->db->loadModule('Datatype');
         $this->db->loadModule('Manager');
@@ -377,7 +380,7 @@ class MDB2_Schema extends PEAR
         $dtd_file = $this->options['dtd_file'];
         if ($dtd_file) {
             include_once 'XML/DTD/XmlValidator.php';
-            $dtd =new XML_DTD_XmlValidator;
+            $dtd =new XML_DTD_XmlValidator;
             if (!$dtd->isValid($dtd_file, $input_file)) {
                 return $this->raiseError(MDB2_SCHEMA_ERROR_PARSE, null, null, $dtd->getMessage());
             }
@@ -390,7 +393,7 @@ class MDB2_Schema extends PEAR
             return $result;
         }
 
-        $parser =new $class_name($variables, $fail_on_invalid_names, $structure, $this->options['valid_types'], $this->options['force_defaults']);
+        $parser =new $class_name($variables, $fail_on_invalid_names, $structure, $this->options['valid_types'], $this->options['force_defaults']);
         $result = $parser->setInputFile($input_file);
         if (PEAR::isError($result)) {
             return $result;
@@ -425,6 +428,7 @@ class MDB2_Schema extends PEAR
             return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
                 'it was not specified a valid database name');
         }
+
         $class_name = $this->options['validate'];
 
         $result = MDB2::loadClass($class_name, $this->db->getOption('debug'));
@@ -432,7 +436,7 @@ class MDB2_Schema extends PEAR
             return $result;
         }
 
-        $val =new $class_name($this->options['fail_on_invalid_names'], $this->options['valid_types'], $this->options['force_defaults']);
+        $val =new $class_name($this->options['fail_on_invalid_names'], $this->options['valid_types'], $this->options['force_defaults']);
 
         $database_definition = array(
             'name' => $database,
@@ -1338,15 +1342,15 @@ class MDB2_Schema extends PEAR
 
             if ($dbExists) {
                 $this->db->debug('Database already exists: ' . $db_name, __FUNCTION__);
-//                 if (!empty($dbOptions)) {
-//                     $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NO_PERMISSION);
-//                     $this->db->expectError($errorcodes);
-//                     $result = $this->db->manager->alterDatabase($db_name, $dbOptions);
-//                     $this->db->popExpect();
-//                     if (PEAR::isError($result) && !MDB2::isError($result, $errorcodes)) {
-//                         return $result;
-//                     }
-//                 }
+                if (!empty($dbOptions)) {
+                    $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NO_PERMISSION);
+                    $this->db->expectError($errorcodes);
+                    $result = $this->db->manager->alterDatabase($db_name, $dbOptions);
+                    $this->db->popExpect();
+                    if (PEAR::isError($result) && !MDB2::isError($result, $errorcodes)) {
+                        return $result;
+                    }
+                }
                 $create = false;
             } else {
                 $this->db->expectError(MDB2_ERROR_UNSUPPORTED);
@@ -2444,7 +2448,7 @@ class MDB2_Schema extends PEAR
             }
         }
 
-        $writer = new $class_name($this->options['valid_types']);
+        $writer =& new $class_name($this->options['valid_types']);
         return $writer->dumpDatabase($database_definition, $arguments, $dump);
     }
 
@@ -2692,9 +2696,9 @@ class MDB2_Schema extends PEAR
      * @access  public
      * @see PEAR_Error
      */
-    function raiseError($code = null, $mode = null, $options = null, $userinfo = null,$a=null,$b=null,$c=null)
+    function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
     {
-        $err =PEAR::raiseError(null, $code, $mode, $options,
+        $err =PEAR::raiseError(null, $code, $mode, $options,
                                 $userinfo, 'MDB2_Schema_Error', true);
         return $err;
     }
@@ -2713,7 +2717,7 @@ class MDB2_Schema extends PEAR
      * @return  bool  true if parameter is an error
      * @access  public
      */
-    static function isError($data, $code = null)
+    function isError($data, $code = null)
     {
         if (is_a($data, 'MDB2_Schema_Error')) {
             if (is_null($code)) {
index b740ef55fa85d17fc82dfb1fb08ecccdc493e02b..9e8e74b6317bd6968f077a282a6e4f937f7fb674 100644 (file)
@@ -54,8 +54,8 @@
  */
 
 
-require_once('XML/Parser.php');
-require_once('MDB2/Schema/Validate.php');
+require_once 'XML/Parser.php';
+require_once 'MDB2/Schema/Validate.php';
 
 /**
  * Parses an XML schema file
@@ -120,11 +120,18 @@ class MDB2_Schema_Parser extends XML_Parser
     {
         // force ISO-8859-1 due to different defaults for PHP4 and PHP5
         // todo: this probably needs to be investigated some more andcleaned up
-        parent::__construct('ISO-8859-1');
+        parent::XML_Parser('ISO-8859-1');
 
         $this->variables = $variables;
         $this->structure = $structure;
-        $this->val       =new MDB2_Schema_Validate($fail_on_invalid_names, $valid_types, $force_defaults);
+        $this->val       =& new MDB2_Schema_Validate($fail_on_invalid_names, $valid_types, $force_defaults);
+    }
+
+    function MDB2_Schema_Parser($variables, $fail_on_invalid_names = true,
+                                $structure = false, $valid_types = array(),
+                                $force_defaults = true)
+    {
+        $this->__construct($variables, $fail_on_invalid_names, $structure, $valid_types, $force_defaults);
     }
 
     function startHandler($xp, $element, $attribs)
@@ -496,7 +503,7 @@ class MDB2_Schema_Parser extends XML_Parser
         $this->element = implode('-', $this->elements);
     }
 
-    function raiseError($msg = null, $xmlecode = 0, $xp = null, $ecode = MDB2_SCHEMA_ERROR_PARSE,$a=null,$b=null,$c=null)
+    function &raiseError($msg = null, $xmlecode = 0, $xp = null, $ecode = MDB2_SCHEMA_ERROR_PARSE)
     {
         if (is_null($this->error)) {
             $error = '';
index 217cf51b9592545c892d16e2108912f7e8606750..21be024ce9fbbc883ea200aecbad1f7c038abcf7 100644 (file)
@@ -91,6 +91,11 @@ class MDB2_Schema_Validate
         $this->force_defaults = $force_defaults;
     }
 
+    function MDB2_Schema_Validate($fail_on_invalid_names = true, $valid_types = array(), $force_defaults = true)
+    {
+        $this->__construct($fail_on_invalid_names, $valid_types, $force_defaults);
+    }
+
     // }}}
     // {{{ raiseError()
 
index 38b4f8fe8a668055ecf77beb1e09c2d226b7dd2d..a38a161aef9dae100925b8cdcafde59883254aaa 100644 (file)
@@ -1,42 +1,58 @@
 <?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4                                                        |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group                                |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license,       |
-// | that is bundled with this package in the file LICENSE, and is        |
-// | available at through the world-wide-web at                           |
-// | http://www.php.net/license/3_0.txt.                                  |
-// | If you did not receive a copy of the PHP license and are unable to   |
-// | obtain it through the world-wide-web, please send a note to          |
-// | license@php.net so we can mail you a copy immediately.               |
-// +----------------------------------------------------------------------+
-// | Author: Stig Bakken <ssb@fast.no>                                    |
-// |         Tomas V.V.Cox <cox@idecnet.com>                              |
-// |         Stephan Schmidt <schst@php-tools.net>                        |
-// +----------------------------------------------------------------------+
-//
-// $Id: Parser.php,v 1.25 2005/03/25 17:13:10 schst Exp $
+
+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
 
 /**
- * XML Parser class.
+ * XML_Parser
  *
- * This is an XML parser based on PHP's "xml" extension,
- * based on the bundled expat library.
+ * XML Parser package
+ *
+ * PHP versions 4 and 5
+ *
+ * LICENSE:
  *
- * @category XML
- * @package XML_Parser
- * @author  Stig Bakken <ssb@fast.no>
- * @author  Tomas V.V.Cox <cox@idecnet.com>
- * @author  Stephan Schmidt <schst@php-tools.net>
+ * Copyright (c) 2002-2008 The PHP Group
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *    * Redistributions of source code must retain the above copyright
+ *      notice, this list of conditions and the following disclaimer.
+ *    * Redistributions in binary form must reproduce the above copyright
+ *      notice, this list of conditions and the following disclaimer in the
+ *      documentation and/or other materials provided with the distribution.
+ *    * The name of the author may not be used to endorse or promote products
+ *      derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @category  XML
+ * @package   XML_Parser
+ * @author    Stig Bakken <ssb@fast.no>
+ * @author    Tomas V.V.Cox <cox@idecnet.com>
+ * @author    Stephan Schmidt <schst@php.net>
+ * @copyright 2002-2008 The PHP Group
+ * @license   http://opensource.org/licenses/bsd-license New BSD License
+ * @version   CVS: $Id: Parser.php 302733 2010-08-24 01:09:09Z clockwerx $
+ * @link      http://pear.php.net/package/XML_Parser
  */
 
 /**
  * uses PEAR's error handling
  */
-require_once('PEAR.php');
+require_once 'PEAR.php';
 
 /**
  * resource could not be created
@@ -79,25 +95,29 @@ define('XML_PARSER_ERROR_REMOTE', 205);
  * - From revision 1.17, the function names used by the 'func' mode
  *   are in the format "xmltag_$elem", for example: use "xmltag_name"
  *   to handle the <name></name> tags of your xml file.
- *
- * @category XML
- * @package XML_Parser
- * @author  Stig Bakken <ssb@fast.no>
- * @author  Tomas V.V.Cox <cox@idecnet.com>
- * @author  Stephan Schmidt <schst@php-tools.net>
- * @todo    create XML_Parser_Namespace to parse documents with namespaces
- * @todo    create XML_Parser_Pull
- * @todo    Tests that need to be made:
- *          - mixing character encodings
- *          - a test using all expat handlers
- *          - options (folding, output charset)
  *          - different parsing modes
+ *
+ * @category  XML
+ * @package   XML_Parser
+ * @author    Stig Bakken <ssb@fast.no>
+ * @author    Tomas V.V.Cox <cox@idecnet.com>
+ * @author    Stephan Schmidt <schst@php.net>
+ * @copyright 2002-2008 The PHP Group
+ * @license   http://opensource.org/licenses/bsd-license New BSD License
+ * @version   Release: @package_version@
+ * @link      http://pear.php.net/package/XML_Parser
+ * @todo      create XML_Parser_Namespace to parse documents with namespaces
+ * @todo      create XML_Parser_Pull
+ * @todo      Tests that need to be made:
+ *            - mixing character encodings
+ *            - a test using all expat handlers
+ *            - options (folding, output charset)
  */
 class XML_Parser extends PEAR
 {
     // {{{ properties
 
-   /**
+    /**
      * XML parser handle
      *
      * @var  resource
@@ -164,7 +184,35 @@ class XML_Parser extends PEAR
      */
     var $_handlerObj;
 
+    /**
+     * valid encodings
+     *
+     * @var array
+     */
+    var $_validEncodings = array('ISO-8859-1', 'UTF-8', 'US-ASCII');
+
+    // }}}
+    // {{{ php4 constructor
+
+    /**
+     * Creates an XML parser.
+     *
+     * This is needed for PHP4 compatibility, it will
+     * call the constructor, when a new instance is created.
+     *
+     * @param string $srcenc source charset encoding, use NULL (default) to use
+     *                       whatever the document specifies
+     * @param string $mode   how this parser object should work, "event" for
+     *                       startelement/endelement-type events, "func"
+     *                       to have it call functions named after elements
+     * @param string $tgtenc a valid target encoding
+     */
+    function XML_Parser($srcenc = null, $mode = 'event', $tgtenc = null)
+    {
+        XML_Parser::__construct($srcenc, $mode, $tgtenc);
+    }
     // }}}
+    // {{{ php5 constructor
 
     /**
      * PHP5 constructor
@@ -174,7 +222,7 @@ class XML_Parser extends PEAR
      * @param string $mode   how this parser object should work, "event" for
      *                       startelement/endelement-type events, "func"
      *                       to have it call functions named after elements
-     * @param string $tgenc  a valid target encoding
+     * @param string $tgtenc a valid target encoding
      */
     function __construct($srcenc = null, $mode = 'event', $tgtenc = null)
     {
@@ -199,14 +247,16 @@ class XML_Parser extends PEAR
      * This method is only needed, when switching to a new
      * mode at a later point.
      *
-     * @access  public
-     * @param   string          mode, either 'func' or 'event'
-     * @return  boolean|object  true on success, PEAR_Error otherwise   
+     * @param string $mode mode, either 'func' or 'event'
+     *
+     * @return boolean|object  true on success, PEAR_Error otherwise
+     * @access public
      */
     function setMode($mode)
     {
         if ($mode != 'func' && $mode != 'event') {
-            $this->raiseError('Unsupported mode given', XML_PARSER_ERROR_UNSUPPORTED_MODE);
+            $this->raiseError('Unsupported mode given', 
+                XML_PARSER_ERROR_UNSUPPORTED_MODE);
         }
 
         $this->mode = $mode;
@@ -223,10 +273,11 @@ class XML_Parser extends PEAR
      * If no object will be set, XML_Parser assumes that you
      * extend this class and handle the events in $this.
      *
-     * @access  public
-     * @param   object      object to handle the events
-     * @return  boolean     will always return true
-     * @since   v1.2.0beta3
+     * @param object &$obj object to handle the events
+     *
+     * @return boolean will always return true
+     * @access public
+     * @since v1.2.0beta3
      */
     function setHandlerObj(&$obj)
     {
@@ -237,7 +288,8 @@ class XML_Parser extends PEAR
     /**
      * Init the element handlers
      *
-     * @access  private
+     * @return mixed
+     * @access private
      */
     function _initHandlers()
     {
@@ -250,21 +302,22 @@ class XML_Parser extends PEAR
         }
         switch ($this->mode) {
 
-            case 'func':
-                xml_set_object($this->parser, $this->_handlerObj);
-                xml_set_element_handler($this->parser, array(&$this, 'funcStartHandler'), array(&$this, 'funcEndHandler'));
-                break;
-
-            case 'event':
-                xml_set_object($this->parser, $this->_handlerObj);
-                xml_set_element_handler($this->parser, 'startHandler', 'endHandler');
-                break;
-            default:
-                return $this->raiseError('Unsupported mode given', XML_PARSER_ERROR_UNSUPPORTED_MODE);
-                break;
+        case 'func':
+            xml_set_object($this->parser, $this->_handlerObj);
+            xml_set_element_handler($this->parser, 
+                array(&$this, 'funcStartHandler'), array(&$this, 'funcEndHandler'));
+            break;
+
+        case 'event':
+            xml_set_object($this->parser, $this->_handlerObj);
+            xml_set_element_handler($this->parser, 'startHandler', 'endHandler');
+            break;
+        default:
+            return $this->raiseError('Unsupported mode given', 
+                XML_PARSER_ERROR_UNSUPPORTED_MODE);
+            break;
         }
 
-
         /**
          * set additional handlers for character data, entities, etc.
          */
@@ -273,7 +326,7 @@ class XML_Parser extends PEAR
                 $xml_func = 'xml_set_' . $xml_func;
                 $xml_func($this->parser, $method);
             }
-               }
+        }
     }
 
     // {{{ _create()
@@ -287,9 +340,10 @@ class XML_Parser extends PEAR
      * Furthermore it allows us returning an error
      * if something fails.
      *
-     * @access   private
-     * @return   boolean|object     true on success, PEAR_Error otherwise
+     * NOTE: uses '@' error suppresion in this method
      *
+     * @return bool|PEAR_Error true on success, PEAR_Error otherwise
+     * @access private
      * @see xml_parser_create
      */
     function _create()
@@ -301,21 +355,27 @@ class XML_Parser extends PEAR
         }
         if (is_resource($xp)) {
             if ($this->tgtenc !== null) {
-                if (!@xml_parser_set_option($xp, XML_OPTION_TARGET_ENCODING,
-                                            $this->tgtenc)) {
-                    return $this->raiseError('invalid target encoding', XML_PARSER_ERROR_INVALID_ENCODING);
+                if (!@xml_parser_set_option($xp, XML_OPTION_TARGET_ENCODING, 
+                    $this->tgtenc)
+                ) {
+                    return $this->raiseError('invalid target encoding', 
+                        XML_PARSER_ERROR_INVALID_ENCODING);
                 }
             }
             $this->parser = $xp;
-            $result = $this->_initHandlers($this->mode);
+            $result       = $this->_initHandlers($this->mode);
             if ($this->isError($result)) {
                 return $result;
             }
             xml_parser_set_option($xp, XML_OPTION_CASE_FOLDING, $this->folding);
-
             return true;
         }
-        return $this->raiseError('Unable to create XML parser resource.', XML_PARSER_ERROR_NO_RESOURCE);
+        if (!in_array(strtoupper($this->srcenc), $this->_validEncodings)) {
+            return $this->raiseError('invalid source encoding', 
+                XML_PARSER_ERROR_INVALID_ENCODING);
+        }
+        return $this->raiseError('Unable to create XML parser resource.', 
+            XML_PARSER_ERROR_NO_RESOURCE);
     }
 
     // }}}
@@ -333,7 +393,7 @@ class XML_Parser extends PEAR
     function reset()
     {
         $result = $this->_create();
-        if ($this->isError( $result )) {
+        if ($this->isError($result)) {
             return $result;
         }
         return true;
@@ -345,47 +405,53 @@ class XML_Parser extends PEAR
     /**
      * Sets the input xml file to be parsed
      *
-     * @param    string      Filename (full path)
-     * @return   resource    fopen handle of the given file
-     * @throws   XML_Parser_Error
-     * @see      setInput(), setInputString(), parse()
-     * @access   public
+     * @param string $file Filename (full path)
+     *
+     * @return resource fopen handle of the given file
+     * @access public
+     * @throws XML_Parser_Error
+     * @see setInput(), setInputString(), parse()
      */
     function setInputFile($file)
     {
         /**
          * check, if file is a remote file
          */
-        if (preg_match('[^(http|ftp)://]', substr($file, 0, 10))) {
+        if (preg_match('/^(http|ftp):\/\//i', substr($file, 0, 10))) {
             if (!ini_get('allow_url_fopen')) {
-               return $this->raiseError('Remote files cannot be parsed, as safe mode is enabled.', XML_PARSER_ERROR_REMOTE);
+                return $this->
+                raiseError('Remote files cannot be parsed, as safe mode is enabled.',
+                XML_PARSER_ERROR_REMOTE);
             }
         }
-        $fp = fopen($file, 'rb');
+
+        $fp = @fopen($file, 'rb');
         if (is_resource($fp)) {
             $this->fp = $fp;
             return $fp;
         }
-        return $this->raiseError('File could not be opened.', XML_PARSER_ERROR_FILE_NOT_READABLE);
+        return $this->raiseError('File could not be opened.', 
+            XML_PARSER_ERROR_FILE_NOT_READABLE);
     }
 
     // }}}
     // {{{ setInputString()
-    
+
     /**
      * XML_Parser::setInputString()
-     * 
+     *
      * Sets the xml input from a string
-     * 
+     *
      * @param string $data a string containing the XML document
+     *
      * @return null
-     **/
+     */
     function setInputString($data)
     {
         $this->fp = $data;
         return null;
     }
-    
+
     // }}}
     // {{{ setInput()
 
@@ -393,35 +459,35 @@ class XML_Parser extends PEAR
      * Sets the file handle to use with parse().
      *
      * You should use setInputFile() or setInputString() if you
-     * pass a string 
+     * pass a string
      *
-     * @param    mixed  $fp  Can be either a resource returned from fopen(),
-     *                       a URL, a local filename or a string.
-     * @access   public
-     * @see      parse()
-     * @uses     setInputString(), setInputFile()
+     * @param mixed $fp Can be either a resource returned from fopen(),
+     *                  a URL, a local filename or a string.
+     *
+     * @return mixed
+     * @access public
+     * @see parse()
+     * @uses setInputString(), setInputFile()
      */
     function setInput($fp)
     {
         if (is_resource($fp)) {
             $this->fp = $fp;
             return true;
-        }
-        // see if it's an absolute URL (has a scheme at the beginning)
-        elseif (eregi('^[a-z]+://', substr($fp, 0, 10))) {
+        } elseif (preg_match('/^[a-z]+:\/\//i', substr($fp, 0, 10))) {
+            // see if it's an absolute URL (has a scheme at the beginning)
             return $this->setInputFile($fp);
-        }
-        // see if it's a local file
-        elseif (file_exists($fp)) {
+        } elseif (file_exists($fp)) {
+            // see if it's a local file
             return $this->setInputFile($fp);
-        }
-        // it must be a string
-        else {
+        } else {
+            // it must be a string
             $this->fp = $fp;
             return true;
         }
 
-        return $this->raiseError('Illegal input format', XML_PARSER_ERROR_INVALID_INPUT);
+        return $this->raiseError('Illegal input format', 
+            XML_PARSER_ERROR_INVALID_INPUT);
     }
 
     // }}}
@@ -430,8 +496,8 @@ class XML_Parser extends PEAR
     /**
      * Central parsing function.
      *
-     * @return   true|object PEAR error     returns true on success, or a PEAR_Error otherwise
-     * @access   public
+     * @return bool|PEAR_Error returns true on success, or a PEAR_Error otherwise
+     * @access public
      */
     function parse()
     {
@@ -444,7 +510,7 @@ class XML_Parser extends PEAR
         }
         // if $this->fp was fopened previously
         if (is_resource($this->fp)) {
-        
+
             while ($data = fread($this->fp, 4096)) {
                 if (!$this->_parseString($data, feof($this->fp))) {
                     $error = &$this->raiseError();
@@ -452,8 +518,8 @@ class XML_Parser extends PEAR
                     return $error;
                 }
             }
-        // otherwise, $this->fp must be a string
         } else {
+            // otherwise, $this->fp must be a string
             if (!$this->_parseString($this->fp, true)) {
                 $error = &$this->raiseError();
                 $this->free();
@@ -467,9 +533,10 @@ class XML_Parser extends PEAR
 
     /**
      * XML_Parser::_parseString()
-     * 
-     * @param string $data
-     * @param boolean $eof
+     *
+     * @param string $data data
+     * @param bool   $eof  end-of-file flag
+     *
      * @return bool
      * @access private
      * @see parseString()
@@ -478,31 +545,33 @@ class XML_Parser extends PEAR
     {
         return xml_parse($this->parser, $data, $eof);
     }
-    
+
     // }}}
     // {{{ parseString()
 
     /**
      * XML_Parser::parseString()
-     * 
+     *
      * Parses a string.
      *
-     * @param    string  $data XML data
-     * @param    boolean $eof  If set and TRUE, data is the last piece of data sent in this parser
-     * @throws   XML_Parser_Error
-     * @return   Pear Error|true   true on success or a PEAR Error
-     * @see      _parseString()
+     * @param string  $data XML data
+     * @param boolean $eof  If set and TRUE, data is the last piece 
+     *                      of data sent in this parser
+     *
+     * @return bool|PEAR_Error true on success or a PEAR Error
+     * @throws XML_Parser_Error
+     * @see _parseString()
      */
     function parseString($data, $eof = false)
     {
         if (!isset($this->parser) || !is_resource($this->parser)) {
             $this->reset();
         }
-        
+
         if (!$this->_parseString($data, $eof)) {
-           $error = &$this->raiseError();
-           $this->free();
-           return $error;
+            $error = &$this->raiseError();
+            $this->free();
+            return $error;
         }
 
         if ($eof === true) {
@@ -510,12 +579,12 @@ class XML_Parser extends PEAR
         }
         return true;
     }
-    
+
     /**
      * XML_Parser::free()
-     * 
+     *
      * Free the internal resources associated with the parser
-     * 
+     *
      * @return null
      **/
     function free()
@@ -530,52 +599,63 @@ class XML_Parser extends PEAR
         unset($this->fp);
         return null;
     }
-    
+
     /**
      * XML_Parser::raiseError()
-     * 
+     *
      * Throws a XML_Parser_Error
-     * 
+     *
      * @param string  $msg   the error message
      * @param integer $ecode the error message code
-     * @return XML_Parser_Error 
+     *
+     * @return XML_Parser_Error reference to the error object
      **/
-    function raiseError($msg = null, $ecode = 0,$mode = null,
-                         $options = null,
-                         $userinfo = null,
-                         $error_class = null,
-                         $skipmsg = false)
+    function &raiseError($msg = null, $ecode = 0)
     {
         $msg = !is_null($msg) ? $msg : $this->parser;
-        $err = new XML_Parser_Error($msg, $ecode);
+        $err = &new XML_Parser_Error($msg, $ecode);
         return parent::raiseError($err);
     }
-    
+
     // }}}
     // {{{ funcStartHandler()
 
+    /**
+     * derives and calls the Start Handler function
+     *
+     * @param mixed $xp      ??
+     * @param mixed $elem    ??
+     * @param mixed $attribs ??
+     *
+     * @return void
+     */
     function funcStartHandler($xp, $elem, $attribs)
     {
         $func = 'xmltag_' . $elem;
-        if (strchr($func, '.')) {
-            $func = str_replace('.', '_', $func);
-        }
+        $func = str_replace(array('.', '-', ':'), '_', $func);
         if (method_exists($this->_handlerObj, $func)) {
             call_user_func(array(&$this->_handlerObj, $func), $xp, $elem, $attribs);
         } elseif (method_exists($this->_handlerObj, 'xmltag')) {
-            call_user_func(array(&$this->_handlerObj, 'xmltag'), $xp, $elem, $attribs);
+            call_user_func(array(&$this->_handlerObj, 'xmltag'), 
+                $xp, $elem, $attribs);
         }
     }
 
     // }}}
     // {{{ funcEndHandler()
 
+    /**
+     * derives and calls the End Handler function
+     *
+     * @param mixed $xp   ??
+     * @param mixed $elem ??
+     *
+     * @return void
+     */
     function funcEndHandler($xp, $elem)
     {
         $func = 'xmltag_' . $elem . '_';
-        if (strchr($func, '.')) {
-            $func = str_replace('.', '_', $func);
-        }
+        $func = str_replace(array('.', '-', ':'), '_', $func);
         if (method_exists($this->_handlerObj, $func)) {
             call_user_func(array(&$this->_handlerObj, $func), $xp, $elem);
         } elseif (method_exists($this->_handlerObj, 'xmltag_')) {
@@ -587,24 +667,35 @@ class XML_Parser extends PEAR
     // {{{ startHandler()
 
     /**
+     * abstract method signature for Start Handler
+     *
+     * @param mixed $xp       ??
+     * @param mixed $elem     ??
+     * @param mixed &$attribs ??
      *
+     * @return null
      * @abstract
      */
-    function startHandler($xp, $elem, $attribs)
+    function startHandler($xp, $elem, &$attribs)
     {
-        return NULL;
+        return null;
     }
 
     // }}}
     // {{{ endHandler()
 
     /**
+     * abstract method signature for End Handler
+     *
+     * @param mixed $xp   ??
+     * @param mixed $elem ??
      *
+     * @return null
      * @abstract
      */
     function endHandler($xp, $elem)
     {
-        return NULL;
+        return null;
     }
 
 
@@ -622,46 +713,56 @@ class XML_Parser extends PEAR
  * - check for XML_Parser error, using is_a( $error, 'XML_Parser_Error' )
  * - messages can be generated from the xml_parser resource
  *
- * @package XML_Parser
- * @access  public
- * @see     PEAR_Error
+ * @category  XML
+ * @package   XML_Parser
+ * @author    Stig Bakken <ssb@fast.no>
+ * @author    Tomas V.V.Cox <cox@idecnet.com>
+ * @author    Stephan Schmidt <schst@php.net>
+ * @copyright 2002-2008 The PHP Group
+ * @license   http://opensource.org/licenses/bsd-license New BSD License
+ * @version   Release: @package_version@
+ * @link      http://pear.php.net/package/XML_Parser
+ * @see       PEAR_Error
  */
 class XML_Parser_Error extends PEAR_Error
 {
     // {{{ properties
 
-   /**
+    /**
     * prefix for all messages
     *
     * @var      string
-    */    
+    */
     var $error_message_prefix = 'XML_Parser: ';
 
     // }}}
     // {{{ constructor()
-   /**
+    /**
     * construct a new error instance
     *
     * You may either pass a message or an xml_parser resource as first
     * parameter. If a resource has been passed, the last error that
     * happened will be retrieved and returned.
     *
+    * @param string|resource $msgorparser message or parser resource
+    * @param integer         $code        error code
+    * @param integer         $mode        error handling
+    * @param integer         $level       error level
+    *
     * @access   public
-    * @param    string|resource     message or parser resource
-    * @param    integer             error code
-    * @param    integer             error handling
-    * @param    integer             error level
-    */    
+    * @todo PEAR CS - can't meet 85char line limit without arg refactoring
+    */
     function XML_Parser_Error($msgorparser = 'unknown error', $code = 0, $mode = PEAR_ERROR_RETURN, $level = E_USER_NOTICE)
     {
         if (is_resource($msgorparser)) {
-            $code = xml_get_error_code($msgorparser);
-            $msgorparser = sprintf('%s at XML input line %d',
-                                   xml_error_string($code),
-                                   xml_get_current_line_number($msgorparser));
+            $code        = xml_get_error_code($msgorparser);
+            $msgorparser = sprintf('%s at XML input line %d:%d',
+                xml_error_string($code),
+                xml_get_current_line_number($msgorparser),
+                xml_get_current_column_number($msgorparser));
         }
         $this->PEAR_Error($msgorparser, $code, $mode, $level);
     }
     // }}}
 }
-?>
\ No newline at end of file
+?>
diff --git a/3rdparty/XML/Parser/Simple.php b/3rdparty/XML/Parser/Simple.php
new file mode 100644 (file)
index 0000000..9ed0abf
--- /dev/null
@@ -0,0 +1,326 @@
+<?php
+
+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
+
+/**
+ * XML_Parser
+ *
+ * XML Parser's Simple parser class 
+ *
+ * PHP versions 4 and 5
+ *
+ * LICENSE:
+ *
+ * Copyright (c) 2002-2008 The PHP Group
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *    * Redistributions of source code must retain the above copyright
+ *      notice, this list of conditions and the following disclaimer.
+ *    * Redistributions in binary form must reproduce the above copyright
+ *      notice, this list of conditions and the following disclaimer in the
+ *      documentation and/or other materials provided with the distribution.
+ *    * The name of the author may not be used to endorse or promote products
+ *      derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @category  XML
+ * @package   XML_Parser
+ * @author    Stephan Schmidt <schst@php.net>
+ * @copyright 2004-2008 Stephan Schmidt <schst@php.net>
+ * @license   http://opensource.org/licenses/bsd-license New BSD License
+ * @version   CVS: $Id: Simple.php 265444 2008-08-24 21:48:21Z ashnazg $
+ * @link      http://pear.php.net/package/XML_Parser
+ */
+
+/**
+ * built on XML_Parser
+ */
+require_once 'XML/Parser.php';
+
+/**
+ * Simple XML parser class.
+ *
+ * This class is a simplified version of XML_Parser.
+ * In most XML applications the real action is executed,
+ * when a closing tag is found.
+ *
+ * XML_Parser_Simple allows you to just implement one callback
+ * for each tag that will receive the tag with its attributes
+ * and CData.
+ *
+ * <code>
+ * require_once '../Parser/Simple.php';
+ *
+ * class myParser extends XML_Parser_Simple
+ * {
+ *     function myParser()
+ *     {
+ *        $this->XML_Parser_Simple();
+ *      }
+ * 
+ *    function handleElement($name, $attribs, $data)
+ *     {
+ *         printf('handle %s<br>', $name);
+ *     }
+ * }
+ * 
+ * $p = &new myParser();
+ * 
+ * $result = $p->setInputFile('myDoc.xml');
+ * $result = $p->parse();
+ * </code>
+ *
+ * @category  XML
+ * @package   XML_Parser
+ * @author    Stephan Schmidt <schst@php.net>
+ * @copyright 2004-2008 The PHP Group
+ * @license   http://opensource.org/licenses/bsd-license New BSD License
+ * @version   Release: @package_version@
+ * @link      http://pear.php.net/package/XML_Parser
+ */
+class XML_Parser_Simple extends XML_Parser
+{
+    /**
+     * element stack
+     *
+     * @access   private
+     * @var      array
+     */
+    var $_elStack = array();
+
+    /**
+     * all character data
+     *
+     * @access   private
+     * @var      array
+     */
+    var $_data = array();
+
+    /**
+     * element depth
+     *
+     * @access   private
+     * @var      integer
+     */
+    var $_depth = 0;
+
+    /**
+     * Mapping from expat handler function to class method.
+     *
+     * @var  array
+     */
+    var $handler = array(
+        'default_handler'                   => 'defaultHandler',
+        'processing_instruction_handler'    => 'piHandler',
+        'unparsed_entity_decl_handler'      => 'unparsedHandler',
+        'notation_decl_handler'             => 'notationHandler',
+        'external_entity_ref_handler'       => 'entityrefHandler'
+    );
+    
+    /**
+     * Creates an XML parser.
+     *
+     * This is needed for PHP4 compatibility, it will
+     * call the constructor, when a new instance is created.
+     *
+     * @param string $srcenc source charset encoding, use NULL (default) to use
+     *                       whatever the document specifies
+     * @param string $mode   how this parser object should work, "event" for
+     *                       handleElement(), "func" to have it call functions
+     *                       named after elements (handleElement_$name())
+     * @param string $tgtenc a valid target encoding
+     */
+    function XML_Parser_Simple($srcenc = null, $mode = 'event', $tgtenc = null)
+    {
+        $this->XML_Parser($srcenc, $mode, $tgtenc);
+    }
+
+    /**
+     * inits the handlers
+     *
+     * @return mixed
+     * @access private
+     */
+    function _initHandlers()
+    {
+        if (!is_object($this->_handlerObj)) {
+            $this->_handlerObj = &$this;
+        }
+
+        if ($this->mode != 'func' && $this->mode != 'event') {
+            return $this->raiseError('Unsupported mode given', 
+                XML_PARSER_ERROR_UNSUPPORTED_MODE);
+        }
+        xml_set_object($this->parser, $this->_handlerObj);
+
+        xml_set_element_handler($this->parser, array(&$this, 'startHandler'), 
+            array(&$this, 'endHandler'));
+        xml_set_character_data_handler($this->parser, array(&$this, 'cdataHandler'));
+        
+        /**
+         * set additional handlers for character data, entities, etc.
+         */
+        foreach ($this->handler as $xml_func => $method) {
+            if (method_exists($this->_handlerObj, $method)) {
+                $xml_func = 'xml_set_' . $xml_func;
+                $xml_func($this->parser, $method);
+            }
+        }
+    }
+
+    /**
+     * Reset the parser.
+     *
+     * This allows you to use one parser instance
+     * to parse multiple XML documents.
+     *
+     * @access   public
+     * @return   boolean|object     true on success, PEAR_Error otherwise
+     */
+    function reset()
+    {
+        $this->_elStack = array();
+        $this->_data    = array();
+        $this->_depth   = 0;
+        
+        $result = $this->_create();
+        if ($this->isError($result)) {
+            return $result;
+        }
+        return true;
+    }
+
+    /**
+     * start handler
+     *
+     * Pushes attributes and tagname onto a stack
+     *
+     * @param resource $xp       xml parser resource
+     * @param string   $elem     element name
+     * @param array    &$attribs attributes
+     *
+     * @return mixed
+     * @access private
+     * @final
+     */
+    function startHandler($xp, $elem, &$attribs)
+    {
+        array_push($this->_elStack, array(
+            'name'    => $elem,
+            'attribs' => $attribs
+        ));
+        $this->_depth++;
+        $this->_data[$this->_depth] = '';
+    }
+
+    /**
+     * end handler
+     *
+     * Pulls attributes and tagname from a stack
+     *
+     * @param resource $xp   xml parser resource
+     * @param string   $elem element name
+     *
+     * @return mixed
+     * @access private
+     * @final
+     */
+    function endHandler($xp, $elem)
+    {
+        $el   = array_pop($this->_elStack);
+        $data = $this->_data[$this->_depth];
+        $this->_depth--;
+
+        switch ($this->mode) {
+        case 'event':
+            $this->_handlerObj->handleElement($el['name'], $el['attribs'], $data);
+            break;
+        case 'func':
+            $func = 'handleElement_' . $elem;
+            if (strchr($func, '.')) {
+                $func = str_replace('.', '_', $func);
+            }
+            if (method_exists($this->_handlerObj, $func)) {
+                call_user_func(array(&$this->_handlerObj, $func), 
+                    $el['name'], $el['attribs'], $data);
+            }
+            break;
+        }
+    }
+
+    /**
+     * handle character data
+     *
+     * @param resource $xp   xml parser resource
+     * @param string   $data data
+     *
+     * @return void
+     * @access private
+     * @final
+     */
+    function cdataHandler($xp, $data)
+    {
+        $this->_data[$this->_depth] .= $data;
+    }
+
+    /**
+     * handle a tag
+     *
+     * Implement this in your parser 
+     *
+     * @param string $name    element name
+     * @param array  $attribs attributes
+     * @param string $data    character data
+     *
+     * @return void
+     * @access public
+     * @abstract
+     */
+    function handleElement($name, $attribs, $data)
+    {
+    }
+
+    /**
+     * get the current tag depth
+     *
+     * The root tag is in depth 0.
+     *
+     * @access   public
+     * @return   integer
+     */
+    function getCurrentDepth()
+    {
+        return $this->_depth;
+    }
+
+    /**
+     * add some string to the current ddata.
+     *
+     * This is commonly needed, when a document is parsed recursively.
+     *
+     * @param string $data data to add
+     *
+     * @return void
+     * @access public
+     */
+    function addToData($data)
+    {
+        $this->_data[$this->_depth] .= $data;
+    }
+}
+?>
diff --git a/3rdparty/XML/RPC.php b/3rdparty/XML/RPC.php
deleted file mode 100644 (file)
index 096b22a..0000000
+++ /dev/null
@@ -1,1951 +0,0 @@
-<?php
-
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * PHP implementation of the XML-RPC protocol
- *
- * This is a PEAR-ified version of Useful inc's XML-RPC for PHP.
- * It has support for HTTP transport, proxies and authentication.
- *
- * PHP versions 4 and 5
- *
- * LICENSE: License is granted to use or modify this software
- * ("XML-RPC for PHP") for commercial or non-commercial use provided the
- * copyright of the author is preserved in any distributed or derivative work.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESSED OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category   Web Services
- * @package    XML_RPC
- * @author     Edd Dumbill <edd@usefulinc.com>
- * @author     Stig Bakken <stig@php.net>
- * @author     Martin Jansen <mj@php.net>
- * @author     Daniel Convissor <danielc@php.net>
- * @copyright  1999-2001 Edd Dumbill, 2001-2005 The PHP Group
- * @version    CVS: $Id: RPC.php,v 1.83 2005/08/14 20:25:35 danielc Exp $
- * @link       http://pear.php.net/package/XML_RPC
- */
-
-
-if (!function_exists('xml_parser_create')) {
-    PEAR::loadExtension('xml');
-}
-
-/**#@+
- * Error constants
- */
-/**
- * Parameter values don't match parameter types
- */
-define('XML_RPC_ERROR_INVALID_TYPE', 101);
-/**
- * Parameter declared to be numeric but the values are not
- */
-define('XML_RPC_ERROR_NON_NUMERIC_FOUND', 102);
-/**
- * Communication error
- */
-define('XML_RPC_ERROR_CONNECTION_FAILED', 103);
-/**
- * The array or struct has already been started
- */
-define('XML_RPC_ERROR_ALREADY_INITIALIZED', 104);
-/**
- * Incorrect parameters submitted
- */
-define('XML_RPC_ERROR_INCORRECT_PARAMS', 105);
-/**
- * Programming error by developer
- */
-define('XML_RPC_ERROR_PROGRAMMING', 106);
-/**#@-*/
-
-
-/**
- * Data types
- * @global string $GLOBALS['XML_RPC_I4']
- */
-$GLOBALS['XML_RPC_I4'] = 'i4';
-
-/**
- * Data types
- * @global string $GLOBALS['XML_RPC_Int']
- */
-$GLOBALS['XML_RPC_Int'] = 'int';
-
-/**
- * Data types
- * @global string $GLOBALS['XML_RPC_Boolean']
- */
-$GLOBALS['XML_RPC_Boolean'] = 'boolean';
-
-/**
- * Data types
- * @global string $GLOBALS['XML_RPC_Double']
- */
-$GLOBALS['XML_RPC_Double'] = 'double';
-
-/**
- * Data types
- * @global string $GLOBALS['XML_RPC_String']
- */
-$GLOBALS['XML_RPC_String'] = 'string';
-
-/**
- * Data types
- * @global string $GLOBALS['XML_RPC_DateTime']
- */
-$GLOBALS['XML_RPC_DateTime'] = 'dateTime.iso8601';
-
-/**
- * Data types
- * @global string $GLOBALS['XML_RPC_Base64']
- */
-$GLOBALS['XML_RPC_Base64'] = 'base64';
-
-/**
- * Data types
- * @global string $GLOBALS['XML_RPC_Array']
- */
-$GLOBALS['XML_RPC_Array'] = 'array';
-
-/**
- * Data types
- * @global string $GLOBALS['XML_RPC_Struct']
- */
-$GLOBALS['XML_RPC_Struct'] = 'struct';
-
-
-/**
- * Data type meta-types
- * @global array $GLOBALS['XML_RPC_Types']
- */
-$GLOBALS['XML_RPC_Types'] = array(
-    $GLOBALS['XML_RPC_I4']       => 1,
-    $GLOBALS['XML_RPC_Int']      => 1,
-    $GLOBALS['XML_RPC_Boolean']  => 1,
-    $GLOBALS['XML_RPC_String']   => 1,
-    $GLOBALS['XML_RPC_Double']   => 1,
-    $GLOBALS['XML_RPC_DateTime'] => 1,
-    $GLOBALS['XML_RPC_Base64']   => 1,
-    $GLOBALS['XML_RPC_Array']    => 2,
-    $GLOBALS['XML_RPC_Struct']   => 3,
-);
-
-
-/**
- * Error message numbers
- * @global array $GLOBALS['XML_RPC_err']
- */
-$GLOBALS['XML_RPC_err'] = array(
-    'unknown_method'      => 1,
-    'invalid_return'      => 2,
-    'incorrect_params'    => 3,
-    'introspect_unknown'  => 4,
-    'http_error'          => 5,
-    'not_response_object' => 6,
-    'invalid_request'     => 7,
-);
-
-/**
- * Error message strings
- * @global array $GLOBALS['XML_RPC_str']
- */
-$GLOBALS['XML_RPC_str'] = array(
-    'unknown_method'      => 'Unknown method',
-    'invalid_return'      => 'Invalid return payload: enable debugging to examine incoming payload',
-    'incorrect_params'    => 'Incorrect parameters passed to method',
-    'introspect_unknown'  => 'Can\'t introspect: method unknown',
-    'http_error'          => 'Didn\'t receive 200 OK from remote server.',
-    'not_response_object' => 'The requested method didn\'t return an XML_RPC_Response object.',
-    'invalid_request'     => 'Invalid request payload',
-);
-
-
-/**
- * Default XML encoding (ISO-8859-1, UTF-8 or US-ASCII)
- * @global string $GLOBALS['XML_RPC_defencoding']
- */
-$GLOBALS['XML_RPC_defencoding'] = 'UTF-8';
-
-/**
- * User error codes start at 800
- * @global int $GLOBALS['XML_RPC_erruser']
- */
-$GLOBALS['XML_RPC_erruser'] = 800;
-
-/**
- * XML parse error codes start at 100
- * @global int $GLOBALS['XML_RPC_errxml']
- */
-$GLOBALS['XML_RPC_errxml'] = 100;
-
-
-/**
- * Compose backslashes for escaping regexp
- * @global string $GLOBALS['XML_RPC_backslash']
- */
-$GLOBALS['XML_RPC_backslash'] = chr(92) . chr(92);
-
-
-/**
- * Valid parents of XML elements
- * @global array $GLOBALS['XML_RPC_valid_parents']
- */
-$GLOBALS['XML_RPC_valid_parents'] = array(
-    'BOOLEAN' => array('VALUE'),
-    'I4' => array('VALUE'),
-    'INT' => array('VALUE'),
-    'STRING' => array('VALUE'),
-    'DOUBLE' => array('VALUE'),
-    'DATETIME.ISO8601' => array('VALUE'),
-    'BASE64' => array('VALUE'),
-    'ARRAY' => array('VALUE'),
-    'STRUCT' => array('VALUE'),
-    'PARAM' => array('PARAMS'),
-    'METHODNAME' => array('METHODCALL'),
-    'PARAMS' => array('METHODCALL', 'METHODRESPONSE'),
-    'MEMBER' => array('STRUCT'),
-    'NAME' => array('MEMBER'),
-    'DATA' => array('ARRAY'),
-    'FAULT' => array('METHODRESPONSE'),
-    'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'),
-);
-
-
-/**
- * Stores state during parsing
- *
- * quick explanation of components:
- *   + ac     = accumulates values
- *   + qt     = decides if quotes are needed for evaluation
- *   + cm     = denotes struct or array (comma needed)
- *   + isf    = indicates a fault
- *   + lv     = indicates "looking for a value": implements the logic
- *               to allow values with no types to be strings
- *   + params = stores parameters in method calls
- *   + method = stores method name
- *
- * @global array $GLOBALS['XML_RPC_xh']
- */
-$GLOBALS['XML_RPC_xh'] = array();
-
-
-/**
- * Start element handler for the XML parser
- *
- * @return void
- */
-function XML_RPC_se($parser_resource, $name, $attrs)
-{
-    global $XML_RPC_xh, $XML_RPC_DateTime, $XML_RPC_String, $XML_RPC_valid_parents;
-    $parser = (int) $parser_resource;
-
-    // if invalid xmlrpc already detected, skip all processing
-    if ($XML_RPC_xh[$parser]['isf'] >= 2) {
-        return;
-    }
-
-    // check for correct element nesting
-    // top level element can only be of 2 types
-    if (count($XML_RPC_xh[$parser]['stack']) == 0) {
-        if ($name != 'METHODRESPONSE' && $name != 'METHODCALL') {
-            $XML_RPC_xh[$parser]['isf'] = 2;
-            $XML_RPC_xh[$parser]['isf_reason'] = 'missing top level xmlrpc element';
-            return;
-        }
-    } else {
-        // not top level element: see if parent is OK
-        if (!in_array($XML_RPC_xh[$parser]['stack'][0], $XML_RPC_valid_parents[$name])) {
-            $name = preg_replace('[^a-zA-Z0-9._-]', '', $name);
-            $XML_RPC_xh[$parser]['isf'] = 2;
-            $XML_RPC_xh[$parser]['isf_reason'] = "xmlrpc element $name cannot be child of {$XML_RPC_xh[$parser]['stack'][0]}";
-            return;
-        }
-    }
-
-    switch ($name) {
-    case 'STRUCT':
-        $XML_RPC_xh[$parser]['cm']++;
-
-        // turn quoting off
-        $XML_RPC_xh[$parser]['qt'] = 0;
-
-        $cur_val = array();
-        $cur_val['value'] = array();
-        $cur_val['members'] = 1;
-        array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val);
-        break;
-
-    case 'ARRAY':
-        $XML_RPC_xh[$parser]['cm']++;
-
-        // turn quoting off
-        $XML_RPC_xh[$parser]['qt'] = 0;
-
-        $cur_val = array();
-        $cur_val['value'] = array();
-        $cur_val['members'] = 0;
-        array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val);
-        break;
-
-    case 'NAME':
-        $XML_RPC_xh[$parser]['ac'] = '';
-        break;
-
-    case 'FAULT':
-        $XML_RPC_xh[$parser]['isf'] = 1;
-        break;
-
-    case 'PARAM':
-        $XML_RPC_xh[$parser]['valuestack'] = array();
-        break;
-
-    case 'VALUE':
-        $XML_RPC_xh[$parser]['lv'] = 1;
-        $XML_RPC_xh[$parser]['vt'] = $XML_RPC_String;
-        $XML_RPC_xh[$parser]['ac'] = '';
-        $XML_RPC_xh[$parser]['qt'] = 0;
-        // look for a value: if this is still 1 by the
-        // time we reach the first data segment then the type is string
-        // by implication and we need to add in a quote
-        break;
-
-    case 'I4':
-    case 'INT':
-    case 'STRING':
-    case 'BOOLEAN':
-    case 'DOUBLE':
-    case 'DATETIME.ISO8601':
-    case 'BASE64':
-        $XML_RPC_xh[$parser]['ac'] = ''; // reset the accumulator
-
-        if ($name == 'DATETIME.ISO8601' || $name == 'STRING') {
-            $XML_RPC_xh[$parser]['qt'] = 1;
-
-            if ($name == 'DATETIME.ISO8601') {
-                $XML_RPC_xh[$parser]['vt'] = $XML_RPC_DateTime;
-            }
-
-        } elseif ($name == 'BASE64') {
-            $XML_RPC_xh[$parser]['qt'] = 2;
-        } else {
-            // No quoting is required here -- but
-            // at the end of the element we must check
-            // for data format errors.
-            $XML_RPC_xh[$parser]['qt'] = 0;
-        }
-        break;
-
-    case 'MEMBER':
-        $XML_RPC_xh[$parser]['ac'] = '';
-        break;
-
-    case 'DATA':
-    case 'METHODCALL':
-    case 'METHODNAME':
-    case 'METHODRESPONSE':
-    case 'PARAMS':
-        // valid elements that add little to processing
-        break;
-    }
-
-
-    // Save current element to stack
-    array_unshift($XML_RPC_xh[$parser]['stack'], $name);
-
-    if ($name != 'VALUE') {
-        $XML_RPC_xh[$parser]['lv'] = 0;
-    }
-}
-
-/**
- * End element handler for the XML parser
- *
- * @return void
- */
-function XML_RPC_ee($parser_resource, $name)
-{
-    global $XML_RPC_xh, $XML_RPC_Types, $XML_RPC_String;
-    $parser = (int) $parser_resource;
-
-    if ($XML_RPC_xh[$parser]['isf'] >= 2) {
-        return;
-    }
-
-    // push this element from stack
-    // NB: if XML validates, correct opening/closing is guaranteed and
-    // we do not have to check for $name == $curr_elem.
-    // we also checked for proper nesting at start of elements...
-    $curr_elem = array_shift($XML_RPC_xh[$parser]['stack']);
-
-    switch ($name) {
-    case 'STRUCT':
-    case 'ARRAY':
-    $cur_val = array_shift($XML_RPC_xh[$parser]['valuestack']);
-    $XML_RPC_xh[$parser]['value'] = $cur_val['value'];
-        $XML_RPC_xh[$parser]['vt'] = strtolower($name);
-        $XML_RPC_xh[$parser]['cm']--;
-        break;
-
-    case 'NAME':
-    $XML_RPC_xh[$parser]['valuestack'][0]['name'] = $XML_RPC_xh[$parser]['ac'];
-        break;
-
-    case 'BOOLEAN':
-        // special case here: we translate boolean 1 or 0 into PHP
-        // constants true or false
-        if ($XML_RPC_xh[$parser]['ac'] == '1') {
-            $XML_RPC_xh[$parser]['ac'] = 'true';
-        } else {
-            $XML_RPC_xh[$parser]['ac'] = 'false';
-        }
-
-        $XML_RPC_xh[$parser]['vt'] = strtolower($name);
-        // Drop through intentionally.
-
-    case 'I4':
-    case 'INT':
-    case 'STRING':
-    case 'DOUBLE':
-    case 'DATETIME.ISO8601':
-    case 'BASE64':
-        if ($XML_RPC_xh[$parser]['qt'] == 1) {
-            // we use double quotes rather than single so backslashification works OK
-            $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac'];
-        } elseif ($XML_RPC_xh[$parser]['qt'] == 2) {
-            $XML_RPC_xh[$parser]['value'] = base64_decode($XML_RPC_xh[$parser]['ac']);
-        } elseif ($name == 'BOOLEAN') {
-            $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac'];
-        } else {
-            // we have an I4, INT or a DOUBLE
-            // we must check that only 0123456789-.<space> are characters here
-            if (!ereg("^[+-]?[0123456789 \t\.]+$", $XML_RPC_xh[$parser]['ac'])) {
-                XML_RPC_Base::raiseError('Non-numeric value received in INT or DOUBLE',
-                                         XML_RPC_ERROR_NON_NUMERIC_FOUND);
-                $XML_RPC_xh[$parser]['value'] = XML_RPC_ERROR_NON_NUMERIC_FOUND;
-            } else {
-                // it's ok, add it on
-                $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac'];
-            }
-        }
-
-        $XML_RPC_xh[$parser]['ac'] = '';
-        $XML_RPC_xh[$parser]['qt'] = 0;
-        $XML_RPC_xh[$parser]['lv'] = 3; // indicate we've found a value
-        break;
-
-    case 'VALUE':
-        // deal with a string value
-        if (strlen($XML_RPC_xh[$parser]['ac']) > 0 &&
-            $XML_RPC_xh[$parser]['vt'] == $XML_RPC_String) {
-            $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac'];
-        }
-
-        $temp = new XML_RPC_Value($XML_RPC_xh[$parser]['value'], $XML_RPC_xh[$parser]['vt']);
-
-        $cur_val = array_shift($XML_RPC_xh[$parser]['valuestack']);
-        if (is_array($cur_val)) {
-            if ($cur_val['members']==0) {
-                $cur_val['value'][] = $temp;
-            } else {
-                $XML_RPC_xh[$parser]['value'] = $temp;
-            }
-            array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val);
-        } else {
-            $XML_RPC_xh[$parser]['value'] = $temp;
-        }
-        break;
-
-    case 'MEMBER':
-        $XML_RPC_xh[$parser]['ac'] = '';
-        $XML_RPC_xh[$parser]['qt'] = 0;
-
-        $cur_val = array_shift($XML_RPC_xh[$parser]['valuestack']);
-        if (is_array($cur_val)) {
-            if ($cur_val['members']==1) {
-                $cur_val['value'][$cur_val['name']] = $XML_RPC_xh[$parser]['value'];
-            }
-            array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val);
-        }
-        break;
-
-    case 'DATA':
-        $XML_RPC_xh[$parser]['ac'] = '';
-        $XML_RPC_xh[$parser]['qt'] = 0;
-        break;
-
-    case 'PARAM':
-        $XML_RPC_xh[$parser]['params'][] = $XML_RPC_xh[$parser]['value'];
-        break;
-
-    case 'METHODNAME':
-    case 'RPCMETHODNAME':
-        $XML_RPC_xh[$parser]['method'] = ereg_replace("^[\n\r\t ]+", '',
-                                                      $XML_RPC_xh[$parser]['ac']);
-        break;
-    }
-
-    // if it's a valid type name, set the type
-    if (isset($XML_RPC_Types[strtolower($name)])) {
-        $XML_RPC_xh[$parser]['vt'] = strtolower($name);
-    }
-}
-
-/**
- * Character data handler for the XML parser
- *
- * @return void
- */
-function XML_RPC_cd($parser_resource, $data)
-{
-    global $XML_RPC_xh, $XML_RPC_backslash;
-    $parser = (int) $parser_resource;
-
-    if ($XML_RPC_xh[$parser]['lv'] != 3) {
-        // "lookforvalue==3" means that we've found an entire value
-        // and should discard any further character data
-
-        if ($XML_RPC_xh[$parser]['lv'] == 1) {
-            // if we've found text and we're just in a <value> then
-            // turn quoting on, as this will be a string
-            $XML_RPC_xh[$parser]['qt'] = 1;
-            // and say we've found a value
-            $XML_RPC_xh[$parser]['lv'] = 2;
-        }
-
-        // replace characters that eval would
-        // do special things with
-        if (!isset($XML_RPC_xh[$parser]['ac'])) {
-            $XML_RPC_xh[$parser]['ac'] = '';
-        }
-        $XML_RPC_xh[$parser]['ac'] .= $data;
-    }
-}
-
-/**
- * The common methods and properties for all of the XML_RPC classes
- *
- * @category   Web Services
- * @package    XML_RPC
- * @author     Edd Dumbill <edd@usefulinc.com>
- * @author     Stig Bakken <stig@php.net>
- * @author     Martin Jansen <mj@php.net>
- * @author     Daniel Convissor <danielc@php.net>
- * @copyright  1999-2001 Edd Dumbill, 2001-2005 The PHP Group
- * @version    Release: 1.4.0
- * @link       http://pear.php.net/package/XML_RPC
- */
-class XML_RPC_Base {
-
-    /**
-     * PEAR Error handling
-     *
-     * @return object  PEAR_Error object
-     */
-    function raiseError($msg, $code)
-    {
-        include_once 'PEAR.php';
-        if (is_object(@$this)) {
-            return PEAR::raiseError(get_class($this) . ': ' . $msg, $code);
-        } else {
-            return PEAR::raiseError('XML_RPC: ' . $msg, $code);
-        }
-    }
-
-    /**
-     * Tell whether something is a PEAR_Error object
-     *
-     * @param mixed $value  the item to check
-     *
-     * @return bool  whether $value is a PEAR_Error object or not
-     *
-     * @access public
-     */
-    function isError($value)
-    {
-        return is_a($value, 'PEAR_Error');
-    }
-}
-
-/**
- * The methods and properties for submitting XML RPC requests
- *
- * @category   Web Services
- * @package    XML_RPC
- * @author     Edd Dumbill <edd@usefulinc.com>
- * @author     Stig Bakken <stig@php.net>
- * @author     Martin Jansen <mj@php.net>
- * @author     Daniel Convissor <danielc@php.net>
- * @copyright  1999-2001 Edd Dumbill, 2001-2005 The PHP Group
- * @version    Release: 1.4.0
- * @link       http://pear.php.net/package/XML_RPC
- */
-class XML_RPC_Client extends XML_RPC_Base {
-
-    /**
-     * The path and name of the RPC server script you want the request to go to
-     * @var string
-     */
-    var $path = '';
-
-    /**
-     * The name of the remote server to connect to
-     * @var string
-     */
-    var $server = '';
-
-    /**
-     * The protocol to use in contacting the remote server
-     * @var string
-     */
-    var $protocol = 'http://';
-
-    /**
-     * The port for connecting to the remote server
-     *
-     * The default is 80 for http:// connections
-     * and 443 for https:// and ssl:// connections.
-     *
-     * @var integer
-     */
-    var $port = 80;
-
-    /**
-     * A user name for accessing the RPC server
-     * @var string
-     * @see XML_RPC_Client::setCredentials()
-     */
-    var $username = '';
-
-    /**
-     * A password for accessing the RPC server
-     * @var string
-     * @see XML_RPC_Client::setCredentials()
-     */
-    var $password = '';
-
-    /**
-     * The name of the proxy server to use, if any
-     * @var string
-     */
-    var $proxy = '';
-
-    /**
-     * The protocol to use in contacting the proxy server, if any
-     * @var string
-     */
-    var $proxy_protocol = 'http://';
-
-    /**
-     * The port for connecting to the proxy server
-     *
-     * The default is 8080 for http:// connections
-     * and 443 for https:// and ssl:// connections.
-     *
-     * @var integer
-     */
-    var $proxy_port = 8080;
-
-    /**
-     * A user name for accessing the proxy server
-     * @var string
-     */
-    var $proxy_user = '';
-
-    /**
-     * A password for accessing the proxy server
-     * @var string
-     */
-    var $proxy_pass = '';
-
-    /**
-     * The error number, if any
-     * @var integer
-     */
-    var $errno = 0;
-
-    /**
-     * The error message, if any
-     * @var string
-     */
-    var $errstr = '';
-
-    /**
-     * The current debug mode (1 = on, 0 = off)
-     * @var integer
-     */
-    var $debug = 0;
-
-    /**
-     * The HTTP headers for the current request.
-     * @var string
-     */
-    var $headers = '';
-
-
-    /**
-     * Sets the object's properties
-     *
-     * @param string  $path        the path and name of the RPC server script
-     *                              you want the request to go to
-     * @param string  $server      the URL of the remote server to connect to.
-     *                              If this parameter doesn't specify a
-     *                              protocol and $port is 443, ssl:// is
-     *                              assumed.
-     * @param integer $port        a port for connecting to the remote server.
-     *                              Defaults to 80 for http:// connections and
-     *                              443 for https:// and ssl:// connections.
-     * @param string  $proxy       the URL of the proxy server to use, if any.
-     *                              If this parameter doesn't specify a
-     *                              protocol and $port is 443, ssl:// is
-     *                              assumed.
-     * @param integer $proxy_port  a port for connecting to the remote server.
-     *                              Defaults to 8080 for http:// connections and
-     *                              443 for https:// and ssl:// connections.
-     * @param string  $proxy_user  a user name for accessing the proxy server
-     * @param string  $proxy_pass  a password for accessing the proxy server
-     *
-     * @return void
-     */
-    function XML_RPC_Client($path, $server, $port = 0,
-                            $proxy = '', $proxy_port = 0,
-                            $proxy_user = '', $proxy_pass = '')
-    {
-        $this->path       = $path;
-        $this->proxy_user = $proxy_user;
-        $this->proxy_pass = $proxy_pass;
-
-        preg_match('@^(http://|https://|ssl://)?(.*)$@', $server, $match);
-        if ($match[1] == '') {
-            if ($port == 443) {
-                $this->server   = $match[2];
-                $this->protocol = 'ssl://';
-                $this->port     = 443;
-            } else {
-                $this->server = $match[2];
-                if ($port) {
-                    $this->port = $port;
-                }
-            }
-        } elseif ($match[1] == 'http://') {
-            $this->server = $match[2];
-            if ($port) {
-                $this->port = $port;
-            }
-        } else {
-            $this->server   = $match[2];
-            $this->protocol = 'ssl://';
-            if ($port) {
-                $this->port = $port;
-            } else {
-                $this->port = 443;
-            }
-        }
-
-        if ($proxy) {
-            preg_match('@^(http://|https://|ssl://)?(.*)$@', $proxy, $match);
-            if ($match[1] == '') {
-                if ($proxy_port == 443) {
-                    $this->proxy          = $match[2];
-                    $this->proxy_protocol = 'ssl://';
-                    $this->proxy_port     = 443;
-                } else {
-                    $this->proxy = $match[2];
-                    if ($proxy_port) {
-                        $this->proxy_port = $proxy_port;
-                    }
-                }
-            } elseif ($match[1] == 'http://') {
-                $this->proxy = $match[2];
-                if ($proxy_port) {
-                    $this->proxy_port = $proxy_port;
-                }
-            } else {
-                $this->proxy          = $match[2];
-                $this->proxy_protocol = 'ssl://';
-                if ($proxy_port) {
-                    $this->proxy_port = $proxy_port;
-                } else {
-                    $this->proxy_port = 443;
-                }
-            }
-        }
-    }
-
-    /**
-     * Change the current debug mode
-     *
-     * @param int $in  where 1 = on, 0 = off
-     *
-     * @return void
-     */
-    function setDebug($in)
-    {
-        if ($in) {
-            $this->debug = 1;
-        } else {
-            $this->debug = 0;
-        }
-    }
-
-    /**
-     * Set username and password properties for connecting to the RPC server
-     *
-     * @param string $u  the user name
-     * @param string $p  the password
-     *
-     * @return void
-     *
-     * @see XML_RPC_Client::$username, XML_RPC_Client::$password
-     */
-    function setCredentials($u, $p)
-    {
-        $this->username = $u;
-        $this->password = $p;
-    }
-
-    /**
-     * Transmit the RPC request via HTTP 1.0 protocol
-     *
-     * @param object $msg       the XML_RPC_Message object
-     * @param int    $timeout   how many seconds to wait for the request
-     *
-     * @return object  an XML_RPC_Response object.  0 is returned if any
-     *                  problems happen.
-     *
-     * @see XML_RPC_Message, XML_RPC_Client::XML_RPC_Client(),
-     *      XML_RPC_Client::setCredentials()
-     */
-    function send($msg, $timeout = 0)
-    {
-        if (strtolower(get_class($msg)) != 'xml_rpc_message') {
-            $this->errstr = 'send()\'s $msg parameter must be an'
-                          . ' XML_RPC_Message object.';
-            $this->raiseError($this->errstr, XML_RPC_ERROR_PROGRAMMING);
-            return 0;
-        }
-        $msg->debug = $this->debug;
-        return $this->sendPayloadHTTP10($msg, $this->server, $this->port,
-                                        $timeout, $this->username,
-                                        $this->password);
-    }
-
-    /**
-     * Transmit the RPC request via HTTP 1.0 protocol
-     *
-     * Requests should be sent using XML_RPC_Client send() rather than
-     * calling this method directly.
-     *
-     * @param object $msg       the XML_RPC_Message object
-     * @param string $server    the server to send the request to
-     * @param int    $port      the server port send the request to
-     * @param int    $timeout   how many seconds to wait for the request
-     *                           before giving up
-     * @param string $username  a user name for accessing the RPC server
-     * @param string $password  a password for accessing the RPC server
-     *
-     * @return object  an XML_RPC_Response object.  0 is returned if any
-     *                  problems happen.
-     *
-     * @access protected
-     * @see XML_RPC_Client::send()
-     */
-    function sendPayloadHTTP10($msg, $server, $port, $timeout = 0,
-                               $username = '', $password = '')
-    {
-        /*
-         * If we're using a proxy open a socket to the proxy server
-         * instead to the xml-rpc server
-         */
-        if ($this->proxy) {
-            if ($this->proxy_protocol == 'http://') {
-                $protocol = '';
-            } else {
-                $protocol = $this->proxy_protocol;
-            }
-            if ($timeout > 0) {
-                $fp = @fsockopen($protocol . $this->proxy, $this->proxy_port,
-                                 $this->errno, $this->errstr, $timeout);
-            } else {
-                $fp = @fsockopen($protocol . $this->proxy, $this->proxy_port,
-                                 $this->errno, $this->errstr);
-            }
-        } else {
-            if ($this->protocol == 'http://') {
-                $protocol = '';
-            } else {
-                $protocol = $this->protocol;
-            }
-            if ($timeout > 0) {
-                $fp = @fsockopen($protocol . $server, $port,
-                                 $this->errno, $this->errstr, $timeout);
-            } else {
-                $fp = @fsockopen($protocol . $server, $port,
-                                 $this->errno, $this->errstr);
-            }
-        }
-
-        /*
-         * Just raising the error without returning it is strange,
-         * but keep it here for backwards compatibility.
-         */
-        if (!$fp && $this->proxy) {
-            $this->raiseError('Connection to proxy server '
-                              . $this->proxy . ':' . $this->proxy_port
-                              . ' failed. ' . $this->errstr,
-                              XML_RPC_ERROR_CONNECTION_FAILED);
-            return 0;
-        } elseif (!$fp) {
-            $this->raiseError('Connection to RPC server '
-                              . $server . ':' . $port
-                              . ' failed. ' . $this->errstr,
-                              XML_RPC_ERROR_CONNECTION_FAILED);
-            return 0;
-        }
-
-        if ($timeout) {
-            /*
-             * Using socket_set_timeout() because stream_set_timeout()
-             * was introduced in 4.3.0, but we need to support 4.2.0.
-             */
-            socket_set_timeout($fp, $timeout);
-        }
-
-        // Pre-emptive BC hacks for fools calling sendPayloadHTTP10() directly
-        if ($username != $this->username) {
-            $this->setCredentials($username, $password);
-        }
-
-        // Only create the payload if it was not created previously
-        if (empty($msg->payload)) {
-            $msg->createPayload();
-        }
-        $this->createHeaders($msg);
-
-        $op  = $this->headers . "\r\n\r\n";
-        $op .= $msg->payload;
-
-        if (!fputs($fp, $op, strlen($op))) {
-            $this->errstr = 'Write error';
-            return 0;
-        }
-        $resp = $msg->parseResponseFile($fp);
-
-        $meta = socket_get_status($fp);
-        if ($meta['timed_out']) {
-            fclose($fp);
-            $this->errstr = 'RPC server did not send response before timeout.';
-            $this->raiseError($this->errstr, XML_RPC_ERROR_CONNECTION_FAILED);
-            return 0;
-        }
-
-        fclose($fp);
-        return $resp;
-    }
-
-    /**
-     * Determines the HTTP headers and puts it in the $headers property
-     *
-     * @param object $msg       the XML_RPC_Message object
-     *
-     * @return boolean  TRUE if okay, FALSE if the message payload isn't set.
-     *
-     * @access protected
-     */
-    function createHeaders($msg)
-    {
-        if (empty($msg->payload)) {
-            return false;
-        }
-        if ($this->proxy) {
-            $this->headers = 'POST ' . $this->protocol . $this->server;
-            if ($this->proxy_port) {
-                $this->headers .= ':' . $this->port;
-            }
-        } else {
-           $this->headers = 'POST ';
-        }
-        $this->headers .= $this->path. " HTTP/1.0\r\n";
-
-        $this->headers .= "User-Agent: PEAR XML_RPC\r\n";
-        $this->headers .= 'Host: ' . $this->server . "\r\n";
-
-        if ($this->proxy && $this->proxy_user) {
-            $this->headers .= 'Proxy-Authorization: Basic '
-                     . base64_encode("$this->proxy_user:$this->proxy_pass")
-                     . "\r\n";
-        }
-
-        // thanks to Grant Rauscher <grant7@firstworld.net> for this
-        if ($this->username) {
-            $this->headers .= 'Authorization: Basic '
-                     . base64_encode("$this->username:$this->password")
-                     . "\r\n";
-        }
-
-        $this->headers .= "Content-Type: text/xml\r\n";
-        $this->headers .= 'Content-Length: ' . strlen($msg->payload);
-        return true;
-    }
-}
-
-/**
- * The methods and properties for interpreting responses to XML RPC requests
- *
- * @category   Web Services
- * @package    XML_RPC
- * @author     Edd Dumbill <edd@usefulinc.com>
- * @author     Stig Bakken <stig@php.net>
- * @author     Martin Jansen <mj@php.net>
- * @author     Daniel Convissor <danielc@php.net>
- * @copyright  1999-2001 Edd Dumbill, 2001-2005 The PHP Group
- * @version    Release: 1.4.0
- * @link       http://pear.php.net/package/XML_RPC
- */
-class XML_RPC_Response extends XML_RPC_Base
-{
-    var $xv;
-    var $fn;
-    var $fs;
-    var $hdrs;
-
-    /**
-     * @return void
-     */
-    function XML_RPC_Response($val, $fcode = 0, $fstr = '')
-    {
-        if ($fcode != 0) {
-            $this->fn = $fcode;
-            $this->fs = htmlspecialchars($fstr);
-        } else {
-            $this->xv = $val;
-        }
-    }
-
-    /**
-     * @return int  the error code
-     */
-    function faultCode()
-    {
-        if (isset($this->fn)) {
-            return $this->fn;
-        } else {
-            return 0;
-        }
-    }
-
-    /**
-     * @return string  the error string
-     */
-    function faultString()
-    {
-        return $this->fs;
-    }
-
-    /**
-     * @return mixed  the value
-     */
-    function value()
-    {
-        return $this->xv;
-    }
-
-    /**
-     * @return string  the error message in XML format
-     */
-    function serialize()
-    {
-        $rs = "<methodResponse>\n";
-        if ($this->fn) {
-            $rs .= "<fault>
-  <value>
-    <struct>
-      <member>
-        <name>faultCode</name>
-        <value><int>" . $this->fn . "</int></value>
-      </member>
-      <member>
-        <name>faultString</name>
-        <value><string>" . $this->fs . "</string></value>
-      </member>
-    </struct>
-  </value>
-</fault>";
-        } else {
-            $rs .= "<params>\n<param>\n" . $this->xv->serialize() .
-        "</param>\n</params>";
-        }
-        $rs .= "\n</methodResponse>";
-        return $rs;
-    }
-}
-
-/**
- * The methods and properties for composing XML RPC messages
- *
- * @category   Web Services
- * @package    XML_RPC
- * @author     Edd Dumbill <edd@usefulinc.com>
- * @author     Stig Bakken <stig@php.net>
- * @author     Martin Jansen <mj@php.net>
- * @author     Daniel Convissor <danielc@php.net>
- * @copyright  1999-2001 Edd Dumbill, 2001-2005 The PHP Group
- * @version    Release: 1.4.0
- * @link       http://pear.php.net/package/XML_RPC
- */
-class XML_RPC_Message extends XML_RPC_Base
-{
-    /**
-     * The current debug mode (1 = on, 0 = off)
-     * @var integer
-     */
-    var $debug = 0;
-
-    /**
-     * The encoding to be used for outgoing messages
-     *
-     * Defaults to the value of <var>$GLOBALS['XML_RPC_defencoding']</var>
-     *
-     * @var string
-     * @see XML_RPC_Message::setSendEncoding(),
-     *      $GLOBALS['XML_RPC_defencoding'], XML_RPC_Message::xml_header()
-     */
-    var $send_encoding = '';
-
-    /**
-     * The method presently being evaluated
-     * @var string
-     */
-    var $methodname = '';
-
-    /**
-     * @var array
-     */
-    var $params = array();
-
-    /**
-     * The XML message being generated
-     * @var string
-     */
-    var $payload = '';
-
-    /**
-     * @return void
-     */
-    function XML_RPC_Message($meth, $pars = 0)
-    {
-        $this->methodname = $meth;
-        if (is_array($pars) && sizeof($pars) > 0) {
-            for ($i = 0; $i < sizeof($pars); $i++) {
-                $this->addParam($pars[$i]);
-            }
-        }
-    }
-
-    /**
-     * Produces the XML declaration including the encoding attribute
-     *
-     * The encoding is determined by this class' <var>$send_encoding</var>
-     * property.  If the <var>$send_encoding</var> property is not set, use
-     * <var>$GLOBALS['XML_RPC_defencoding']</var>.
-     *
-     * @return string  the XML declaration and <methodCall> element
-     *
-     * @see XML_RPC_Message::setSendEncoding(),
-     *      XML_RPC_Message::$send_encoding, $GLOBALS['XML_RPC_defencoding']
-     */
-    function xml_header()
-    {
-        global $XML_RPC_defencoding;
-        if (!$this->send_encoding) {
-            $this->send_encoding = $XML_RPC_defencoding;
-        }
-        return '<?xml version="1.0" encoding="' . $this->send_encoding . '"?>'
-               . "\n<methodCall>\n";
-    }
-
-    /**
-     * @return string  the closing </methodCall> tag
-     */
-    function xml_footer()
-    {
-        return "</methodCall>\n";
-    }
-
-    /**
-     * @return void
-     *
-     * @uses XML_RPC_Message::xml_header(), XML_RPC_Message::xml_footer()
-     */
-    function createPayload()
-    {
-        $this->payload = $this->xml_header();
-        $this->payload .= '<methodName>' . $this->methodname . "</methodName>\n";
-        $this->payload .= "<params>\n";
-        for ($i = 0; $i < sizeof($this->params); $i++) {
-            $p = $this->params[$i];
-            $this->payload .= "<param>\n" . $p->serialize() . "</param>\n";
-        }
-        $this->payload .= "</params>\n";
-        $this->payload .= $this->xml_footer();
-        $this->payload = ereg_replace("[\r\n]+", "\r\n", $this->payload);
-    }
-
-    /**
-     * @return string  the name of the method
-     */
-    function method($meth = '')
-    {
-        if ($meth != '') {
-            $this->methodname = $meth;
-        }
-        return $this->methodname;
-    }
-
-    /**
-     * @return string  the payload
-     */
-    function serialize()
-    {
-        $this->createPayload();
-        return $this->payload;
-    }
-
-    /**
-     * @return void
-     */
-    function addParam($par)
-    {
-        $this->params[] = $par;
-    }
-
-    /**
-     * Obtains an XML_RPC_Value object for the given parameter
-     *
-     * @param int $i  the index number of the parameter to obtain
-     *
-     * @return object  the XML_RPC_Value object.
-     *                  If the parameter doesn't exist, an XML_RPC_Response object.
-     *
-     * @since Returns XML_RPC_Response object on error since Release 1.3.0
-     */
-    function getParam($i)
-    {
-        global $XML_RPC_err, $XML_RPC_str;
-
-        if (isset($this->params[$i])) {
-            return $this->params[$i];
-        } else {
-            $this->raiseError('The submitted request did not contain this parameter',
-                              XML_RPC_ERROR_INCORRECT_PARAMS);
-            return new XML_RPC_Response(0, $XML_RPC_err['incorrect_params'],
-                                        $XML_RPC_str['incorrect_params']);
-        }
-    }
-
-    /**
-     * @return int  the number of parameters
-     */
-    function getNumParams()
-    {
-        return sizeof($this->params);
-    }
-
-    /**
-     * Sets the XML declaration's encoding attribute
-     *
-     * @param string $type  the encoding type (ISO-8859-1, UTF-8 or US-ASCII)
-     *
-     * @return void
-     *
-     * @see XML_RPC_Message::$send_encoding, XML_RPC_Message::xml_header()
-     * @since Method available since Release 1.2.0
-     */
-    function setSendEncoding($type)
-    {
-        $this->send_encoding = $type;
-    }
-
-    /**
-     * Determine the XML's encoding via the encoding attribute
-     * in the XML declaration
-     *
-     * If the encoding parameter is not set or is not ISO-8859-1, UTF-8
-     * or US-ASCII, $XML_RPC_defencoding will be returned.
-     *
-     * @param string $data  the XML that will be parsed
-     *
-     * @return string  the encoding to be used
-     *
-     * @link   http://php.net/xml_parser_create
-     * @since  Method available since Release 1.2.0
-     */
-    function getEncoding($data)
-    {
-        global $XML_RPC_defencoding;
-
-        if (preg_match('/<\?xml[^>]*\s*encoding\s*=\s*[\'"]([^"\']*)[\'"]/i',
-                       $data, $match))
-        {
-            $match[1] = trim(strtoupper($match[1]));
-            switch ($match[1]) {
-                case 'ISO-8859-1':
-                case 'UTF-8':
-                case 'US-ASCII':
-                    return $match[1];
-                    break;
-
-                default:
-                    return $XML_RPC_defencoding;
-            }
-        } else {
-            return $XML_RPC_defencoding;
-        }
-    }
-
-    /**
-     * @return object  a new XML_RPC_Response object
-     */
-    function parseResponseFile($fp)
-    {
-        $ipd = '';
-        while ($data = @fread($fp, 8192)) {
-            $ipd .= $data;
-        }
-        return $this->parseResponse($ipd);
-    }
-
-    /**
-     * @return object  a new XML_RPC_Response object
-     */
-    function parseResponse($data = '')
-    {
-        global $XML_RPC_xh, $XML_RPC_err, $XML_RPC_str, $XML_RPC_defencoding;
-
-        $encoding = $this->getEncoding($data);
-        $parser_resource = xml_parser_create($encoding);
-        $parser = (int) $parser_resource;
-
-        $XML_RPC_xh = array();
-        $XML_RPC_xh[$parser] = array();
-
-        $XML_RPC_xh[$parser]['cm'] = 0;
-        $XML_RPC_xh[$parser]['isf'] = 0;
-        $XML_RPC_xh[$parser]['ac'] = '';
-        $XML_RPC_xh[$parser]['qt'] = '';
-        $XML_RPC_xh[$parser]['stack'] = array();
-        $XML_RPC_xh[$parser]['valuestack'] = array();
-
-        xml_parser_set_option($parser_resource, XML_OPTION_CASE_FOLDING, true);
-        xml_set_element_handler($parser_resource, 'XML_RPC_se', 'XML_RPC_ee');
-        xml_set_character_data_handler($parser_resource, 'XML_RPC_cd');
-
-        $hdrfnd = 0;
-        if ($this->debug) {
-            print "\n<pre>---GOT---\n";
-            print isset($_SERVER['SERVER_PROTOCOL']) ? htmlspecialchars($data) : $data;
-            print "\n---END---</pre>\n";
-        }
-
-        // See if response is a 200 or a 100 then a 200, else raise error.
-        // But only do this if we're using the HTTP protocol.
-        if (ereg('^HTTP', $data) &&
-            !ereg('^HTTP/[0-9\.]+ 200 ', $data) &&
-            !preg_match('@^HTTP/[0-9\.]+ 10[0-9]([A-Za-z ]+)?[\r\n]+HTTP/[0-9\.]+ 200@', $data))
-        {
-                $errstr = substr($data, 0, strpos($data, "\n") - 1);
-                if(defined("DEBUG") && DEBUG) {error_log('HTTP error, got response: ' . $errstr);}
-                $r = new XML_RPC_Response(0, $XML_RPC_err['http_error'],
-                                          $XML_RPC_str['http_error'] . ' (' .
-                                          $errstr . ')');
-                xml_parser_free($parser_resource);
-                return $r;
-        }
-
-        // gotta get rid of headers here
-        if (!$hdrfnd && ($brpos = strpos($data,"\r\n\r\n"))) {
-            $XML_RPC_xh[$parser]['ha'] = substr($data, 0, $brpos);
-            $data = substr($data, $brpos + 4);
-            $hdrfnd = 1;
-        }
-
-        /*
-         * be tolerant of junk after methodResponse
-         * (e.g. javascript automatically inserted by free hosts)
-         * thanks to Luca Mariano <luca.mariano@email.it>
-         */
-        $data = substr($data, 0, strpos($data, "</methodResponse>") + 17);
-
-        if (!xml_parse($parser_resource, $data, sizeof($data))) {
-            // thanks to Peter Kocks <peter.kocks@baygate.com>
-            if (xml_get_current_line_number($parser_resource) == 1) {
-                $errstr = 'XML error at line 1, check URL';
-            } else {
-                $errstr = sprintf('XML error: %s at line %d',
-                                  xml_error_string(xml_get_error_code($parser_resource)),
-                                  xml_get_current_line_number($parser_resource));
-            }
-            if(defined("DEBUG") && DEBUG) {error_log($errstr);}
-            $r = new XML_RPC_Response(0, $XML_RPC_err['invalid_return'],
-                                      $XML_RPC_str['invalid_return']);
-            xml_parser_free($parser_resource);
-            return $r;
-        }
-
-        xml_parser_free($parser_resource);
-
-        if ($this->debug) {
-            print "\n<pre>---PARSED---\n";
-            var_dump($XML_RPC_xh[$parser]['value']);
-            print "---END---</pre>\n";
-        }
-
-        if ($XML_RPC_xh[$parser]['isf'] > 1) {
-            $r = new XML_RPC_Response(0, $XML_RPC_err['invalid_return'],
-                                      $XML_RPC_str['invalid_return'].' '.$XML_RPC_xh[$parser]['isf_reason']);
-        } elseif (!is_object($XML_RPC_xh[$parser]['value'])) {
-            // then something odd has happened
-            // and it's time to generate a client side error
-            // indicating something odd went on
-            $r = new XML_RPC_Response(0, $XML_RPC_err['invalid_return'],
-                                      $XML_RPC_str['invalid_return']);
-        } else {
-            $v = $XML_RPC_xh[$parser]['value'];
-            $allOK=1;
-            if ($XML_RPC_xh[$parser]['isf']) {
-                $f = $v->structmem('faultCode');
-                $fs = $v->structmem('faultString');
-                $r = new XML_RPC_Response($v, $f->scalarval(),
-                                          $fs->scalarval());
-            } else {
-                $r = new XML_RPC_Response($v);
-            }
-        }
-        $r->hdrs = split("\r?\n", $XML_RPC_xh[$parser]['ha'][1]);
-        return $r;
-    }
-}
-
-/**
- * The methods and properties that represent data in XML RPC format
- *
- * @category   Web Services
- * @package    XML_RPC
- * @author     Edd Dumbill <edd@usefulinc.com>
- * @author     Stig Bakken <stig@php.net>
- * @author     Martin Jansen <mj@php.net>
- * @author     Daniel Convissor <danielc@php.net>
- * @copyright  1999-2001 Edd Dumbill, 2001-2005 The PHP Group
- * @version    Release: 1.4.0
- * @link       http://pear.php.net/package/XML_RPC
- */
-class XML_RPC_Value extends XML_RPC_Base
-{
-    var $me = array();
-    var $mytype = 0;
-
-    /**
-     * @return void
-     */
-    function XML_RPC_Value($val = -1, $type = '')
-    {
-        global $XML_RPC_Types;
-        $this->me = array();
-        $this->mytype = 0;
-        if ($val != -1 || $type != '') {
-            if ($type == '') {
-                $type = 'string';
-            }
-            if (!array_key_exists($type, $XML_RPC_Types)) {
-                // XXX
-                // need some way to report this error
-            } elseif ($XML_RPC_Types[$type] == 1) {
-                $this->addScalar($val, $type);
-            } elseif ($XML_RPC_Types[$type] == 2) {
-                $this->addArray($val);
-            } elseif ($XML_RPC_Types[$type] == 3) {
-                $this->addStruct($val);
-            }
-        }
-    }
-
-    /**
-     * @return int  returns 1 if successful or 0 if there are problems
-     */
-    function addScalar($val, $type = 'string')
-    {
-        global $XML_RPC_Types, $XML_RPC_Boolean;
-
-        if ($this->mytype == 1) {
-            $this->raiseError('Scalar can have only one value',
-                              XML_RPC_ERROR_INVALID_TYPE);
-            return 0;
-        }
-        $typeof = $XML_RPC_Types[$type];
-        if ($typeof != 1) {
-            $this->raiseError("Not a scalar type (${typeof})",
-                              XML_RPC_ERROR_INVALID_TYPE);
-            return 0;
-        }
-
-        if ($type == $XML_RPC_Boolean) {
-            if (strcasecmp($val, 'true') == 0
-                || $val == 1
-                || ($val == true && strcasecmp($val, 'false')))
-            {
-                $val = 1;
-            } else {
-                $val = 0;
-            }
-        }
-
-        if ($this->mytype == 2) {
-            // we're adding to an array here
-            $ar = $this->me['array'];
-            $ar[] = new XML_RPC_Value($val, $type);
-            $this->me['array'] = $ar;
-        } else {
-            // a scalar, so set the value and remember we're scalar
-            $this->me[$type] = $val;
-            $this->mytype = $typeof;
-        }
-        return 1;
-    }
-
-    /**
-     * @return int  returns 1 if successful or 0 if there are problems
-     */
-    function addArray($vals)
-    {
-        global $XML_RPC_Types;
-        if ($this->mytype != 0) {
-            $this->raiseError(
-                    'Already initialized as a [' . $this->kindOf() . ']',
-                    XML_RPC_ERROR_ALREADY_INITIALIZED);
-            return 0;
-        }
-        $this->mytype = $XML_RPC_Types['array'];
-        $this->me['array'] = $vals;
-        return 1;
-    }
-
-    /**
-     * @return int  returns 1 if successful or 0 if there are problems
-     */
-    function addStruct($vals)
-    {
-        global $XML_RPC_Types;
-        if ($this->mytype != 0) {
-            $this->raiseError(
-                    'Already initialized as a [' . $this->kindOf() . ']',
-                    XML_RPC_ERROR_ALREADY_INITIALIZED);
-            return 0;
-        }
-        $this->mytype = $XML_RPC_Types['struct'];
-        $this->me['struct'] = $vals;
-        return 1;
-    }
-
-    /**
-     * @return void
-     */
-    function dump($ar)
-    {
-        reset($ar);
-        foreach ($ar as $key => $val) {
-            echo "$key => $val<br />";
-            if ($key == 'array') {
-                foreach ($val as $key2 => $val2) {
-                    echo "-- $key2 => $val2<br />";
-                }
-            }
-        }
-    }
-
-    /**
-     * @return string  the data type of the current value
-     */
-    function kindOf()
-    {
-        switch ($this->mytype) {
-        case 3:
-            return 'struct';
-
-        case 2:
-            return 'array';
-
-        case 1:
-            return 'scalar';
-
-        default:
-            return 'undef';
-        }
-    }
-
-    /**
-     * @return string  the data in XML format
-     */
-    function serializedata($typ, $val)
-    {
-        $rs = '';
-        global $XML_RPC_Types, $XML_RPC_Base64, $XML_RPC_String, $XML_RPC_Boolean;
-        if (!array_key_exists($typ, $XML_RPC_Types)) {
-            // XXX
-            // need some way to report this error
-            return;
-        }
-        switch ($XML_RPC_Types[$typ]) {
-        case 3:
-            // struct
-            $rs .= "<struct>\n";
-            reset($val);
-            foreach ($val as $key2 => $val2) {
-                $rs .= "<member><name>${key2}</name>\n";
-                $rs .= $this->serializeval($val2);
-                $rs .= "</member>\n";
-            }
-            $rs .= '</struct>';
-            break;
-
-        case 2:
-            // array
-            $rs .= "<array>\n<data>\n";
-            for ($i = 0; $i < sizeof($val); $i++) {
-                $rs .= $this->serializeval($val[$i]);
-            }
-            $rs .= "</data>\n</array>";
-            break;
-
-        case 1:
-            switch ($typ) {
-            case $XML_RPC_Base64:
-                $rs .= "<${typ}>" . base64_encode($val) . "</${typ}>";
-                break;
-            case $XML_RPC_Boolean:
-                $rs .= "<${typ}>" . ($val ? '1' : '0') . "</${typ}>";
-                break;
-            case $XML_RPC_String:
-                $rs .= "<${typ}>" . htmlspecialchars($val). "</${typ}>";
-                break;
-            default:
-                $rs .= "<${typ}>${val}</${typ}>";
-            }
-        }
-        return $rs;
-    }
-
-    /**
-     * @return string  the data in XML format
-     */
-    function serialize()
-    {
-        return $this->serializeval($this);
-    }
-
-    /**
-     * @return string  the data in XML format
-     */
-    function serializeval($o)
-    {
-        if (!is_object($o) || empty($o->me) || !is_array($o->me)) {
-            return '';
-        }
-        $ar = $o->me;
-        reset($ar);
-        list($typ, $val) = each($ar);
-        return '<value>' .  $this->serializedata($typ, $val) .  "</value>\n";
-    }
-
-    /**
-     * @return mixed  the contents of the element requested
-     */
-    function structmem($m)
-    {
-        return $this->me['struct'][$m];
-    }
-
-    /**
-     * @return void
-     */
-    function structreset()
-    {
-        reset($this->me['struct']);
-    }
-
-    /**
-     * @return  the key/value pair of the struct's current element
-     */
-    function structeach()
-    {
-        return each($this->me['struct']);
-    }
-
-    /**
-     * @return mixed  the current value
-     */
-    function getval()
-    {
-        // UNSTABLE
-        global $XML_RPC_BOOLEAN, $XML_RPC_Base64;
-
-        reset($this->me);
-        $b = current($this->me);
-
-        // contributed by I Sofer, 2001-03-24
-        // add support for nested arrays to scalarval
-        // i've created a new method here, so as to
-        // preserve back compatibility
-
-        if (is_array($b)) {
-            foreach ($b as $id => $cont) {
-                $b[$id] = $cont->scalarval();
-            }
-        }
-
-        // add support for structures directly encoding php objects
-        if (is_object($b)) {
-            $t = get_object_vars($b);
-            foreach ($t as $id => $cont) {
-                $t[$id] = $cont->scalarval();
-            }
-            foreach ($t as $id => $cont) {
-                $b->$id = $cont;
-            }
-        }
-
-        // end contrib
-        return $b;
-    }
-
-    /**
-     * @return mixed
-     */
-    function scalarval()
-    {
-        global $XML_RPC_Boolean, $XML_RPC_Base64;
-        reset($this->me);
-        return current($this->me);
-    }
-
-    /**
-     * @return string
-     */
-    function scalartyp()
-    {
-        global $XML_RPC_I4, $XML_RPC_Int;
-        reset($this->me);
-        $a = key($this->me);
-        if ($a == $XML_RPC_I4) {
-            $a = $XML_RPC_Int;
-        }
-        return $a;
-    }
-
-    /**
-     * @return mixed  the struct's current element
-     */
-    function arraymem($m)
-    {
-        return $this->me['array'][$m];
-    }
-
-    /**
-     * @return int  the number of elements in the array
-     */
-    function arraysize()
-    {
-        reset($this->me);
-        list($a, $b) = each($this->me);
-        return sizeof($b);
-    }
-
-    /**
-     * Determines if the item submitted is an XML_RPC_Value object
-     *
-     * @param mixed $val  the variable to be evaluated
-     *
-     * @return bool  TRUE if the item is an XML_RPC_Value object
-     *
-     * @static
-     * @since Method available since Release 1.3.0
-     */
-    function isValue($val)
-    {
-        return (strtolower(get_class($val)) == 'xml_rpc_value');
-    }
-}
-
-/**
- * Return an ISO8601 encoded string
- *
- * While timezones ought to be supported, the XML-RPC spec says:
- *
- * "Don't assume a timezone. It should be specified by the server in its
- * documentation what assumptions it makes about timezones."
- *
- * This routine always assumes localtime unless $utc is set to 1, in which
- * case UTC is assumed and an adjustment for locale is made when encoding.
- *
- * @return string  the formatted date
- */
-function XML_RPC_iso8601_encode($timet, $utc = 0)
-{
-    if (!$utc) {
-        $t = strftime('%Y%m%dT%H:%M:%S', $timet);
-    } else {
-        if (function_exists('gmstrftime')) {
-            // gmstrftime doesn't exist in some versions
-            // of PHP
-            $t = gmstrftime('%Y%m%dT%H:%M:%S', $timet);
-        } else {
-            $t = strftime('%Y%m%dT%H:%M:%S', $timet - date('Z'));
-        }
-    }
-    return $t;
-}
-
-/**
- * Convert a datetime string into a Unix timestamp
- *
- * While timezones ought to be supported, the XML-RPC spec says:
- *
- * "Don't assume a timezone. It should be specified by the server in its
- * documentation what assumptions it makes about timezones."
- *
- * This routine always assumes localtime unless $utc is set to 1, in which
- * case UTC is assumed and an adjustment for locale is made when encoding.
- *
- * @return int  the unix timestamp of the date submitted
- */
-function XML_RPC_iso8601_decode($idate, $utc = 0)
-{
-    $t = 0;
-    if (ereg('([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})', $idate, $regs)) {
-        if ($utc) {
-            $t = gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
-        } else {
-            $t = mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
-        }
-    }
-    return $t;
-}
-
-/**
- * Converts an XML_RPC_Value object into native PHP types
- *
- * @param object $XML_RPC_val  the XML_RPC_Value object to decode
- *
- * @return mixed  the PHP values
- */
-function XML_RPC_decode($XML_RPC_val)
-{
-    $kind = $XML_RPC_val->kindOf();
-
-    if ($kind == 'scalar') {
-        return $XML_RPC_val->scalarval();
-
-    } elseif ($kind == 'array') {
-        $size = $XML_RPC_val->arraysize();
-        $arr = array();
-        for ($i = 0; $i < $size; $i++) {
-            $arr[] = XML_RPC_decode($XML_RPC_val->arraymem($i));
-        }
-        return $arr;
-
-    } elseif ($kind == 'struct') {
-        $XML_RPC_val->structreset();
-        $arr = array();
-        while (list($key, $value) = $XML_RPC_val->structeach()) {
-            $arr[$key] = XML_RPC_decode($value);
-        }
-        return $arr;
-    }
-}
-
-/**
- * Converts native PHP types into an XML_RPC_Value object
- *
- * @param mixed $php_val  the PHP value or variable you want encoded
- *
- * @return object  the XML_RPC_Value object
- */
-function XML_RPC_encode($php_val)
-{
-    global $XML_RPC_Boolean, $XML_RPC_Int, $XML_RPC_Double, $XML_RPC_String,
-           $XML_RPC_Array, $XML_RPC_Struct;
-
-    $type = gettype($php_val);
-    $XML_RPC_val = new XML_RPC_Value;
-
-    switch ($type) {
-    case 'array':
-        if (empty($php_val)) {
-            $XML_RPC_val->addArray($php_val);
-            break;
-        }
-        $tmp = array_diff(array_keys($php_val), range(0, count($php_val)-1));
-        if (empty($tmp)) {
-           $arr = array();
-           foreach ($php_val as $k => $v) {
-               $arr[$k] = XML_RPC_encode($v);
-           }
-           $XML_RPC_val->addArray($arr);
-           break;
-        }
-        // fall though if it's not an enumerated array
-
-    case 'object':
-        $arr = array();
-        foreach ($php_val as $k => $v) {
-            $arr[$k] = XML_RPC_encode($v);
-        }
-        $XML_RPC_val->addStruct($arr);
-        break;
-
-    case 'integer':
-        $XML_RPC_val->addScalar($php_val, $XML_RPC_Int);
-        break;
-
-    case 'double':
-        $XML_RPC_val->addScalar($php_val, $XML_RPC_Double);
-        break;
-
-    case 'string':
-    case 'NULL':
-        $XML_RPC_val->addScalar($php_val, $XML_RPC_String);
-        break;
-
-    case 'boolean':
-        // Add support for encoding/decoding of booleans, since they
-        // are supported in PHP
-        // by <G_Giunta_2001-02-29>
-        $XML_RPC_val->addScalar($php_val, $XML_RPC_Boolean);
-        break;
-
-    case 'unknown type':
-    default:
-        $XML_RPC_val = false;
-    }
-    return $XML_RPC_val;
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * c-hanging-comment-ender-p: nil
- * End:
- */
-
-?>
diff --git a/3rdparty/XML/RPC/Server.php b/3rdparty/XML/RPC/Server.php
deleted file mode 100644 (file)
index 5c5c04b..0000000
+++ /dev/null
@@ -1,624 +0,0 @@
-<?php
-
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * Server commands for our PHP implementation of the XML-RPC protocol
- *
- * This is a PEAR-ified version of Useful inc's XML-RPC for PHP.
- * It has support for HTTP transport, proxies and authentication.
- *
- * PHP versions 4 and 5
- *
- * LICENSE: License is granted to use or modify this software
- * ("XML-RPC for PHP") for commercial or non-commercial use provided the
- * copyright of the author is preserved in any distributed or derivative work.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESSED OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category   Web Services
- * @package    XML_RPC
- * @author     Edd Dumbill <edd@usefulinc.com>
- * @author     Stig Bakken <stig@php.net>
- * @author     Martin Jansen <mj@php.net>
- * @author     Daniel Convissor <danielc@php.net>
- * @copyright  1999-2001 Edd Dumbill, 2001-2005 The PHP Group
- * @version    CVS: $Id: Server.php,v 1.29 2005/08/14 20:25:35 danielc Exp $
- * @link       http://pear.php.net/package/XML_RPC
- */
-
-
-/**
- * Pull in the XML_RPC class
- */
-require_once 'XML/RPC.php';
-
-
-/**
- * signature for system.listMethods: return = array,
- * parameters = a string or nothing
- * @global array $GLOBALS['XML_RPC_Server_listMethods_sig']
- */
-$GLOBALS['XML_RPC_Server_listMethods_sig'] = array(
-    array($GLOBALS['XML_RPC_Array'],
-          $GLOBALS['XML_RPC_String']
-    ),
-    array($GLOBALS['XML_RPC_Array'])
-);
-
-/**
- * docstring for system.listMethods
- * @global string $GLOBALS['XML_RPC_Server_listMethods_doc']
- */
-$GLOBALS['XML_RPC_Server_listMethods_doc'] = 'This method lists all the'
-        . ' methods that the XML-RPC server knows how to dispatch';
-
-/**
- * signature for system.methodSignature: return = array,
- * parameters = string
- * @global array $GLOBALS['XML_RPC_Server_methodSignature_sig']
- */
-$GLOBALS['XML_RPC_Server_methodSignature_sig'] = array(
-    array($GLOBALS['XML_RPC_Array'],
-          $GLOBALS['XML_RPC_String']
-    )
-);
-
-/**
- * docstring for system.methodSignature
- * @global string $GLOBALS['XML_RPC_Server_methodSignature_doc']
- */
-$GLOBALS['XML_RPC_Server_methodSignature_doc'] = 'Returns an array of known'
-        . ' signatures (an array of arrays) for the method name passed. If'
-        . ' no signatures are known, returns a none-array (test for type !='
-        . ' array to detect missing signature)';
-
-/**
- * signature for system.methodHelp: return = string,
- * parameters = string
- * @global array $GLOBALS['XML_RPC_Server_methodHelp_sig']
- */
-$GLOBALS['XML_RPC_Server_methodHelp_sig'] = array(
-    array($GLOBALS['XML_RPC_String'],
-          $GLOBALS['XML_RPC_String']
-    )
-);
-
-/**
- * docstring for methodHelp
- * @global string $GLOBALS['XML_RPC_Server_methodHelp_doc']
- */
-$GLOBALS['XML_RPC_Server_methodHelp_doc'] = 'Returns help text if defined'
-        . ' for the method passed, otherwise returns an empty string';
-
-/**
- * dispatch map for the automatically declared XML-RPC methods.
- * @global array $GLOBALS['XML_RPC_Server_dmap']
- */
-$GLOBALS['XML_RPC_Server_dmap'] = array(
-    'system.listMethods' => array(
-        'function'  => 'XML_RPC_Server_listMethods',
-        'signature' => $GLOBALS['XML_RPC_Server_listMethods_sig'],
-        'docstring' => $GLOBALS['XML_RPC_Server_listMethods_doc']
-    ),
-    'system.methodHelp' => array(
-        'function'  => 'XML_RPC_Server_methodHelp',
-        'signature' => $GLOBALS['XML_RPC_Server_methodHelp_sig'],
-        'docstring' => $GLOBALS['XML_RPC_Server_methodHelp_doc']
-    ),
-    'system.methodSignature' => array(
-        'function'  => 'XML_RPC_Server_methodSignature',
-        'signature' => $GLOBALS['XML_RPC_Server_methodSignature_sig'],
-        'docstring' => $GLOBALS['XML_RPC_Server_methodSignature_doc']
-    )
-);
-
-/**
- * @global string $GLOBALS['XML_RPC_Server_debuginfo']
- */
-$GLOBALS['XML_RPC_Server_debuginfo'] = '';
-
-
-/**
- * Lists all the methods that the XML-RPC server knows how to dispatch
- *
- * @return object  a new XML_RPC_Response object
- */
-function XML_RPC_Server_listMethods($server, $m)
-{
-    global $XML_RPC_err, $XML_RPC_str, $XML_RPC_Server_dmap;
-
-    $v = new XML_RPC_Value();
-    $outAr = array();
-    foreach ($server->dmap as $key => $val) {
-        $outAr[] = new XML_RPC_Value($key, 'string');
-    }
-    foreach ($XML_RPC_Server_dmap as $key => $val) {
-        $outAr[] = new XML_RPC_Value($key, 'string');
-    }
-    $v->addArray($outAr);
-    return new XML_RPC_Response($v);
-}
-
-/**
- * Returns an array of known signatures (an array of arrays)
- * for the given method
- *
- * If no signatures are known, returns a none-array
- * (test for type != array to detect missing signature)
- *
- * @return object  a new XML_RPC_Response object
- */
-function XML_RPC_Server_methodSignature($server, $m)
-{
-    global $XML_RPC_err, $XML_RPC_str, $XML_RPC_Server_dmap;
-
-    $methName = $m->getParam(0);
-    $methName = $methName->scalarval();
-    if (strpos($methName, 'system.') === 0) {
-        $dmap = $XML_RPC_Server_dmap;
-        $sysCall = 1;
-    } else {
-        $dmap = $server->dmap;
-        $sysCall = 0;
-    }
-    //  print "<!-- ${methName} -->\n";
-    if (isset($dmap[$methName])) {
-        if ($dmap[$methName]['signature']) {
-            $sigs = array();
-            $thesigs = $dmap[$methName]['signature'];
-            for ($i = 0; $i < sizeof($thesigs); $i++) {
-                $cursig = array();
-                $inSig = $thesigs[$i];
-                for ($j = 0; $j < sizeof($inSig); $j++) {
-                    $cursig[] = new XML_RPC_Value($inSig[$j], 'string');
-                }
-                $sigs[] = new XML_RPC_Value($cursig, 'array');
-            }
-            $r = new XML_RPC_Response(new XML_RPC_Value($sigs, 'array'));
-        } else {
-            $r = new XML_RPC_Response(new XML_RPC_Value('undef', 'string'));
-        }
-    } else {
-        $r = new XML_RPC_Response(0, $XML_RPC_err['introspect_unknown'],
-                                  $XML_RPC_str['introspect_unknown']);
-    }
-    return $r;
-}
-
-/**
- * Returns help text if defined for the method passed, otherwise returns
- * an empty string
- *
- * @return object  a new XML_RPC_Response object
- */
-function XML_RPC_Server_methodHelp($server, $m)
-{
-    global $XML_RPC_err, $XML_RPC_str, $XML_RPC_Server_dmap;
-
-    $methName = $m->getParam(0);
-    $methName = $methName->scalarval();
-    if (strpos($methName, 'system.') === 0) {
-        $dmap = $XML_RPC_Server_dmap;
-        $sysCall = 1;
-    } else {
-        $dmap = $server->dmap;
-        $sysCall = 0;
-    }
-
-    if (isset($dmap[$methName])) {
-        if ($dmap[$methName]['docstring']) {
-            $r = new XML_RPC_Response(new XML_RPC_Value($dmap[$methName]['docstring']),
-                                                        'string');
-        } else {
-            $r = new XML_RPC_Response(new XML_RPC_Value('', 'string'));
-        }
-    } else {
-        $r = new XML_RPC_Response(0, $XML_RPC_err['introspect_unknown'],
-                                     $XML_RPC_str['introspect_unknown']);
-    }
-    return $r;
-}
-
-/**
- * @return void
- */
-function XML_RPC_Server_debugmsg($m)
-{
-    global $XML_RPC_Server_debuginfo;
-    $XML_RPC_Server_debuginfo = $XML_RPC_Server_debuginfo . $m . "\n";
-}
-
-
-/**
- * A server for receiving and replying to XML RPC requests
- *
- * <code>
- * $server = new XML_RPC_Server(
- *     array(
- *         'isan8' =>
- *             array(
- *                 'function' => 'is_8',
- *                 'signature' =>
- *                      array(
- *                          array('boolean', 'int'),
- *                          array('boolean', 'int', 'boolean'),
- *                          array('boolean', 'string'),
- *                          array('boolean', 'string', 'boolean'),
- *                      ),
- *                 'docstring' => 'Is the value an 8?'
- *             ),
- *     ),
- *     1,
- *     0
- * ); 
- * </code>
- *
- * @category   Web Services
- * @package    XML_RPC
- * @author     Edd Dumbill <edd@usefulinc.com>
- * @author     Stig Bakken <stig@php.net>
- * @author     Martin Jansen <mj@php.net>
- * @author     Daniel Convissor <danielc@php.net>
- * @copyright  1999-2001 Edd Dumbill, 2001-2005 The PHP Group
- * @version    Release: 1.4.0
- * @link       http://pear.php.net/package/XML_RPC
- */
-class XML_RPC_Server
-{
-    /**
-     * The dispatch map, listing the methods this server provides.
-     * @var array
-     */
-    var $dmap = array();
-
-    /**
-     * The present response's encoding
-     * @var string
-     * @see XML_RPC_Message::getEncoding()
-     */
-    var $encoding = '';
-
-    /**
-     * Debug mode (0 = off, 1 = on)
-     * @var integer
-     */
-    var $debug = 0;
-
-    /**
-     * The response's HTTP headers
-     * @var string
-     */
-    var $server_headers = '';
-
-    /**
-     * The response's XML payload
-     * @var string
-     */
-    var $server_payload = '';
-
-
-    /**
-     * Constructor for the XML_RPC_Server class
-     *
-     * @param array $dispMap   the dispatch map. An associative array
-     *                          explaining each function. The keys of the main
-     *                          array are the procedure names used by the
-     *                          clients. The value is another associative array
-     *                          that contains up to three elements:
-     *                            + The 'function' element's value is the name
-     *                              of the function or method that gets called.
-     *                              To define a class' method: 'class::method'.
-     *                            + The 'signature' element (optional) is an
-     *                              array describing the return values and
-     *                              parameters
-     *                            + The 'docstring' element (optional) is a
-     *                              string describing what the method does
-     * @param int $serviceNow  should the HTTP response be sent now?
-     *                          (1 = yes, 0 = no)
-     * @param int $debug       should debug output be displayed?
-     *                          (1 = yes, 0 = no)
-     *
-     * @return void
-     */
-    function XML_RPC_Server($dispMap, $serviceNow = 1, $debug = 0)
-    {
-        global $HTTP_RAW_POST_DATA;
-
-        if ($debug) {
-            $this->debug = 1;
-        } else {
-            $this->debug = 0;
-        }
-
-        $this->dmap = $dispMap;
-
-        if ($serviceNow) {
-            $this->service();
-        } else {
-            $this->createServerPayload();
-            $this->createServerHeaders();
-        }
-    }
-
-    /**
-     * @return string  the debug information if debug debug mode is on
-     */
-    function serializeDebug()
-    {
-        global $XML_RPC_Server_debuginfo, $HTTP_RAW_POST_DATA;
-
-        if ($this->debug) {
-            XML_RPC_Server_debugmsg('vvv POST DATA RECEIVED BY SERVER vvv' . "\n"
-                                    . $HTTP_RAW_POST_DATA
-                                    . "\n" . '^^^ END POST DATA ^^^');
-        }
-
-        if ($XML_RPC_Server_debuginfo != '') {
-            return "<!-- PEAR XML_RPC SERVER DEBUG INFO:\n\n"
-                   . preg_replace('/-(?=-)/', '- ', $XML_RPC_Server_debuginfo)
-                   . "-->\n";
-        } else {
-            return '';
-        }
-    }
-
-    /**
-     * Sends the response
-     *
-     * The encoding and content-type are determined by
-     * XML_RPC_Message::getEncoding()
-     *
-     * @return void
-     *
-     * @uses XML_RPC_Server::createServerPayload(),
-     *       XML_RPC_Server::createServerHeaders()
-     */
-    function service()
-    {
-        if (!$this->server_payload) {
-            $this->createServerPayload();
-        }
-        if (!$this->server_headers) {
-            $this->createServerHeaders();
-        }
-        header($this->server_headers);
-        print $this->server_payload;
-    }
-
-    /**
-     * Generates the payload and puts it in the $server_payload property
-     *
-     * @return void
-     *
-     * @uses XML_RPC_Server::parseRequest(), XML_RPC_Server::$encoding,
-     *       XML_RPC_Response::serialize(), XML_RPC_Server::serializeDebug()
-     */
-    function createServerPayload()
-    {
-        $r = $this->parseRequest();
-        $this->server_payload = '<?xml version="1.0" encoding="'
-                              . $this->encoding . '"?>' . "\n"
-                              . $this->serializeDebug()
-                              . $r->serialize();
-    }
-
-    /**
-     * Determines the HTTP headers and puts them in the $server_headers
-     * property
-     *
-     * @return boolean  TRUE if okay, FALSE if $server_payload isn't set.
-     *
-     * @uses XML_RPC_Server::createServerPayload(),
-     *       XML_RPC_Server::$server_headers
-     */
-    function createServerHeaders()
-    {
-        if (!$this->server_payload) {
-            return false;
-        }
-        $this->server_headers = 'Content-Length: '
-                              . strlen($this->server_payload) . "\r\n"
-                              . 'Content-Type: text/xml;'
-                              . ' charset=' . $this->encoding;
-        return true;
-    }
-
-    /**
-     * @return array
-     */
-    function verifySignature($in, $sig)
-    {
-        for ($i = 0; $i < sizeof($sig); $i++) {
-            // check each possible signature in turn
-            $cursig = $sig[$i];
-            if (sizeof($cursig) == $in->getNumParams() + 1) {
-                $itsOK = 1;
-                for ($n = 0; $n < $in->getNumParams(); $n++) {
-                    $p = $in->getParam($n);
-                    // print "<!-- $p -->\n";
-                    if ($p->kindOf() == 'scalar') {
-                        $pt = $p->scalartyp();
-                    } else {
-                        $pt = $p->kindOf();
-                    }
-                    // $n+1 as first type of sig is return type
-                    if ($pt != $cursig[$n+1]) {
-                        $itsOK = 0;
-                        $pno = $n+1;
-                        $wanted = $cursig[$n+1];
-                        $got = $pt;
-                        break;
-                    }
-                }
-                if ($itsOK) {
-                    return array(1);
-                }
-            }
-        }
-        if (isset($wanted)) {
-            return array(0, "Wanted ${wanted}, got ${got} at param ${pno}");
-        } else {
-            $allowed = array();
-            foreach ($sig as $val) {
-                end($val);
-                $allowed[] = key($val);
-            }
-            $allowed = array_unique($allowed);
-            $last = count($allowed) - 1;
-            if ($last > 0) {
-                $allowed[$last] = 'or ' . $allowed[$last];
-            }
-            return array(0,
-                         'Signature permits ' . implode(', ', $allowed)
-                                . ' parameters but the request had '
-                                . $in->getNumParams());
-        }
-    }
-
-    /**
-     * @return object  a new XML_RPC_Response object
-     *
-     * @uses XML_RPC_Message::getEncoding(), XML_RPC_Server::$encoding
-     */
-    function parseRequest($data = '')
-    {
-        global $XML_RPC_xh, $HTTP_RAW_POST_DATA,
-                $XML_RPC_err, $XML_RPC_str, $XML_RPC_errxml,
-                $XML_RPC_defencoding, $XML_RPC_Server_dmap;
-
-        if ($data == '') {
-            $data = $HTTP_RAW_POST_DATA;
-        }
-
-        $this->encoding = XML_RPC_Message::getEncoding($data);
-        $parser_resource = xml_parser_create($this->encoding);
-        $parser = (int) $parser_resource;
-
-        $XML_RPC_xh[$parser] = array();
-        $XML_RPC_xh[$parser]['cm']     = 0;
-        $XML_RPC_xh[$parser]['isf']    = 0;
-        $XML_RPC_xh[$parser]['params'] = array();
-        $XML_RPC_xh[$parser]['method'] = '';
-        $XML_RPC_xh[$parser]['stack'] = array();       
-        $XML_RPC_xh[$parser]['valuestack'] = array();  
-
-        $plist = '';
-
-        // decompose incoming XML into request structure
-
-        xml_parser_set_option($parser_resource, XML_OPTION_CASE_FOLDING, true);
-        xml_set_element_handler($parser_resource, 'XML_RPC_se', 'XML_RPC_ee');
-        xml_set_character_data_handler($parser_resource, 'XML_RPC_cd');
-        if (!xml_parse($parser_resource, $data, 1)) {
-            // return XML error as a faultCode
-            $r = new XML_RPC_Response(0,
-                                      $XML_RPC_errxml+xml_get_error_code($parser_resource),
-                                      sprintf('XML error: %s at line %d',
-                                              xml_error_string(xml_get_error_code($parser_resource)),
-                                              xml_get_current_line_number($parser_resource)));
-            xml_parser_free($parser_resource);
-        } elseif ($XML_RPC_xh[$parser]['isf']>1) {
-            $r = new XML_RPC_Response(0,
-                                      $XML_RPC_err['invalid_request'],
-                                      $XML_RPC_str['invalid_request']
-                                      . ': '
-                                      . $XML_RPC_xh[$parser]['isf_reason']);
-            xml_parser_free($parser_resource);
-        } else {
-            xml_parser_free($parser_resource);
-            $m = new XML_RPC_Message($XML_RPC_xh[$parser]['method']);
-            // now add parameters in
-            for ($i = 0; $i < sizeof($XML_RPC_xh[$parser]['params']); $i++) {
-                // print '<!-- ' . $XML_RPC_xh[$parser]['params'][$i]. "-->\n";
-                $plist .= "$i - " . var_export($XML_RPC_xh[$parser]['params'][$i], true) . " \n";
-                $m->addParam($XML_RPC_xh[$parser]['params'][$i]);
-            }
-            XML_RPC_Server_debugmsg($plist);
-
-            // now to deal with the method
-            $methName = $XML_RPC_xh[$parser]['method'];
-            if (strpos($methName, 'system.') === 0) {
-                $dmap = $XML_RPC_Server_dmap;
-                $sysCall = 1;
-            } else {
-                $dmap = $this->dmap;
-                $sysCall = 0;
-            }
-
-            if (isset($dmap[$methName]['function'])
-                && is_string($dmap[$methName]['function'])
-                && strpos($dmap[$methName]['function'], '::') !== false)
-            {
-                $dmap[$methName]['function'] =
-                        explode('::', $dmap[$methName]['function']);
-            }
-
-            if (isset($dmap[$methName]['function'])
-                && is_callable($dmap[$methName]['function']))
-            {
-                // dispatch if exists
-                if (isset($dmap[$methName]['signature'])) {
-                    $sr = $this->verifySignature($m,
-                                                 $dmap[$methName]['signature'] );
-                }
-                if (!isset($dmap[$methName]['signature']) || $sr[0]) {
-                    // if no signature or correct signature
-                    if ($sysCall) {
-                        $r = call_user_func($dmap[$methName]['function'], $this, $m);
-                    } else {
-                        $r = call_user_func($dmap[$methName]['function'], $m);
-                    }
-                    if (!is_a($r, 'XML_RPC_Response')) {
-                        $r = new XML_RPC_Response(0, $XML_RPC_err['not_response_object'],
-                                                  $XML_RPC_str['not_response_object']);
-                    }
-                } else {
-                    $r = new XML_RPC_Response(0, $XML_RPC_err['incorrect_params'],
-                                              $XML_RPC_str['incorrect_params']
-                                              . ': ' . $sr[1]);
-                }
-            } else {
-                // else prepare error response
-                $r = new XML_RPC_Response(0, $XML_RPC_err['unknown_method'],
-                                          $XML_RPC_str['unknown_method']);
-            }
-        }
-        return $r;
-    }
-
-    /**
-     * Echos back the input packet as a string value
-     *
-     * @return void
-     *
-     * Useful for debugging.
-     */
-    function echoInput()
-    {
-        global $HTTP_RAW_POST_DATA;
-
-        $r = new XML_RPC_Response(0);
-        $r->xv = new XML_RPC_Value("'Aha said I: '" . $HTTP_RAW_POST_DATA, 'string');
-        print $r->serialize();
-    }
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * c-hanging-comment-ender-p: nil
- * End:
- */
-
-?>