Query/src/Drivers/AbstractDriver.php

631 lines
14 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
*
2022-09-29 11:33:08 -04:00
* PHP version 8.1
2016-09-07 13:17:17 -04:00
*
* @package Query
2023-01-20 11:30:51 -05:00
* @author Timothy J. Warren <tim@timshome.page>
* @copyright 2012 - 2023 Timothy J. Warren
2016-09-07 13:17:17 -04:00
* @license http://www.opensource.org/licenses/mit-license.html MIT License
2019-12-11 16:49:42 -05:00
* @link https://git.timshomepage.net/aviat/Query
2023-03-17 16:34:21 -04:00
* @version 4.1.0
2012-03-15 09:25:18 -04:00
*/
2023-03-17 15:18:33 -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;
use PHPUnit\Framework\Attributes\CodeCoverageIgnore;
2020-04-23 18:16:32 -04:00
use function call_user_func_array;
use function dbFilter;
use function is_object;
use function is_string;
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
*/
2023-03-17 15:18:33 -04:00
abstract class AbstractDriver extends PDO implements DriverInterface
{
2014-03-31 16:01:58 -04:00
/**
* Reference to the last executed query
*/
protected PDOStatement $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
*/
protected string $escapeCharOpen = '"';
2016-09-07 17:39:19 -04:00
/**
* End character to escape identifiers
*/
protected string $escapeCharClose = '"';
2012-08-09 12:15:36 -04:00
2014-03-31 16:01:58 -04:00
/**
* Reference to sql class
*/
protected SQLInterface $driverSQL;
2012-08-09 12:15:36 -04:00
2014-03-31 16:01:58 -04:00
/**
* Reference to util class
*/
protected AbstractUtil $util;
2012-03-15 09:25:18 -04:00
2014-03-31 16:01:58 -04:00
/**
* Last query executed
*/
protected string $lastQuery = '';
2013-02-28 12:22:55 -05:00
2014-03-31 16:01:58 -04:00
/**
* Prefix to apply to table names
*/
protected string $tablePrefix = '';
2012-09-27 13:41:29 -04:00
/**
* Whether the driver supports 'TRUNCATE'
*/
protected bool $hasTruncate = TRUE;
2012-03-15 09:25:18 -04:00
/**
* PDO constructor wrapper
*/
2023-03-17 15:18:33 -04:00
public function __construct(string $dsn, ?string $username=NULL, ?string $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();
}
/**
* Allow invoke to work on table object
*
2014-04-22 14:02:54 -04:00
* @return mixed
*/
#[CodeCoverageIgnore]
2016-10-12 22:12:25 -04:00
public function __call(string $name, array $args = [])
{
if (
isset($this->$name)
2020-04-23 18:16:32 -04:00
&& is_object($this->$name)
&& method_exists($this->$name, '__invoke')
2023-03-17 15:18:33 -04:00
) {
2020-04-23 18:16:32 -04:00
return call_user_func_array([$this->$name, '__invoke'], $args);
}
2019-12-11 16:49:06 -05:00
return NULL;
}
2023-03-17 15:18:33 -04:00
/**
* Loads the subclasses for the driver
*/
protected function _loadSubClasses(): void
{
// Load the sql and util class for the driver
$thisClass = static::class;
2023-03-17 15:18:33 -04:00
$nsArray = explode('\\', $thisClass);
array_pop($nsArray);
$driver = array_pop($nsArray);
$sqlClass = __NAMESPACE__ . "\\{$driver}\\SQL";
$utilClass = __NAMESPACE__ . "\\{$driver}\\Util";
$this->driverSQL = new $sqlClass();
$this->util = new $utilClass($this);
}
// --------------------------------------------------------------------------
// ! Accessors / Mutators
// --------------------------------------------------------------------------
/**
2016-09-07 17:39:19 -04:00
* Get the last sql query executed
*/
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
*/
2018-01-22 15:43:56 -05:00
public function setLastQuery(string $queryString): void
{
2016-10-13 21:55:23 -04:00
$this->lastQuery = $queryString;
}
/**
* Get the SQL class for the current driver
*/
2016-10-13 21:55:23 -04:00
public function getSql(): SQLInterface
{
return $this->driverSQL;
}
/**
* Get the Util class for the current driver
*/
2016-10-13 21:55:23 -04:00
public function getUtil(): AbstractUtil
{
return $this->util;
}
/**
* Set the common table name prefix
*/
2018-01-24 13:14:03 -05:00
public function setTablePrefix(string $prefix): void
{
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
*/
public function prepareQuery(string $sql, array $data): PDOStatement
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
// Bind the parameters
2023-03-17 15:18:33 -04:00
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
2023-03-17 15:18:33 -04:00
if (is_numeric($k))
2015-11-11 09:25:21 -05:00
{
$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
*
2018-01-24 13:14:03 -05:00
* @throws InvalidArgumentException
2012-03-15 09:25:18 -04:00
*/
public function prepareExecute(string $sql, array $params): PDOStatement
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
*/
2018-01-22 15:43:56 -05:00
public function affectedRows(): int
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
2012-11-07 08:42:34 -05:00
*/
2018-01-24 13:14:03 -05:00
public function prefixTable(string $table): string
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
*/
2020-04-23 18:16:32 -04:00
public function quoteTable(string $table): string
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
*/
2023-01-13 13:14:28 -05:00
public function quoteIdent(string|array $identifier): string|array
{
2019-12-10 12:17:40 -05:00
if (is_array($identifier))
2012-03-15 09:25:18 -04:00
{
return array_map(__METHOD__, $identifier);
2012-03-15 09:25:18 -04:00
}
2012-08-09 12:15:36 -04:00
2020-04-23 17:00:35 -04:00
// Make all the string-handling methods happy
2022-09-29 11:31:25 -04:00
// $identifier = (string)$identifier;
2020-04-23 17:00:35 -04:00
// Handle comma-separated identifiers
if (str_contains($identifier, ','))
{
2016-09-07 17:39:19 -04:00
$parts = array_map('mb_trim', explode(',', $identifier));
$parts = array_map(__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
$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);
2023-03-17 15:18:33 -04:00
foreach ($funcs as $f)
{
// Unquote the function
// Quote the inside identifiers
2020-04-23 18:16:32 -04:00
$raw = str_replace([$f[0], $f[3]], [$f[1], $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
2012-03-15 09:25:18 -04:00
*/
2018-01-22 15:43:56 -05:00
public function getSchemas(): ?array
2012-04-10 14:06:34 -04:00
{
2019-12-11 16:49:06 -05:00
// Most DBMSs conflate schemas and databases
return $this->getDbs();
2012-04-10 14:06:34 -04:00
}
2012-03-15 09:25:18 -04:00
/**
* Return list of tables for the current database
*/
2018-01-22 15:43:56 -05:00
public function getTables(): ?array
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);
2023-03-17 15:18:33 -04:00
2014-04-28 16:41:46 -04:00
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
*/
2019-12-11 16:49:06 -05:00
public function getDbs(): ?array
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
2012-03-15 09:25:18 -04:00
*/
2018-01-22 15:43:56 -05:00
public function getViews(): ?array
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);
2023-03-17 15:18:33 -04:00
2014-04-28 16:41:46 -04:00
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
2012-03-15 09:25:18 -04:00
*/
2018-01-22 15:43:56 -05:00
public function getSequences(): ?array
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
2023-01-20 10:33:43 -05:00
*
* @deprecated Will be removed in next version
2012-03-15 09:25:18 -04:00
*/
2018-01-22 15:43:56 -05:00
public function getFunctions(): ?array
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
2023-01-20 10:33:43 -05:00
*
* @deprecated Will be removed in next version
2012-03-15 09:25:18 -04:00
*/
2018-01-22 15:43:56 -05:00
public function getProcedures(): ?array
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
2023-01-20 10:33:43 -05:00
*
* @deprecated Will be removed in next version
2012-03-15 09:25:18 -04:00
*/
2018-01-22 15:43:56 -05:00
public function getTriggers(): ?array
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
2012-03-15 09:25:18 -04:00
*/
2018-01-22 15:43:56 -05:00
public function getSystemTables(): ?array
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
*/
2019-12-11 16:49:06 -05:00
public function getColumns(string $table): ?array
{
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
*/
2019-12-11 16:49:06 -05:00
public function getFks(string $table): ?array
{
2016-10-13 21:55:23 -04:00
return $this->driverQuery($this->getSql()->fkList($table), FALSE);
}
/**
* Retrieve indexes for the table
*/
2019-12-11 16:49:06 -05:00
public function getIndexes(string $table): ?array
{
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
*/
2018-01-22 15:43:56 -05:00
public function getTypes(): ?array
{
2016-10-13 21:55:23 -04:00
return $this->driverQuery('typeList', FALSE);
}
2012-04-10 14:06:34 -04:00
/**
* Get the version of the database engine
*/
public function getVersion(): string
{
return $this->getAttribute(PDO::ATTR_SERVER_VERSION);
}
/**
2014-04-22 14:02:54 -04:00
* Method to simplify retrieving db results for meta-data queries
*/
2023-01-13 13:14:28 -05:00
public function driverQuery(string|array $query, bool $filteredIndex=TRUE): ?array
{
// Call the appropriate method, if it exists
if (is_string($query) && method_exists($this->driverSQL, $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
2019-12-10 12:17:40 -05:00
if ( ! is_string($query))
2015-11-11 09:25:21 -05:00
{
return $query;
}
// Run the query!
$res = $this->query($query);
2018-01-22 15:43:56 -05:00
$flag = $filteredIndex ? PDO::FETCH_NUM : PDO::FETCH_ASSOC;
$all = $res->fetchAll($flag);
2019-12-10 12:17:40 -05:00
return $filteredIndex ? dbFilter($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
*/
2018-01-22 15:43:56 -05:00
public function numRows(): ?int
{
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]}");
2023-03-17 15:18:33 -04:00
return (int) $stmt->fetchColumn();
2012-09-27 13:41:29 -04:00
}
return NULL;
}
/**
* Create sql for batch insert
*/
2018-01-24 13:14:03 -05:00
public function insertBatch(string $table, array $data=[]): array
{
2016-09-07 17:39:19 -04:00
$data = (array) $data;
$firstRow = (array) current($data);
2014-04-23 17:03:46 -04:00
// Values for insertion
2016-09-07 13:10:03 -04:00
$vals = [];
2023-03-17 15:18:33 -04:00
foreach ($data as $group)
2014-04-23 17:03:46 -04:00
{
$vals = [...$vals, ...array_values($group)];
2014-04-23 17:03:46 -04:00
}
2019-12-10 12:17:40 -05:00
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), '?');
2018-01-22 15:43:56 -05:00
$paramString = '(' . implode(',', $params) . ')';
2016-10-13 21:55:23 -04:00
$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
*
2018-01-26 08:39:30 -05:00
* @param string $table The table to update
* @param array $data an array of update values
* @param string $where The where key
2016-09-07 17:39:19 -04:00
*/
2018-01-26 08:39:30 -05:00
public function updateBatch(string $table, array $data, string $where): array
2016-09-07 17:39:19 -04:00
{
2018-01-26 08:39:30 -05:00
$affectedRows = 0;
$insertData = [];
$fieldLines = [];
$sql = 'UPDATE ' . $this->quoteTable($table) . ' SET ';
// Get the keys of the current set of data, except the one used to
// set the update condition
$fields = array_unique(
array_reduce($data, static function ($previous, $current) use (&$affectedRows, $where): array {
2018-02-09 16:14:40 -05:00
$affectedRows++;
2018-01-26 08:39:30 -05:00
$keys = array_diff(array_keys($current), [$where]);
2018-02-09 16:14:40 -05:00
if ($previous === NULL)
{
return $keys;
}
2018-01-26 08:39:30 -05:00
2018-02-09 16:14:40 -05:00
return array_merge($previous, $keys);
})
2018-01-26 08:39:30 -05:00
);
// Create the CASE blocks for each data set
foreach ($fields as $field)
{
$line = $this->quoteIdent($field) . " = CASE\n";
$cases = [];
2023-03-17 15:18:33 -04:00
2018-01-26 08:39:30 -05:00
foreach ($data as $case)
{
if (array_key_exists($field, $case))
{
$insertData[] = $case[$where];
$insertData[] = $case[$field];
$cases[] = 'WHEN ' . $this->quoteIdent($where) . ' =? '
. 'THEN ? ';
}
}
$line .= implode("\n", $cases) . "\n";
$line .= 'ELSE ' . $this->quoteIdent($field) . ' END';
$fieldLines[] = $line;
}
$sql .= implode(",\n", $fieldLines) . "\n";
$whereValues = array_column($data, $where);
2023-03-17 15:18:33 -04:00
2018-01-26 08:39:30 -05:00
foreach ($whereValues as $value)
{
$insertData[] = $value;
}
// Create the placeholders for the WHERE IN clause
$placeholders = array_fill(0, count($whereValues), '?');
$sql .= 'WHERE ' . $this->quoteIdent($where) . ' IN ';
$sql .= '(' . implode(',', $placeholders) . ')';
return [$sql, $insertData, $affectedRows];
2016-09-07 17:39:19 -04:00
}
2018-01-24 13:14:03 -05:00
/**
* Empty the passed table
*/
public function truncate(string $table): PDOStatement
2018-01-24 13:14:03 -05:00
{
$sql = $this->hasTruncate
? 'TRUNCATE TABLE '
: 'DELETE FROM ';
$sql .= $this->quoteTable($table);
$this->statement = $this->query($sql);
2023-03-17 15:18:33 -04:00
2018-01-24 13:14:03 -05:00
return $this->statement;
}
/**
* Generate the returning clause for the current database
*/
public function returning(string $query, string $select): string
{
return "{$query} RETURNING {$select}";
}
/**
* Helper method for quote_ident
*/
2023-01-13 13:14:28 -05:00
public function _quote(mixed $str): mixed
{
// Check that the current value is a string,
// and is not already quoted before quoting
// that value, otherwise, return the original value
return (
is_string($str)
&& ( ! str_starts_with($str, $this->escapeCharOpen))
2016-10-13 21:55:23 -04:00
&& 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
*/
2018-01-24 13:14:03 -05:00
protected function _prefix(string $str): string
{
// Don't prefix an already prefixed table
if (str_contains($str, $this->tablePrefix))
{
return $str;
}
2016-10-13 21:55:23 -04:00
return $this->tablePrefix . $str;
}
2019-12-10 12:17:40 -05:00
}