Query/classes/db_pdo.php

555 lines
12 KiB
PHP
Raw Normal View History

2012-03-15 09:25:18 -04:00
<?php
/**
* Query
*
* Free Query Builder / Database Abstraction Layer
*
2012-04-20 13:17:39 -04:00
* @package Query
* @author Timothy J. Warren
2013-01-02 14:26:42 -05:00
* @copyright Copyright (c) 2012 - 2013
2012-03-15 09:25:18 -04:00
* @link https://github.com/aviat4ion/Query
2012-04-20 13:17:39 -04:00
* @license http://philsturgeon.co.uk/code/dbad-license
2012-03-15 09:25:18 -04:00
*/
// --------------------------------------------------------------------------
/**
* Base Database class
*
* Extends PDO to simplify cross-database issues
2012-04-20 13:17:39 -04:00
*
* @package Query
* @subpackage Query
2012-03-15 09:25:18 -04:00
*/
abstract class DB_PDO extends PDO {
2012-11-07 08:42:34 -05:00
// Reference to the last executed query
2012-03-15 09:25:18 -04:00
protected $statement;
2012-08-09 12:15:36 -04:00
2012-11-07 08:42:34 -05:00
// Character to escape identifiers
2012-04-10 14:06:34 -04:00
protected $escape_char = '"';
2012-08-09 12:15:36 -04:00
2012-11-07 08:42:34 -05:00
// Reference to sql sub class
public $sql;
2012-08-09 12:15:36 -04:00
2012-11-07 08:42:34 -05:00
// Reference to util sub class
public $util;
2012-03-15 09:25:18 -04:00
2012-11-07 08:42:34 -05:00
// Last query executed
2012-09-27 13:41:29 -04:00
public $last_query;
2013-02-28 12:22:55 -05:00
2012-11-07 08:42:34 -05:00
// Prefix to apply to table namesa
public $table_prefix = '';
2012-09-27 13:41:29 -04:00
2012-03-15 09:25:18 -04:00
/**
* PDO constructor wrapper
*
* @param string $dsn
* @param string $username
* @param string $password
* @param array $driver_options
2012-03-15 09:25:18 -04:00
*/
public function __construct($dsn, $username=NULL, $password=NULL, $driver_options=array())
{
2013-05-29 13:57:08 -04:00
// Set PDO to display errors as exceptions
$driver_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
2012-03-15 09:25:18 -04:00
parent::__construct($dsn, $username, $password, $driver_options);
2012-08-09 12:15:36 -04:00
// Load the sql class for the driver
$class = get_class($this)."_sql";
$this->sql = new $class();
2012-08-09 12:15:36 -04:00
// Load the util class for the driver
$class = get_class($this)."_util";
$this->util = new $class($this);
2012-04-10 14:06:34 -04:00
// Set additional driver options, if they exist
if ( ! empty($driver_options) && is_array($driver_options))
{
foreach($driver_options as $key => $val)
{
$this->setAttribute($key, $val);
}
}
2012-03-15 09:25:18 -04:00
}
2012-04-10 14:06:34 -04:00
// --------------------------------------------------------------------------
// ! Concrete functions that can be overridden in child classes
// --------------------------------------------------------------------------
2012-04-10 14:06:34 -04:00
2012-03-15 09:25:18 -04:00
/**
* Simplifies prepared statements for database queries
*
* @param string $sql
* @param array $data
* @return mixed PDOStatement / FALSE
*/
public function prepare_query($sql, $data)
{
// Prepare the sql
$query = $this->prepare($sql);
2012-04-10 14:06:34 -04:00
2012-03-15 09:25:18 -04:00
if( ! (is_object($query) || is_resource($query)))
{
$this->get_last_error();
return NULL;
2012-03-15 09:25:18 -04:00
}
2012-04-10 14:06:34 -04:00
2012-03-15 09:25:18 -04:00
// Set the statement in the class variable for easy later access
2013-02-07 16:21:02 -05:00
$this->statement = $query;
2012-04-10 14:06:34 -04:00
2012-03-15 09:25:18 -04:00
if( ! (is_array($data) || is_object($data)))
{
trigger_error("Invalid data argument");
return NULL;
2012-03-15 09:25:18 -04:00
}
2012-04-10 14:06:34 -04:00
2012-03-15 09:25:18 -04:00
// Bind the parameters
foreach($data as $k => $value)
2012-03-15 09:25:18 -04:00
{
if(is_numeric($k))
{
$k++;
}
2012-04-10 14:06:34 -04:00
2012-03-15 09:25:18 -04:00
$res = $query->bindValue($k, $value);
2012-04-10 14:06:34 -04:00
2012-03-15 09:25:18 -04:00
if( ! $res)
{
trigger_error("Parameter not successfully bound");
return NULL;
2012-03-15 09:25:18 -04:00
}
}
2012-04-10 14:06:34 -04:00
return $query;
2012-03-15 09:25:18 -04:00
}
// -------------------------------------------------------------------------
/**
* Create and execute a prepared statement with the provided parameters
*
* @param string $sql
* @param array $params
* @return PDOStatement
*/
public function prepare_execute($sql, $params)
2012-04-10 14:06:34 -04:00
{
2012-03-15 09:25:18 -04:00
$this->statement = $this->prepare_query($sql, $params);
$this->statement->execute();
return $this->statement;
}
// -------------------------------------------------------------------------
/**
* Returns number of rows affected by an INSERT, UPDATE, DELETE type query
*
* @param PDOStatement $statement
* @return int
*/
public function affected_rows($statement='')
{
if ( ! empty($statement))
{
2012-04-10 14:06:34 -04:00
$this->statement = $statement;
2012-03-15 09:25:18 -04:00
}
// Return number of rows affected
return $this->statement->rowCount();
}
2012-04-10 14:06:34 -04:00
2012-03-15 09:25:18 -04:00
// --------------------------------------------------------------------------
2012-04-10 14:06:34 -04:00
2012-03-15 09:25:18 -04:00
/**
* Return the last error for the current database connection
*
* @return string
*/
public function get_last_error()
{
2012-04-18 16:28:12 -04:00
list($i1, $i2, $i3) = $this->errorInfo();
2012-04-10 14:06:34 -04:00
2012-04-18 16:28:12 -04:00
echo "Error: <pre>{$i1}:{$i2}\n{$i3}</pre>";
2012-03-15 09:25:18 -04:00
}
2012-11-07 08:42:34 -05:00
// --------------------------------------------------------------------------
2013-02-28 12:22:55 -05:00
2012-11-07 08:42:34 -05:00
/**
* Quote database table name, and set prefix
2013-02-28 12:22:55 -05:00
*
* @param string $table
2012-11-07 08:42:34 -05:00
* @return string
*/
public function quote_table($table)
2013-02-28 12:22:55 -05:00
{
2012-11-07 08:42:34 -05:00
// If there isn't a prefix set, just quote the table name
if (empty($this->table_prefix))
{
return $this->quote_ident($table);
}
2013-02-28 12:22:55 -05:00
2012-11-07 08:42:34 -05:00
// Split indentifier by period, will split into:
// database.schema.table OR
// schema.table OR
// database.table OR
// table
$idents = (array) explode('.', $table);
$segments = count($idents);
2013-02-28 12:22:55 -05:00
2012-11-07 08:42:34 -05:00
// Reference the last item in the split string
$last =& $idents[$segments - 1];
2013-02-28 12:22:55 -05:00
2012-11-07 08:42:34 -05:00
// Quote the last item
$last = $this->_prefix($last);
2013-02-28 12:22:55 -05:00
2012-11-07 08:42:34 -05:00
// Rejoin
2013-02-28 12:22:55 -05:00
$table = implode('.', $idents);
2012-11-07 08:42:34 -05:00
// Finally, quote the table
return $this->quote_ident($table);
}
2013-02-28 12:22:55 -05:00
2012-11-07 08:42:34 -05:00
// --------------------------------------------------------------------------
2013-02-28 12:22:55 -05:00
/**
2012-11-07 08:42:34 -05:00
* Sets the table prefix on the passed string
2013-02-28 12:22:55 -05:00
*
2012-11-07 08:42:34 -05:00
* @param string $str
* @return string
*/
protected function _prefix($str)
{
// Don't prefix an already prefixed table
if (strpos($str, $this->table_prefix) !== FALSE)
{
return $str;
}
2013-02-28 12:22:55 -05:00
2012-11-07 08:42:34 -05:00
return $this->table_prefix.$str;
}
2013-02-28 12:22:55 -05:00
2012-03-15 09:25:18 -04:00
// --------------------------------------------------------------------------
/**
* Surrounds the string with the databases identifier escape characters
*
* @param mixed $ident
* @return string
*/
public function quote_ident($ident)
{
if (is_array($ident))
{
2012-11-07 08:42:34 -05:00
return array_map(array($this, __METHOD__), $ident);
2012-03-15 09:25:18 -04:00
}
2012-08-09 12:15:36 -04:00
// Handle comma-separated identifiers
if (strpos($ident, ',') !== FALSE)
{
$parts = explode(',', $ident);
$parts = array_map('mb_trim', $parts);
2012-11-07 08:42:34 -05:00
$parts = array_map(array($this, __METHOD__), $parts);
$ident = implode(',', $parts);
}
2012-03-15 09:25:18 -04:00
// Split each identifier by the period
$hiers = explode('.', $ident);
$hiers = array_map('mb_trim', $hiers);
2012-03-15 09:25:18 -04:00
// Re-compile the string
$raw = implode('.', array_map(array($this, '_quote'), $hiers));
// Fix functions
$funcs = array();
preg_match_all("#{$this->escape_char}([a-zA-Z0-9_]+(\((.*?)\))){$this->escape_char}#iu", $raw, $funcs, PREG_SET_ORDER);
foreach($funcs as $f)
{
// Unquote the function
$raw = str_replace($f[0], $f[1], $raw);
// Quote the inside identifiers
$raw = str_replace($f[3], $this->quote_ident($f[3]), $raw);
}
return $raw;
}
2012-08-09 12:15:36 -04:00
// --------------------------------------------------------------------------
2012-08-09 12:15:36 -04:00
/**
* Helper method for quote_ident
*
* @param mixed $str
* @return mixed
*/
protected function _quote($str)
{
// Don't quote numbers
if ( ! is_string($str) && is_numeric($str))
{
return $str;
}
2012-08-09 12:15:36 -04:00
// Don't add additional quotes
if (strpos($str, $this->escape_char) === 0 || strrpos($str, $this->escape_char) === 0)
{
return $str;
}
return "{$this->escape_char}{$str}{$this->escape_char}";
2012-03-15 09:25:18 -04:00
}
// -------------------------------------------------------------------------
/**
* Deletes all the rows from a table. Does the same as the truncate
* method if the database does not support 'TRUNCATE';
*
* @param string $table
* @return mixed
*/
public function empty_table($table)
{
$sql = 'DELETE FROM '.$this->quote_ident($table);
return $this->query($sql);
}
// -------------------------------------------------------------------------
/**
2012-04-10 14:06:34 -04:00
* Return schemas for databases that list them
*
* @return array
2012-03-15 09:25:18 -04:00
*/
2012-04-10 14:06:34 -04:00
public function get_schemas()
{
return NULL;
2012-04-10 14:06:34 -04:00
}
// -------------------------------------------------------------------------
2012-03-15 09:25:18 -04:00
/**
* Return list of tables for the current database
2012-04-10 14:06:34 -04:00
*
2012-03-15 09:25:18 -04:00
* @return array
*/
2012-04-10 14:06:34 -04:00
public function get_tables()
{
return $this->driver_query($this->sql->table_list());
}
// -------------------------------------------------------------------------
2012-04-03 16:54:33 -04:00
/**
* Return list of dbs for the current connection, if possible
*
* @return array
*/
2012-04-10 14:06:34 -04:00
public function get_dbs()
{
return $this->driver_query($this->sql->db_list());
}
// -------------------------------------------------------------------------
2012-03-15 09:25:18 -04:00
/**
2012-04-10 14:06:34 -04:00
* Return list of views for the current database
*
* @return array
2012-03-15 09:25:18 -04:00
*/
2012-04-10 14:06:34 -04:00
public function get_views()
{
return $this->driver_query($this->sql->view_list());
}
// -------------------------------------------------------------------------
2012-03-15 09:25:18 -04:00
/**
2012-04-10 14:06:34 -04:00
* Return list of sequences for the current database, if they exist
*
* @return array
2012-03-15 09:25:18 -04:00
*/
2012-04-10 14:06:34 -04:00
public function get_sequences()
{
return $this->driver_query($this->sql->sequence_list());
}
// -------------------------------------------------------------------------
2012-03-15 09:25:18 -04:00
/**
2012-04-10 14:06:34 -04:00
* Return list of function for the current database
*
2012-03-15 09:25:18 -04:00
* @return array
*/
2012-04-10 14:06:34 -04:00
public function get_functions()
{
return $this->driver_query($this->sql->function_list(), FALSE);
}
// -------------------------------------------------------------------------
2012-03-15 09:25:18 -04:00
/**
2012-04-10 14:06:34 -04:00
* Return list of stored procedures for the current database
2012-03-15 09:25:18 -04:00
*
2012-04-10 14:06:34 -04:00
* @return array
2012-03-15 09:25:18 -04:00
*/
2012-04-10 14:06:34 -04:00
public function get_procedures()
{
return $this->driver_query($this->sql->procedure_list(), FALSE);
}
// -------------------------------------------------------------------------
2012-03-15 09:25:18 -04:00
/**
2012-04-10 14:06:34 -04:00
* Return list of triggers for the current database
2012-03-15 09:25:18 -04:00
*
2012-04-10 14:06:34 -04:00
* @return array
2012-03-15 09:25:18 -04:00
*/
2012-04-10 14:06:34 -04:00
public function get_triggers()
{
return $this->driver_query($this->sql->trigger_list(), FALSE);
}
2012-03-15 09:25:18 -04:00
2012-04-10 14:06:34 -04:00
// -------------------------------------------------------------------------
2012-03-15 09:25:18 -04:00
/**
2012-04-10 14:06:34 -04:00
* Retreives an array of non-user-created tables for
* the connection/database
*
* @return array
2012-03-15 09:25:18 -04:00
*/
2012-04-10 14:06:34 -04:00
public function get_system_tables()
{
return $this->driver_query($this->sql->system_table_list());
}
2012-08-09 12:15:36 -04:00
// --------------------------------------------------------------------------
2012-08-09 12:15:36 -04:00
/**
* Retrieve column information for the current database table
*
* @param string $table
* @return array
*/
public function get_columns($table)
{
return $this->driver_query($this->sql->column_list($table), FALSE);
}
2012-08-09 12:15:36 -04:00
// --------------------------------------------------------------------------
2012-08-09 12:15:36 -04:00
/**
* Retrieve list of data types for the database
*
* @return array
*/
public function get_types()
{
return $this->driver_query($this->sql->type_list(), FALSE);
}
2012-04-10 14:06:34 -04:00
// -------------------------------------------------------------------------
/**
* Method to simplify retreiving db results for meta-data queries
*
* @param string $sql
* @param bool $filtered_index
* @return mixed
*/
2012-05-15 13:35:59 -04:00
public function driver_query($sql, $filtered_index=TRUE)
{
// Return if the query doesn't apply to the driver
if ($sql === NULL)
{
return NULL;
}
2012-08-09 12:15:36 -04:00
$res = $this->query($sql);
$flag = ($filtered_index) ? PDO::FETCH_NUM : PDO::FETCH_ASSOC;
$all = $res->fetchAll($flag);
return ($filtered_index) ? db_filter($all, 0) : $all;
}
2012-08-09 12:15:36 -04:00
// --------------------------------------------------------------------------
/**
* Return the number of rows returned for a SELECT query
*
* @see http://us3.php.net/manual/en/pdostatement.rowcount.php#87110
* @return int
*/
public function num_rows()
{
2012-09-27 13:41:29 -04:00
$regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i';
$output = array();
if (preg_match($regex, $this->last_query, $output) > 0)
{
$stmt = $this->query("SELECT COUNT(*) FROM {$output[1]}", PDO::FETCH_NUM);
return $stmt->fetchColumn();
}
return NULL;
}
2012-04-10 14:06:34 -04:00
// -------------------------------------------------------------------------
// ! Abstract public functions to implement in child classes
2012-04-10 14:06:34 -04:00
// -------------------------------------------------------------------------
2012-03-15 09:25:18 -04:00
/**
2012-04-10 14:06:34 -04:00
* Empty the passed table
*
* @param string $table
* @return void
2012-03-15 09:25:18 -04:00
*/
2012-04-10 14:06:34 -04:00
abstract public function truncate($table);
// --------------------------------------------------------------------------
/**
* Create sql for batch insert
*
* @param string $table
* @param array $data
* @return string
*/
public function insert_batch($table, $data=array())
{
if ( ! is_array($data[0])) return NULL;
$table = $this->quote_table($table);
$fields = array_keys($data[0]);
$vals = array();
$sql = "INSERT INTO {$table} (";
$sql .= implode(',', $this->quote_ident($fields));
$sql .= ") VALUES ";
$params = array_fill(0, count($fields), '?');
$param_string = implode(',', $params);
// Remove the first array after use, as it is a special case
$sql .= "({$param_string})";
$vals = array_values($data[0]);
array_shift($data);
// Add another grouping for each
foreach($data as $group)
{
$sql .= ",({$param_string})";
$vals = array_merge($vals, array_values($group));
}
return array($sql, $vals);
}
2012-03-15 09:25:18 -04:00
}
// End of db_pdo.php