Source for file MDB2.php
Documentation is available at MDB2.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 |
// | 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 $
* @author Lukas Smith <smith@pooteeweet.org>
* 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_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 );
* 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
* @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 (
* 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
* +-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
* @author Lukas Smith <smith@pooteeweet.org>
// {{{ 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
foreach ($options as $option => $value) {
$test = $db->setOption ($option, $value);
if (PEAR ::isError ($test)) {
// {{{ function classExists($classname)
* Checks if a class exists without triggering __autoload
* @param string classname
* @return bool true success and false on error
// {{{ function loadClass($class_name, $debug)
* @param string classname to load
* @param bool if errors should be suppressed
* @return mixed true success or PEAR_Error on failure
$file_name = str_replace('_', DIRECTORY_SEPARATOR , $class_name). '.php';
$include = include_once($file_name);
$include = @include_once($file_name);
$msg = " unable to find package '$class_name' file '$file_name'";
$msg = " unable to load class '$class_name' from file '$file_name'";
// {{{ 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).
* $db =& MDB2::factory($dsn);
* $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
* @return mixed a newly created MDB2 object, or false on error
function &factory($dsn, $options = false )
if (empty ($dsninfo['phptype'])) {
null , null , 'no RDBMS driver specified');
$class_name = 'MDB2_Driver_'. $dsninfo['phptype'];
$debug = (!empty ($options['debug']));
if (PEAR ::isError ($err)) {
$db = & new $class_name();
if (PEAR ::isError ($err)) {
// {{{ function &connect($dsn, $options = false)
* Create a new MDB2_Driver_* connection object and connect to the specified
* 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).
* $db =& MDB2::connect($dsn);
* $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
* @return mixed a newly created MDB2 connection object, or a MDB2
function &connect($dsn, $options = false )
if (PEAR ::isError ($db)) {
if (PEAR ::isError ($err)) {
$dsn = $db->getDSN ('string', 'xxx');
// {{{ 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).
* $db =& MDB2::singleton($dsn);
* $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
* @return mixed a newly created MDB2 connection object, or a MDB2
function &singleton($dsn = null , $options = false )
$dsninfo = array_merge($GLOBALS['_MDB2_dsninfo_default'], $dsninfo);
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');
return $GLOBALS['_MDB2_databases'][$keys[$i]];
} elseif (is_array($GLOBALS['_MDB2_databases']) && reset($GLOBALS['_MDB2_databases'])) {
$db = & $GLOBALS['_MDB2_databases'][key($GLOBALS['_MDB2_databases'])];
// {{{ 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
// {{{ 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
$file_name = 'MDB2'.DIRECTORY_SEPARATOR. $file. '.php';
'unable to find: '. $file_name);
if (!include_once($file_name)) {
'unable to load driver class: '. $file_name);
// {{{ function apiVersion()
* Return the MDB2 API version
* @return string the MDB2 API version number
// {{{ 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
* @param string Extra debug information. Defaults to the last
* query and native error code.
* @return PEAR_Error instance of a PEAR Error object
function &raiseError ($code = null ,
$err = & PEAR ::raiseError (null , $code, $mode, $options, $userinfo, 'MDB2_Error', true );
// {{{ 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
function isError($data, $code = null )
if (is_a($data, 'MDB2_Error')) {
return $data->getMessage () === $code;
return in_array($data->getCode (), $code);
// {{{ function isConnection($value)
* Tell whether a value is a MDB2 connection
* @param mixed value to test
* @return bool whether $value is a MDB2 connection
return is_a($value, '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
return is_a($value, '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
return is_a($value, '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
return is_a($value, '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
if (!isset ($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
* The format of the supplied DSN is in its fullest form:
* phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
* Most variations are allowed:
* 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
* @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
* @author Tomas V.V.Cox <cox@idecnet.com>
$parsed = $GLOBALS['_MDB2_dsninfo_default'];
$dsn['dbsyntax'] = $dsn['phptype'];
// Find phptype and dbsyntax
if (($pos = strpos($dsn, '://')) !== false ) {
$dsn = substr($dsn, $pos + 3 );
// Get phptype and dbsyntax
// $str => phptype(dbsyntax)
if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
$parsed['phptype'] = $arr[1 ];
$parsed['dbsyntax'] = !$arr[2 ] ? $arr[1 ] : $arr[2 ];
$parsed['phptype'] = $str;
$parsed['dbsyntax'] = $str;
// Get (if found): username and password
// $dsn => username:password@protocol+hostspec/database
if (($at = strrpos($dsn,'@')) !== false ) {
if (($pos = strpos($str, ':')) !== false ) {
// Find protocol and hostspec
// $dsn => proto(proto_opts)/database
if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
$proto_opts = $match[2 ] ? $match[2 ] : false;
// $dsn => protocol+hostspec/database (old format)
if (strpos($dsn, '+') !== false ) {
list ($proto, $dsn) = explode('+', $dsn, 2 );
&& 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"
} elseif (strpos($dsn, '/') !== false ) {
list ($proto_opts, $dsn) = explode('/', $dsn, 2 );
// process the different protocol options
$parsed['protocol'] = (!empty ($proto)) ? $proto : 'tcp';
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;
if (($pos = strpos($dsn, '?')) === false ) {
$parsed['database'] = $dsn;
// /database?param1=value1¶m2=value2
$parsed['database'] = substr($dsn, 0 , $pos);
$dsn = substr($dsn, $pos + 1 );
if (strpos($dsn, '&') !== false ) {
} else { // database?param1=value1
foreach ($opts as $opt) {
list ($key, $value) = explode('=', $opt);
if (!isset ($parsed[$key])) {
// don't allow params overwrite
// {{{ function fileExists($file)
* Checks if a file exists in the include path
* @return bool true success and false on error
// safe_mode does notwork with is_readable()
foreach ($dirs as $dir) {
$fp = @fopen($file, 'r', true );
// {{{ class MDB2_Error extends PEAR_Error
* MDB2_Error implements a class for reporting portable database error
* @author Stig Bakken <ssb@fast.no>
// {{{ 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 & PEAR_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 )
$mode, $level, $debuginfo);
// {{{ class MDB2_Driver_Common extends PEAR
* MDB2_Driver_Common: Base class that is extended by each MDB2 driver
* @author Lukas Smith <smith@pooteeweet.org>
// {{{ Variables (Properties)
* index of the MDB2 object within the $GLOBALS['_MDB2_databases'] array
* DSN used for the next query
* DSN that was used to create the current connection
* if the current opened connection is a persistent connection
* the name of the database for the next query
* the name of the database currently selected
* server version information
* list of all supported features of the given driver
'affected_rows' => false ,
'summary_functions' => false ,
'order_by_text' => false ,
'limit_queries' => false ,
'auto_increment' => false ,
'result_introspection' => false ,
'prepared_statements' => false ,
'identifier_quoting' => false ,
'pattern_escaping' => 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:
* <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>
* @see MDB2_Driver_Common::setOption()
'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',
'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 ,
'portability' => MDB2_PORTABILITY_ALL ,
'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',
var $string_quoting = array ('start' => "'", 'end' => "'", 'escape' => false , 'escape_pattern' => false );
array ('start' => '--', 'end' => "\n", 'escape' => false ),
array ('start' => '/*', 'end' => '*/', 'escape' => false ),
* string with the debugging information
* determine if there is an open transaction
* the smart transaction nesting depth
* the first error that occured inside a nested transaction
* result offset used in the next query
* result limit used in the next query
* Database backend used in PHP (mysql, odbc etc.)
* Database used with regards to SQL syntax etc.
* the last query sent to the driver
* the default fetchmode used
* array of module instances
* determines of the PHP4 destructor emulation has been enabled yet
// {{{ constructor: function __construct()
end($GLOBALS['_MDB2_databases']);
$db_index = key($GLOBALS['_MDB2_databases']) + 1;
$GLOBALS['_MDB2_databases'][$db_index] = &$this;
// {{{ function MDB2_Driver_Common()
// {{{ destructor: function __destruct()
* Free the internal references so that the instance can be destroyed
* @return bool true on success, false if result is invalid
unset ($GLOBALS['_MDB2_databases'][$this->db_index]);
// {{{ function __toString()
* @return string representation of the object
$info.= ': (phptype = '. $this->phptype. ', dbsyntax = '. $this->dbsyntax. ')';
// {{{ 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
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
* @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
* @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
$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;
$userinfo = $code->getUserinfo ();
$code = $code->getCode ();
// extension not loaded: don't call $this->errorInfo() or the script
$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";
$userinfo = $method.': '.$userinfo;
$err =& PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
if ($err->getMode () !== PEAR_ERROR_RETURN
// {{{ function resetWarnings()
* reset the warning 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
// {{{ function setFetchMode($fetchmode, $object_class = 'stdClass')
* Sets which fetch mode should be used by default on queries
* @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
* @see MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC, MDB2_FETCHMODE_OBJECT
function setFetchMode($fetchmode, $object_class = 'stdClass')
case MDB2_FETCHMODE_OBJECT:
$this->options['fetch_class'] = $object_class;
case MDB2_FETCHMODE_ORDERED:
case MDB2_FETCHMODE_ASSOC:
return $this->raiseError(MDB2_ERROR_UNSUPPORTED , null , null ,
'invalid fetchmode mode', __FUNCTION__ );
// {{{ 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
function setOption($option, $value)
if (array_key_exists($option, $this->options)) {
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
function getOption($option)
if (array_key_exists($option, $this->options)) {
return $this->raiseError(MDB2_ERROR_UNSUPPORTED , null , null ,
"unknown option $option", __FUNCTION__);
// {{{ function debug($message, $scope = '', $is_manip = null)
* @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.
function debug($message, $scope = '', $context = array())
if (!$this->options['debug_expanded_output']) {
if (!empty($context['when']) && $context['when'] !== 'pre') {
$context = empty($context['is_manip']) ? false : $context['is_manip'];
return call_user_func_array($this->options['debug_handler'], array (&$this, $scope, $message, $context));
// {{{ function getDebugOutput()
* @return string content of the debug_output class variable
function getDebugOutput()
// {{{ 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
function escape($text, $escape_wildcards = false)
// {{{ function escapePattern($text)
* Quotes pattern (% and _) characters in a string)
* @param string the input string to quote
* @return string quoted string
function escapePattern($text)
$text = str_replace($wildcard, $this->string_quoting['escape_pattern'] . $wildcard, $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
* Portability is broken by using the following characters inside
* + 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
* 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
function quoteIdentifier($str, $check_option = false)
if ($check_option && !$this->options['quote_identifier']) {
$parts = explode ('.', $str);
foreach (array_keys ($parts) as $k) {
return implode('.', $parts);
// {{{ function getAsKeyword()
* Gets the string to alias column
* @return string to use when aliasing a column
// {{{ function getConnection()
* Returns a native connection
* @return mixed a valid MDB2 connection object,
* or a MDB2 error object on error
if (PEAR ::isError ($result)) {
// {{{ 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
function _fixResultArrayValues(&$row, $mode)
case MDB2_PORTABILITY_EMPTY_TO_NULL:
foreach ($row as $key => $value) {
case MDB2_PORTABILITY_RTRIM:
foreach ($row as $key => $value) {
$row[$key] = rtrim($value);
case MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES:
foreach ($row as $key => $value) {
$tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL):
foreach ($row as $key => $value) {
} elseif (is_string($value)) {
$row[$key] = rtrim($value);
case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
foreach ($row as $key => $value) {
$tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
case (MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
foreach ($row as $key => $value) {
$tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
foreach ($row as $key => $value) {
} elseif (is_string($value)) {
$tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
// {{{ function &loadModule($module, $property = null, $phptype_specific = null)
* @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
* @return object on success a reference to the given module is returned
* and on failure a PEAR error
function &loadModule($module, $property = null, $phptype_specific = null)
$property = strtolower($module);
if (!isset($this->{$property})) {
$version = $phptype_specific;
if ($phptype_specific !== false) {
$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))
$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)) {
// load module in a specific 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)) {
if (!MDB2::classExists($class_name)) {
$err =& $this->raiseError(MDB2_ERROR_LOADMODULE , null , null ,
"unable to load module '$module' into property '$property'", __FUNCTION__);
$this->{$property} = new $class_name($this->db_index);
$this->modules[$module] = & $this->{$property};
// 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)
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])) {
if (PEAR ::isError ($result)) {
foreach ($this->modules as $key => $foo) {
if (is_object($this->modules[$key])
&& method_exists ($this->modules[$key], $method)
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
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
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
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
function inTransaction($ignore_nested = false)
// {{{ 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
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
function beginNestedTransaction()
if ($this->supports('savepoints') && $savepoint) {
// {{{ function completeNestedTransaction($force_rollback = false, $release = false)
* Finish a nested transaction by rolling back if an error occured or
* @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
function completeNestedTransaction($force_rollback = false)
if ($this->supports('savepoints') && $savepoint) {
if (!PEAR ::isError ($result)) {
$result = $this->commit($savepoint);
// transaction has not yet been rolled back
if (!PEAR ::isError ($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
function failNestedTransaction($error = null, $immediately = false)
// {{{ function getNestedTransactionError()
* The first error that occured since the transaction start.
* @return MDB2_Error|bool MDB2 error object if an error occured or false.
function getNestedTransactionError()
* Connect to the database
* @return true on success, MDB2 Error Object on failure
return $this->raiseError(MDB2_ERROR_UNSUPPORTED , null , null ,
'method not implemented', __FUNCTION__ );
* 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
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 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
function disconnect($force = true)
// {{{ 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
function setDatabase($name)
return $previous_database_name;
// {{{ function getDatabase()
* Get the current database
* @return string name of the database
// {{{ function setDSN($dsn)
* @param mixed DSN string or array
$dsn_default = $GLOBALS['_MDB2_dsninfo_default'];
$dsn = MDB2::parseDSN($dsn);
if (array_key_exists('database', $dsn)) {
$this->dsn = array_merge ($dsn_default, $dsn);
// {{{ 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
function getDSN($type = 'string', $hidepw = false)
$dsn = array_merge($GLOBALS['_MDB2_dsninfo_default'], $this->dsn);
$dsn['password'] = $hidepw;
// expand to include all possible options
($dsn['dbsyntax'] ? ('('.$dsn['dbsyntax'].')') : '').
'://'.$dsn['username'].':'.
$dsn['password'].'@'.$dsn['hostspec'].
($dsn['port'] ? (':'.$dsn['port']) : '').
* Check if the 'new_link' option is set
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
* @param bool if the query is a manipulation query
* @return mixed MDB2_OK on success, a MDB2 error on failure
function &standaloneQuery($query, $types = null, $is_manip = false)
$query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
if (PEAR ::isError ($connection)) {
$result =& $this->_doQuery($query, $is_manip, $connection
|