Query/src/Drivers/AbstractDriver.php

641 lines
13 KiB
PHP
Raw Normal View History

2016-10-12 22:12:25 -04:00
<?php declare(strict_types=1);
2012-03-15 09:25:18 -04:00
/**
* Query
*
2016-09-07 13:17:17 -04:00
* SQL Query Builder / Database Abstraction Layer
2012-03-15 09:25:18 -04:00
*
2018-01-19 13:43:19 -05:00
* PHP version 7.1
2016-09-07 13:17:17 -04:00
*
* @package Query
* @author Timothy J. Warren <tim@timshomepage.net>
2018-01-19 13:43:19 -05:00
* @copyright 2012 - 2018 Timothy J. Warren
2016-09-07 13:17:17 -04:00
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query
2012-03-15 09:25:18 -04:00
*/
2016-09-07 17:39:19 -04:00
namespace Query\Drivers;
2016-09-07 13:17:17 -04:00
2016-10-12 22:12:25 -04:00
use InvalidArgumentException;
2016-09-07 17:39:19 -04:00
use PDO;
use PDOStatement;
2014-04-07 18:28:53 -04:00
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
2014-03-31 16:01:58 -04:00
* @subpackage Drivers
2012-03-15 09:25:18 -04:00
*/
2016-09-07 17:39:19 -04:00
abstract class AbstractDriver extends PDO implements DriverInterface {
2012-03-15 09:25:18 -04:00
2014-03-31 16:01:58 -04:00
/**
* Reference to the last executed query
2016-10-12 22:12:25 -04:00
* @var PDOStatement
2014-03-31 16:01:58 -04:00
*/
2012-03-15 09:25:18 -04:00
protected $statement;
2012-08-09 12:15:36 -04:00
2014-03-31 16:01:58 -04:00
/**
2016-09-07 17:39:19 -04:00
* Start character to escape identifiers
2014-03-31 16:01:58 -04:00
* @var string
*/
2016-10-13 21:55:23 -04:00
protected $escapeCharOpen = '"';
2016-09-07 17:39:19 -04:00
/**
* End character to escape identifiers
* @var string
*/
2016-10-13 21:55:23 -04:00
protected $escapeCharClose = '"';
2012-08-09 12:15:36 -04:00
2014-03-31 16:01:58 -04:00
/**
* Reference to sql class
2015-11-10 20:58:32 -05:00
* @var SQLInterface
2014-03-31 16:01:58 -04:00
*/
protected $sql;
2012-08-09 12:15:36 -04:00
2014-03-31 16:01:58 -04:00
/**
* Reference to util class
2015-11-10 20:58:32 -05:00
* @var AbstractUtil
2014-03-31 16:01:58 -04:00
*/
protected $util;
2012-03-15 09:25:18 -04:00
2014-03-31 16:01:58 -04:00
/**
* Last query executed
* @var string
*/
2016-10-13 21:55:23 -04:00
protected $lastQuery = '';
2013-02-28 12:22:55 -05:00
2014-03-31 16:01:58 -04:00
/**
* Prefix to apply to table names
* @var string
*/
2016-10-13 21:55:23 -04:00
protected $tablePrefix = '';
2012-09-27 13:41:29 -04:00
/**
* Whether the driver supports 'TRUNCATE'
2016-09-07 13:10:03 -04:00
* @var boolean
*/
2016-10-13 21:55:23 -04:00
protected $hasTruncate = TRUE;
2012-03-15 09:25:18 -04:00
/**
* PDO constructor wrapper
*
* @param string $dsn
* @param string $username
* @param string $password
2016-10-13 21:55:23 -04:00
* @param array $driverOptions
2012-03-15 09:25:18 -04:00
*/
2016-10-13 21:55:23 -04:00
public function __construct($dsn, $username=NULL, $password=NULL, array $driverOptions=[])
2012-03-15 09:25:18 -04:00
{
// Set PDO to display errors as exceptions, and apply driver options
2016-10-13 21:55:23 -04:00
$driverOptions[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
parent::__construct($dsn, $username, $password, $driverOptions);
2012-08-09 12:15:36 -04:00
2016-10-13 21:55:23 -04:00
$this->_loadSubClasses();
}
/**
* Loads the subclasses for the driver
*
* @return void
*/
2016-10-13 21:55:23 -04:00
protected function _loadSubClasses()
{
// Load the sql and util class for the driver
2016-10-13 21:55:23 -04:00
$thisClass = get_class($this);
$nsArray = explode("\\", $thisClass);
array_pop($nsArray);
$driver = array_pop($nsArray);
$sqlClass = __NAMESPACE__ . "\\{$driver}\\SQL";
$utilClass = __NAMESPACE__ . "\\{$driver}\\Util";
2016-10-13 21:55:23 -04:00
$this->sql = new $sqlClass();
$this->util = new $utilClass($this);
2012-03-15 09:25:18 -04:00
}
2012-04-10 14:06:34 -04:00
/**
* Allow invoke to work on table object
*
* @codeCoverageIgnore
* @param string $name
* @param array $args
2014-04-22 14:02:54 -04:00
* @return mixed
*/
2016-10-12 22:12:25 -04:00
public function __call(string $name, array $args = [])
{
if (
isset($this->$name)
&& is_object($this->$name)
&& method_exists($this->$name, '__invoke')
)
{
2016-09-07 13:10:03 -04:00
return call_user_func_array([$this->$name, '__invoke'], $args);
}
}
// --------------------------------------------------------------------------
// ! Accessors / Mutators
// --------------------------------------------------------------------------
/**
2016-09-07 17:39:19 -04:00
* Get the last sql query executed
*
* @return string
*/
2016-10-13 21:55:23 -04:00
public function getLastQuery(): string
{
2016-10-13 21:55:23 -04:00
return $this->lastQuery;
}
/**
* Set the last query sql
*
2016-10-13 21:55:23 -04:00
* @param string $queryString
* @return void
*/
2016-10-13 21:55:23 -04:00
public function setLastQuery(string $queryString)
{
2016-10-13 21:55:23 -04:00
$this->lastQuery = $queryString;
}
/**
* Get the SQL class for the current driver
*
* @return SQLInterface
*/
2016-10-13 21:55:23 -04:00
public function getSql(): SQLInterface
{
return $this->sql;
}
/**
* Get the Util class for the current driver
*
* @return AbstractUtil
*/
2016-10-13 21:55:23 -04:00
public function getUtil(): AbstractUtil
{
return $this->util;
}
/**
* Set the common table name prefix
*
2015-07-31 10:56:16 -04:00
* @param string $prefix
* @return void
*/
2016-10-13 21:55:23 -04:00
public function setTablePrefix($prefix)
{
2016-10-13 21:55:23 -04:00
$this->tablePrefix = $prefix;
}
// --------------------------------------------------------------------------
// ! Concrete functions that can be overridden in child classes
// --------------------------------------------------------------------------
2012-03-15 09:25:18 -04:00
/**
* Simplifies prepared statements for database queries
*
* @param string $sql
* @param array $data
2016-09-07 17:39:19 -04:00
* @return PDOStatement | FALSE
* @throws InvalidArgumentException
2012-03-15 09:25:18 -04:00
*/
2016-10-13 21:55:23 -04:00
public function prepareQuery($sql, $data)
2012-03-15 09:25:18 -04:00
{
// Prepare the sql, save the statement for easy access later
$this->statement = $this->prepare($sql);
2012-04-10 14:06:34 -04:00
2012-03-15 09:25:18 -04:00
if( ! (is_array($data) || is_object($data)))
{
2016-09-07 17:39:19 -04:00
throw new InvalidArgumentException("Data argument must be an object or associative array");
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
{
// Parameters are 1-based, the data is 0-based
// So, if the key is numeric, add 1
2015-11-11 09:25:21 -05:00
if(is_numeric($k))
{
$k++;
}
$this->statement->bindValue($k, $value);
2012-03-15 09:25:18 -04:00
}
2012-04-10 14:06:34 -04:00
return $this->statement;
2012-03-15 09:25:18 -04:00
}
/**
* Create and execute a prepared statement with the provided parameters
*
* @param string $sql
* @param array $params
2016-09-07 17:39:19 -04:00
* @return PDOStatement
2012-03-15 09:25:18 -04:00
*/
2016-10-13 21:55:23 -04:00
public function prepareExecute($sql, $params)
2012-04-10 14:06:34 -04:00
{
2016-10-13 21:55:23 -04:00
$this->statement = $this->prepareQuery($sql, $params);
2012-03-15 09:25:18 -04:00
$this->statement->execute();
return $this->statement;
}
/**
* Returns number of rows affected by an INSERT, UPDATE, DELETE type query
*
* @return int
*/
2016-10-13 21:55:23 -04:00
public function affectedRows()
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-11-07 08:42:34 -05:00
/**
2014-04-08 17:13:41 -04:00
* Prefixes a table if it is not already prefixed
* @param string $table
2012-11-07 08:42:34 -05:00
* @return string
*/
2016-10-13 21:55:23 -04:00
public function prefixTable($table)
2013-02-28 12:22:55 -05:00
{
// Add the prefix to the table name
// before quoting it
2016-10-13 21:55:23 -04:00
if ( ! empty($this->tablePrefix))
2012-11-07 08:42:34 -05:00
{
// Split identifier by period, will split into:
// database.schema.table OR
// schema.table OR
// database.table OR
// table
2016-10-13 21:55:23 -04:00
$identifiers = explode('.', $table);
$segments = count($identifiers);
// Quote the last item, and add the database prefix
2016-10-13 21:55:23 -04:00
$identifiers[$segments - 1] = $this->_prefix(end($identifiers));
// Rejoin
2016-10-13 21:55:23 -04:00
$table = implode('.', $identifiers);
2012-11-07 08:42:34 -05:00
}
2013-02-28 12:22:55 -05:00
2014-04-08 17:13:41 -04:00
return $table;
}
/**
* Quote database table name, and set prefix
*
* @param string $table
* @return string
*/
2016-10-13 21:55:23 -04:00
public function quoteTable($table)
2014-04-08 17:13:41 -04:00
{
2016-10-13 21:55:23 -04:00
$table = $this->prefixTable($table);
2014-04-08 17:13:41 -04:00
2012-11-07 08:42:34 -05:00
// Finally, quote the table
2016-10-13 21:55:23 -04:00
return $this->quoteIdent($table);
2012-11-07 08:42:34 -05:00
}
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
*
2016-09-07 17:39:19 -04:00
* @param mixed $identifier
2012-03-15 09:25:18 -04:00
* @return string
*/
2016-10-13 21:55:23 -04:00
public function quoteIdent($identifier)
{
2016-09-07 17:39:19 -04:00
if (is_array($identifier))
2012-03-15 09:25:18 -04:00
{
2016-09-07 17:39:19 -04:00
return array_map([$this, __METHOD__], $identifier);
2012-03-15 09:25:18 -04:00
}
2012-08-09 12:15:36 -04:00
// Handle comma-separated identifiers
2016-09-07 17:39:19 -04:00
if (strpos($identifier, ',') !== FALSE)
{
2016-09-07 17:39:19 -04:00
$parts = array_map('mb_trim', explode(',', $identifier));
2016-09-07 13:10:03 -04:00
$parts = array_map([$this, __METHOD__], $parts);
2016-09-07 17:39:19 -04:00
$identifier = implode(',', $parts);
}
2012-03-15 09:25:18 -04:00
// Split each identifier by the period
2016-09-07 17:39:19 -04:00
$hiers = explode('.', $identifier);
$hiers = array_map('mb_trim', $hiers);
2012-03-15 09:25:18 -04:00
// Re-compile the string
2016-09-07 13:10:03 -04:00
$raw = implode('.', array_map([$this, '_quote'], $hiers));
// Fix functions
2016-09-07 13:10:03 -04:00
$funcs = [];
2016-10-13 21:55:23 -04:00
preg_match_all("#{$this->escapeCharOpen}([a-zA-Z0-9_]+(\((.*?)\))){$this->escapeCharClose}#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
2016-10-13 21:55:23 -04:00
$raw = str_replace($f[3], $this->quoteIdent($f[3]), $raw);
}
return $raw;
}
2012-08-09 12:15:36 -04:00
2012-03-15 09:25:18 -04:00
/**
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
*/
2016-10-13 21:55:23 -04:00
public function getSchemas()
2012-04-10 14:06:34 -04:00
{
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
*/
2016-10-13 21:55:23 -04:00
public function getTables()
2012-04-10 14:06:34 -04:00
{
2016-10-13 21:55:23 -04:00
$tables = $this->driverQuery('tableList');
2014-04-28 16:41:46 -04:00
natsort($tables);
return $tables;
2012-04-10 14:06:34 -04:00
}
2012-04-03 16:54:33 -04:00
/**
* Return list of dbs for the current connection, if possible
*
* @return array
*/
2016-10-13 21:55:23 -04:00
public function getDbs()
2012-04-10 14:06:34 -04:00
{
2016-10-13 21:55:23 -04:00
return $this->driverQuery('dbList');
2012-04-10 14:06:34 -04:00
}
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
*/
2016-10-13 21:55:23 -04:00
public function getViews()
2012-04-10 14:06:34 -04:00
{
2016-10-13 21:55:23 -04:00
$views = $this->driverQuery('viewList');
2014-04-28 16:41:46 -04:00
sort($views);
return $views;
2012-04-10 14:06:34 -04:00
}
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
*/
2016-10-13 21:55:23 -04:00
public function getSequences()
2012-04-10 14:06:34 -04:00
{
2016-10-13 21:55:23 -04:00
return $this->driverQuery('sequenceList');
2012-04-10 14:06:34 -04:00
}
2012-03-15 09:25:18 -04:00
/**
* Return list of functions for the current database
2012-04-10 14:06:34 -04:00
*
2012-03-15 09:25:18 -04:00
* @return array
*/
2016-10-13 21:55:23 -04:00
public function getFunctions()
2012-04-10 14:06:34 -04:00
{
2016-10-13 21:55:23 -04:00
return $this->driverQuery('functionList', FALSE);
2012-04-10 14:06:34 -04:00
}
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
*/
2016-10-13 21:55:23 -04:00
public function getProcedures()
2012-04-10 14:06:34 -04:00
{
2016-10-13 21:55:23 -04:00
return $this->driverQuery('procedureList', FALSE);
2012-04-10 14:06:34 -04:00
}
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
*/
2016-10-13 21:55:23 -04:00
public function getTriggers()
2012-04-10 14:06:34 -04:00
{
2016-10-13 21:55:23 -04:00
return $this->driverQuery('triggerList', FALSE);
2012-04-10 14:06:34 -04:00
}
2012-03-15 09:25:18 -04:00
/**
2014-04-22 14:02:54 -04:00
* Retrieves an array of non-user-created tables for
2012-04-10 14:06:34 -04:00
* the connection/database
*
* @return array
2012-03-15 09:25:18 -04:00
*/
2016-10-13 21:55:23 -04:00
public function getSystemTables()
2012-04-10 14:06:34 -04:00
{
2016-10-13 21:55:23 -04:00
return $this->driverQuery('systemTableList');
2012-04-10 14:06:34 -04:00
}
2012-08-09 12:15:36 -04:00
/**
* Retrieve column information for the current database table
*
* @param string $table
* @return array
*/
2016-10-13 21:55:23 -04:00
public function getColumns($table)
{
2016-10-13 21:55:23 -04:00
return $this->driverQuery($this->getSql()->columnList($this->prefixTable($table)), FALSE);
}
2012-08-09 12:15:36 -04:00
/**
* Retrieve foreign keys for the table
*
* @param string $table
* @return array
*/
2016-10-13 21:55:23 -04:00
public function getFks($table)
{
2016-10-13 21:55:23 -04:00
return $this->driverQuery($this->getSql()->fkList($table), FALSE);
}
/**
* Retrieve indexes for the table
*
* @param string $table
* @return array
*/
2016-10-13 21:55:23 -04:00
public function getIndexes($table)
{
2016-10-13 21:55:23 -04:00
return $this->driverQuery($this->getSql()->indexList($this->prefixTable($table)), FALSE);
}
/**
* Retrieve list of data types for the database
*
* @return array
*/
2016-10-13 21:55:23 -04:00
public function getTypes()
{
2016-10-13 21:55:23 -04:00
return $this->driverQuery('typeList', FALSE);
}
2012-04-10 14:06:34 -04:00
/**
2014-04-22 14:02:54 -04:00
* Method to simplify retrieving db results for meta-data queries
*
* @param string|array|null $query
2016-10-13 21:55:23 -04:00
* @param bool $filteredIndex
* @return array
*/
2016-10-13 21:55:23 -04:00
public function driverQuery($query, $filteredIndex=TRUE)
{
// Call the appropriate method, if it exists
if (is_string($query) && method_exists($this->sql, $query))
{
2016-10-13 21:55:23 -04:00
$query = $this->getSql()->$query();
}
// Return if the values are returned instead of a query,
// or if the query doesn't apply to the driver
2015-11-11 09:25:21 -05:00
if ( ! is_string($query))
{
return $query;
}
// Run the query!
$res = $this->query($query);
2016-10-13 21:55:23 -04:00
$flag = ($filteredIndex) ? PDO::FETCH_NUM : PDO::FETCH_ASSOC;
$all = $res->fetchAll($flag);
2016-10-13 21:55:23 -04:00
return ($filteredIndex) ? \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
2016-09-07 17:39:19 -04:00
* @return int|null
*/
2016-10-13 21:55:23 -04:00
public function numRows()
{
2012-09-27 13:41:29 -04:00
$regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i';
2016-09-07 13:10:03 -04:00
$output = [];
2012-09-27 13:41:29 -04:00
2016-10-13 21:55:23 -04:00
if (preg_match($regex, $this->lastQuery, $output) > 0)
2012-09-27 13:41:29 -04:00
{
2014-02-17 19:31:06 -05:00
$stmt = $this->query("SELECT COUNT(*) FROM {$output[1]}");
return (int) $stmt->fetchColumn();
2012-09-27 13:41:29 -04:00
}
return NULL;
}
/**
* Create sql for batch insert
*
* @param string $table
2016-09-07 17:39:19 -04:00
* @param array|object $data
2015-07-30 13:13:12 -04:00
* @return null|array<string|array|null>
*/
2016-10-13 21:55:23 -04:00
public function insertBatch($table, $data=[])
{
2016-09-07 17:39:19 -04:00
$data = (array) $data;
2016-10-13 21:55:23 -04:00
$firstRow = (array) current($data);
if (is_scalar($firstRow))
{
return NULL;
}
2014-04-23 17:03:46 -04:00
// Values for insertion
2016-09-07 13:10:03 -04:00
$vals = [];
2014-04-23 17:03:46 -04:00
foreach($data as $group)
{
$vals = array_merge($vals, array_values($group));
}
2016-10-13 21:55:23 -04:00
$table = $this->quoteTable($table);
$fields = array_keys($firstRow);
$sql = "INSERT INTO {$table} ("
2016-10-13 21:55:23 -04:00
. implode(',', $this->quoteIdent($fields))
. ") VALUES ";
// Create the placeholder groups
$params = array_fill(0, count($fields), '?');
2016-10-13 21:55:23 -04:00
$paramString = "(" . implode(',', $params) . ")";
$paramList = array_fill(0, count($data), $paramString);
2014-04-23 17:03:46 -04:00
// Append the placeholder groups to the query
2016-10-13 21:55:23 -04:00
$sql .= implode(',', $paramList);
2016-09-07 13:10:03 -04:00
return [$sql, $vals];
}
2016-09-07 17:39:19 -04:00
/**
* Creates a batch update, and executes it.
* Returns the number of affected rows
*
* @param string $table
* @param array|object $data
* @param string $where
* @return int|null
*/
2016-10-13 21:55:23 -04:00
public function updateBatch($table, $data, $where)
2016-09-07 17:39:19 -04:00
{
// @TODO implement
return NULL;
}
/**
* Helper method for quote_ident
*
* @param mixed $str
* @return mixed
*/
public function _quote($str)
{
// Check that the current value is a string,
// and is not already quoted before quoting
// that value, otherwise, return the original value
return (
2014-04-28 16:41:46 -04:00
is_string($str)
2016-10-13 21:55:23 -04:00
&& strpos($str, $this->escapeCharOpen) !== 0
&& strrpos($str, $this->escapeCharClose) !== 0
)
2016-10-13 21:55:23 -04:00
? "{$this->escapeCharOpen}{$str}{$this->escapeCharClose}"
: $str;
}
/**
* Sets the table prefix on the passed string
*
* @param string $str
* @return string
*/
protected function _prefix($str)
{
// Don't prefix an already prefixed table
2016-10-13 21:55:23 -04:00
if (strpos($str, $this->tablePrefix) !== FALSE)
{
return $str;
}
2016-10-13 21:55:23 -04:00
return $this->tablePrefix . $str;
}
/**
* Empty the passed table
*
* @param string $table
2016-09-07 17:39:19 -04:00
* @return PDOStatement
*/
public function truncate($table)
{
2016-10-13 21:55:23 -04:00
$sql = ($this->hasTruncate)
2016-09-07 13:10:03 -04:00
? 'TRUNCATE TABLE '
: 'DELETE FROM ';
2016-10-13 21:55:23 -04:00
$sql .= $this->quoteTable($table);
$this->statement = $this->query($sql);
return $this->statement;
}
2016-10-13 21:55:23 -04:00
}