Source for file BitDbBase.php
Documentation is available at BitDbBase.php
* ADOdb Library interface Class
* @version $Header: /cvsroot/bitweaver/_bit_kernel/BitDbBase.php,v 1.36 2007/02/15 09:15:38 phoenixandy Exp $
* Copyright (c) 2004 bitweaver.org
* Copyright (c) 2003 tikwiki.org
* Copyright (c) 2002-2003, Luis Argerich, Garland Foster, Eduardo Polidor, et. al.
* All Rights Reserved. See copyright.txt for details and a complete list of authors.
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details
* @author spider <spider@steelsun.com>
* ensure your AdoDB install is a subdirectory off your include path
require_once( KERNEL_PKG_PATH. 'bit_error_inc.php' );
define( 'BIT_QUERY_DEFAULT', - 1 );
* This class is used for database access and provides a number of functions to help
* with database portability.
* Currently used as a base class, this class should be optional to ensure bitweaver
* continues to function correctly, without a valid database connection.
* Used to store the ADODB db object used to access the database.
* This is just a pointer to a single global variable used by all classes.
* This limits database connections to just one per request.
* Used to identify the ADODB db object
* Used to store the ADODB db object type
* Used to store failed commands
* Used to store the number of queries executed.
* Used to store the total query time for this request.
* Case sensitivity flag used in convertQuery
* Used to enable AdoDB caching
* Used to determine SQL debug output. BitDbAdodb overrides associated methods to use the debugging mechanisms built into ADODB
* Determines if fatal query functions should terminate script execution. Defaults to TRUE. Can be deactived for things like expected duplicate inserts
* During initialisation, database parameters are passed to the class.
* If these parameters are not valid, class will not be initialised.
global $gBitDbCaseSensitivity;
* This function contains any pre-connection work
* @todo investigate if this is the correct way to do it.
if(isset ($this->mType)) {
// we have a db we're gonna try to load
// avoid database change messages
ini_set("sybct.min_server_severity", "11");
die("No database type specified");
* This function contains any post-connection work
* @todo investigate if this is the correct way to do it.
* @todo remove the BIT_DB_PREFIX, change to a member variable
* @todo get spiderr to explain the schema line
$this->mDb->Execute("set quoted_identifier on");
$this->mDb->Execute("set session sql_mode='PIPES_AS_CONCAT'");
// Do a little prep work for postgres, no break, cause we want default case too
// Assume we want to dump in a schema, so set the search path and nuke the prefix here.
// $result = $this->mDb->Execute( "SET search_path TO $schema,public" );
* Determines if the database connection is valid
* @return true if DB connection is valid, false if not
return( !empty( $this->mDb ) );
* Determines if the database connection is valid
* @return true if DB connection is valid, false if not
* Determines if the database connection is valid
* @return true if DB connection is valid, false if not
* Used to start query timer if in debug mode
$this->mQueryLap = $gBitTimer->elapsed();
/** will activate ADODB like native debugging output
* @param pLevel debugging level - FALSE is off, TRUE is on, 99 is verbose
function debug( $pLevel= 99 ) {
/** returns the level of query debugging output
* @return pLevel debugging level - FALSE is off, TRUE is on, 99 is verbose
* Sets the case sensitivity mode which is used in convertQuery
* @return true if DB connection is valid, false if not
* Sets the case sensitivity mode which is used in convertQuery
* @return true if DB connection is valid, false if not
// Force Oracle to always be insensitive
* Used to stop query tracking and output results if in debug mode
//count the number of queries made
$interval = $gBitTimer->elapsed() - $this->mQueryLap;
$style = ( $interval > .5 ) ? 'color:red;' : (( $interval > .15 ) ? 'color:orange;' : '');
print '<p style="'. $style. '">### Query: '. $num_queries. ' Start time: '. $this->mQueryLap. ' ### Query run time: '. $interval. '</p>';
* Used to create tables - most commonly from package/schema_inc.php files
* @todo remove references to BIT_DB_PREFIX, us a member function
* @param pTables an array of tables and creation information in DataDict
* @param pOptions an array of options used while creating the tables
* true if created with no errors | false if errors are stored in $this->mFailed
* Used to check if tables already exists.
* @todo should be used to confirm tables are already created
* @param pTable the table name
* @return true if table already exists
* @todo remove references to BIT_DB_PREFIX, us a member function
* @param pTables an array of table names to drop
* true if dropped with no errors |
* false if errors are stored in $this->mFailed
* Function to set ADODB query caching member variable
* @param pCacheExecute flag to enable or disable ADODB query caching
* Function to set ADODB query caching member variable
* @param pCacheExecute flag to enable or disable ADODB query caching
* Quotes a string to be sent to the database
* @param pStr string to be quotes
* @return quoted string using AdoDB->qstr()
/** Queries the database, returning an error if one occurs, rather
* than exiting while printing the error. -rlpowell
* @param pQuery the SQL query. Use backticks (`) to quote all table
* and attribute names for AdoDB to quote appropriately.
* @param pError the error string to modify and return
* @param pValues an array of values used in a parameterised query
* @param pNumRows the number of rows (LIMIT) to return in this query
* @param pOffset the row number to begin returning rows from. Used in
* @return an AdoDB RecordSet object
* conjunction with $pNumRows
* @todo currently not used anywhere.
function queryError( $pQuery, &$pError, $pValues = NULL, $pNumRows = - 1, $pOffset = - 1 ) {
/** Queries the database reporting an error if detected
* than exiting while printing the error. -rlpowell
* @param pQuery the SQL query. Use backticks (`) to quote all table
* and attribute names for AdoDB to quote appropriately.
* @param pValues an array of values used in a parameterised query
* @param pNumRows the number of rows (LIMIT) to return in this query
* @param pOffset the row number to begin returning rows from. Used in
* conjunction with $pNumRows
* @return an AdoDB RecordSet object
function query($query, $values = null, $numrows = BIT_QUERY_DEFAULT, $offset = BIT_QUERY_DEFAULT, $pCacheTime= BIT_QUERY_DEFAULT ) {
* ADODB compatibility functions for bitcommerce
function Execute($pQuery, $pNumRows = false, $zf_cache = false, $pCacheTime= BIT_QUERY_DEFAULT) {
if ( $this->mType == "firebird") {
return $this->query( $pQuery, NULL, $pNumRows, NULL, $pCacheTime );
* Create a list of tables available in the current database
* @param ttype can either be 'VIEW' or 'TABLE' or false.
* If false, both views and tables are returned.
* "VIEW" returns only views
* "TABLE" returns only tables
* @param showSchema returns the schema/user with the table name, eg. USER.TABLE
* @param mask is the input mask - only supported by oci8 and postgresql
* @return array of tables for current database.
function MetaTables( $ttype = false, $showSchema = false, $mask= false ) {
* List columns in a database as an array of ADOFieldObjects.
* See top of file for definition of object.
* @param table table name to query
* @param upper uppercase table name (required by some databases)
* @param schema is optional database schema to use - not supported by all databases.
* @return array of ADOFieldObjects for current table.
function MetaColumns($table,$normalize= true, $schema= false) {
* List indexes in a database as an array of ADOFieldObjects.
* See top of file for definition of object.
* @param table table name to query
* @param primary list primary indexes
* @param owner list owner of index
* @return array of ADOFieldObjects for current table.
function MetaIndexes($table,$primary= false, $owner= false) {
/** Executes the SQL and returns all elements of the first column as a 1-dimensional array. The recordset is discarded for you automatically. If an error occurs, false is returned.
* See AdoDB GetCol() function for more detail.
* @param pQuery the SQL query. Use backticks (`) to quote all table
* and attribute names for AdoDB to quote appropriately.
* @param pValues an array of values used in a parameterised query
* @param pForceArray if set to true, when an array is created for each value
* @param pFirst2Cols if set to true, only returns the first two columns
* @return the associative array, or false if an error occurs
* @todo not currently used anywhere
function getCol( $pQuery, $pValues= FALSE, $pTrim= FALSE ) {
/** Returns an associative array for the given query.
* See AdoDB GetAssoc() function for more detail.
* @param pQuery the SQL query. Use backticks (`) to quote all table
* and attribute names for AdoDB to quote appropriately.
* @param pValues an array of values used in a parameterised query
* @param pForceArray if set to true, when an array is created for each value
* @param pFirst2Cols if set to true, only returns the first two columns
* @return the associative array, or false if an error occurs
function getArray( $pQuery, $pValues= FALSE, $pForceArray= FALSE, $pFirst2Cols= FALSE, $pCacheTime= BIT_QUERY_DEFAULT ) {
/** Returns an associative array for the given query.
* See AdoDB GetAssoc() function for more detail.
* @param pQuery the SQL query. Use backticks (`) to quote all table
* and attribute names for AdoDB to quote appropriately.
* @param pValues an array of values used in a parameterised query
* @param pForceArray if set to true, when an array is created for each value
* @param pFirst2Cols if set to true, only returns the first two columns
* @return the associative array, or false if an error occurs
function getAssoc( $pQuery, $pValues= FALSE, $pForceArray= FALSE, $pFirst2Cols= FALSE, $pCacheTime= BIT_QUERY_DEFAULT ) {
/** Executes the SQL and returns the first row as an array. The recordset and remaining rows are discarded for you automatically. If an error occurs, false is returned.
* See AdoDB GetRow() function for more detail.
* @param pQuery the SQL query. Use backticks (`) to quote all table
* and attribute names for AdoDB to quote appropriately.
* @param pValues an array of values used in a parameterised query
* @return returns the first row as an array, or false if an error occurs
function getRow( $pQuery, $pValues= FALSE, $pCacheTime= BIT_QUERY_DEFAULT ) {
/** Returns a single column value from the database.
* @param pQuery the SQL query. Use backticks (`) to quote all table
* and attribute names for AdoDB to quote appropriately.
* @param pValues an array of values used in a parameterised query
* @param pReportErrors report errors to STDOUT
* @param pOffset the row number to begin returning rows from.
* @return the associative array, or false if an error occurs
function getOne($pQuery, $pValues= NULL, $pNumRows= NULL, $pOffset= NULL, $pCacheTime = BIT_QUERY_DEFAULT ) {
* This function will take a set of fields identified by an associative array - $insertData
* generate a suitable SQL script
* and insert the data into the specified table - $insertTable
* @param insertTable Name of the table to be inserted into
* @param insertData Array of data to be inserted. Array keys provide the field names
* @return Error status of the insert
//stupid little loop to generate question marks. Start at one, and tack at the end to ease dealing with comma
for( $i = 1; $i < count( $insertData ); $i++ ) {
if( $insertTable[0] != '`' ) {
$insertTable = '`'. $insertTable. '`';
$query = "INSERT INTO $insertTable ( $setSql ) VALUES ( $valueSql )";
* This function will take a set of fields identified by an associative array - $updateData
* generate a suitable SQL script
* update the data into the specified table
* at the location identified in updateId which holds a name and value entry
* @param updateTable Name of the table to be updated
* @param updateData Array of data to be changed. Array keys provide the field names
* If an array key contains an '=' it will assumed to already be properly quoted.
* This allows use of keys like this: `column_name` = `column_name` + ?
* @param updateId Array identifying the record to update.
* Array key 'name' provide the field name, and 'value' the record key
* @return Error status of the insert
foreach( $updateData as $key=> $value ) {
if (strpos($key,'=') === false) {
$setSql .= ", `$key` = ?";
if( $updateTable[0] != '`' ) {
$updateTable = '`'. $updateTable. '`';
$query = "UPDATE $updateTable SET $setSql WHERE $keyNames";
$result = $this->query( $query, $bindVars );
* A database portable Sequence management function.
* @param pSequenceName Name of the sequence to be used
* It will be created if it does not already exist
* @return 0 if not supported, otherwise a sequence id
function GenID( $pSequenceName, $pUseDbPrefix = true ) {
* A database portable Sequence management function.
* @param pSequenceName Name of the sequence to be used
* It will be created if it does not already exist
* @param pStartID Allows setting the initial value of the sequence
* @return 0 if not supported, otherwise a sequence id
* @todo To be combined with GenID
* A database portable IFNULL function.
* @param pField argument to compare to NULL
* @param pNullRepl the NULL replacement value
* @return a string that represents the function that checks whether
* $pField is NULL for the given database, and if NULL, change the
* value returned to $pNullRepl.
function ifNull($pField, $pNullRepl) {
/** Format the timestamp in the format the database accepts.
* @param pDate a Unix integer timestamp or an ISO format Y-m-d H:i:s
* @return the timestamp as a quoted string.
* @todo could be used to later convert all int timestamps  |