Source for file abstract.php
Documentation is available at abstract.php
* @version $Id: abstract.php 4628 2012-05-06 19:56:43Z johanjanssens $
* @package Koowa_Database
* @copyright Copyright (C) 2007 - 2012 Johan Janssens. All rights reserved.
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
* Abstract Database Adapter
* @author Johan Janssens <johan@nooku.org>
* @package Koowa_Database
* @uses KPatternCommandChain
* Active state of the connection
* The database connection resource
* Last auto-generated insert_id
* Quote for named objects
* @param object An optional KConfig object with configuration options.
* Recognized key values include 'command_chain', 'charset', 'table_prefix',
* (this list is not meant to be comprehensive).
//If no config is passed create it
if(!isset ($config)) $config = new KConfig();
// Initialize the options
// Set the default charset. http://dev.mysql.com/doc/refman/5.1/en/charset-connection.html
if (!empty($config->charset)) {
//$this->setCharset($config->charset);
// Set the connection options
//Set the mixer in the config
// Mixin the command interface
* Free any resources that are open.
* Initializes the options for the object
* Called from {@link __construct()} as a first step of object instantiation.
* @param object An optional KConfig object with configuration options.
'table_prefix' => 'jos_',
'command_chain' => $this->getService('koowa:command.chain'),
'dispatch_events' => true,
'event_dispatcher' => $this->getService('koowa:event.dispatcher'),
'enable_callbacks' => false,
* Get a database query object
public function getQuery(KConfig $config = null)
$config = new KConfig(array('adapter' => $this));
* @return KDatabaseAdapterAbstract
* @return KDatabaseAdapterAbstract
* @return string The database name
* @param string The database name
* @return KDatabaseAdapterAbstract
* Provides access to the underlying database connection. Useful for when
* you need to call a proprietary method such as postgresql's lo_* methods
* @param resource The connection resource
* @return KDatabaseAdapterAbstract
* Get the insert id of the last insert operation
* @return mixed The id of the last inserted row(s)
* Preforms a select query
* Use for SELECT and anything that returns rows.
* If <var>key</var> is not empty then the returned array is indexed by the value
* of the database key. Returns <var>null</var> if the query fails.
* @param string|object A full SQL query to run. Data inside the query should be properly escaped.
* @param integer The fetch mode. Controls how the result will be returned to the caller. This
* value must be one of the KDatabase::FETCH_* constants.
* @param string The column name of the index to use
* @return mixed The return value of this function on success depends on the fetch type.
* In all cases, FALSE is returned on failure.
public function select($query, $mode = KDatabase::FETCH_ARRAY_LIST, $key = '')
$context = $this->getCommandContext();
$context->query = $query;
$context->operation = KDatabase::OPERATION_SELECT;
// Excute the insert operation
if($this->getCommandChain()->run('before.select', $context) !== false)
default : $result->free();
$this->getCommandChain()->run('after.select', $context);
* @param string|object A full SQL query to run. Data inside the query should be properly escaped.
* @param integer The fetch mode. Controls how the result will be returned to the caller. This
* value must be one of the KDatabase::FETCH_* constants.
* @return mixed The return value of this function on success depends on the fetch type.
* In all cases, FALSE is returned on failure.
public function show($query, $mode = KDatabase::FETCH_ARRAY_LIST)
$context = $this->getCommandContext();
$context->query = $query;
$context->operation = KDatabase::OPERATION_SHOW;
// Excute the insert operation
if($this->getCommandChain()->run('before.show', $context) !== false)
default : $result->free();
$this->getCommandChain()->run('after.show', $context);
* Inserts a row of data into a table.
* Automatically quotes the data values
* @param string The table to insert data into.
* @param array An associative array where the key is the colum name and
* the value is the value to insert for that column.
* @return bool|integer If the insert query was executed returns the number of rows updated, or 0 if
* no rows where updated, or -1 if an error occurred. Otherwise FALSE.
public function insert($table, array $data)
$context = $this->getCommandContext();
$context->table = $table;
$context->operation = KDatabase::OPERATION_INSERT;
//Excute the insert operation
if($this->getCommandChain()->run('before.insert', $context) !== false)
//Check if we have valid data to insert, if not return false
if(count($context->data))
foreach($context->data as $key => $val)
$context->result = $this->execute($context->query);
$this->getCommandChain()->run('after.insert', $context);
else $context->affected = false;
return $context->affected;
* Updates a table with specified data based on a WHERE clause
* Automatically quotes the data values
* @param string The table to update
* @param array An associative array where the key is the column name and
* the value is the value to use ofr that column.
* @param mixed A sql string or KDatabaseQuery object to limit which rows are updated.
* @return integer If the update query was executed returns the number of rows updated, or 0 if
* no rows where updated, or -1 if an error occurred. Otherwise FALSE.
public function update($table, array $data, $where = null)
$context = $this->getCommandContext();
$context->table = $table;
$context->where = $where;
$context->operation = KDatabase::OPERATION_UPDATE;
//Excute the update operation
if($this->getCommandChain()->run('before.update', $context) !== false)
if(count($context->data))
foreach($context->data as $key => $val) {
$vals[] = '`'. $key. '` = '. $this->quoteValue($val);
$context->result = $this->execute($context->query);
$this->getCommandChain()->run('after.update', $context);
else $context->affected = false;
return $context->affected;
* Deletes rows from the table based on a WHERE clause.
* @param string The table to update
* @param mixed A query string or a KDatabaseQuery object to limit which rows are updated.
* @return integer Number of rows affected, or -1 if an error occured.
public function delete($table, $where)
$context = $this->getCommandContext();
$context->table = $table;
$context->where = $where;
$context->operation = KDatabase::OPERATION_DELETE;
//Excute the delete operation
if($this->getCommandChain()->run('before.delete', $context) !== false)
$context->result = $this->execute($context->query);
$this->getCommandChain()->run('after.delete', $context);
return $context->affected;
* Use and other queries that don't return rows
* @param string The query to run. Data inside the query should be properly escaped.
* @param integer The result maode, either the constant KDatabase::RESULT_USE or KDatabase::RESULT_STORE
* depending on the desired behavior. By default, KDatabase::RESULT_STORE is used. If you
* use KDatabase::RESULT_USE all subsequent calls will return error Commands out of sync
* unless you free the result first.
* @throws KDatabaseException
* @return boolean For SELECT, SHOW, DESCRIBE or EXPLAIN will return a result object.
* For other successful queries return TRUE.
public function execute($sql, $mode = KDatabase::RESULT_STORE )
//Replace the database table prefix
* @param string The table prefix
* @return KDatabaseAdapterAbstract
* @see KDatabaseAdapterAbstract::replaceTableNeedle
* @return string The table prefix
* @see KDatabaseAdapterAbstract::replaceTableNeedle
* @return string The table needle
* @see KDatabaseAdapterAbstract::replaceTableNeedle
* This function replaces the table needles in a query string with the actual table prefix.
* @param string The SQL query string
* @return string The SQL query string
$pattern = "($needle(?=[a-z0-9]))";
* Safely quotes a value for an SQL statement.
* If an array is passed as the value, the array values are quoted
* and then returned as a comma-separated string; this is useful
* for generating IN() lists.
* @param mixed The value to quote.
* @return string An SQL-safe quoted value (or a string of separated-
//Quote array values, not keys, then combine with commas.
foreach ($value as $k => $v) {
* Quotes a single identifier name (table, table alias, table column,
* index, sequence). Ignores empty values.
* This function requires all SQL statements, operators and functions to be
* @param string|arrayThe identifier name to quote. If an array, quotes
* each element in the array as an identifier name.
* @return string|arrayThe quoted identifier name (or array of names).
foreach ($spec as $key => $val) {
// String spaces around the identifier
// Quote all the lower case parts
$spec = preg_replace_callback('#(?:\b|\#)+(?<!`)([a-z0-9\.\#\-_]+)(?!`)\b#', array($this, '_quoteName') , $spec);
* Fetch the first field of the first row
* @param mysqli_result The result object. A result set identifier returned by the select() function
* @param integer The index to use
* @return The value returned in the query or null if the query failed.
abstract protected function _fetchField($result, $key = 0);
* Fetch an array of single field results
* @param mysqli_result The result object. A result set identifier returned by the select() function
* @param integer The index to use
* @return array A sequential array of returned rows.
* Fetch the first row of a result set as an associative array
* @param mysqli_result The result object. A result set identifier returned by the select() function
* Fetch all result rows of a result set as an array of associative arrays
* If <var>key</var> is not empty then the returned array is indexed by the value
* of the database key. Returns <var>null</var> if the query fails.
* @param mysqli_result The result object. A result set identifier returned by the select() function
* @param string The column name of the index to use
* @return array If key is empty as sequential list of returned records.
* Fetch the first row of a result set as an object
* @param mysqli_result The result object. A result set identifier returned by the select() function
* Fetch all rows of a result set as an array of objects
* If <var>key</var> is not empty then the returned array is indexed by the value
* of the database key. Returns <var>null</var> if the query fails.
* @param mysqli_result The result object. A result set identifier returned by the select() function
* @param string The column name of the index to use
* @return array If <var>key</var> is empty as sequential array of returned rows.
* Parse the raw table schema information
* @param object The raw table schema information
* @return KDatabaseSchemaTable
* Parse the raw column schema information
* @param object The raw column schema information
* @return KDatabaseSchemaColumn
* Given a raw column specification, parse into datatype, size, and decimal scope.
* @param string The column specification; for example,
* "VARCHAR(255)" or "NUMERIC(10,2)".
* @return array A sequential array of the column type, size, and scope.
* Safely quotes a value for an SQL statement.
* @param mixed The value to quote
* @return string An SQL-safe quoted value
* Quotes an identifier name (table, index, etc). Ignores empty values.
* If the name contains a dot, this method will separately quote the
* parts before and after the dot.
* @param string The identifier name to quote.
* @return string The quoted identifier name.
$result = "$table.$column";
|