Source of file AbstractDriver.php
Size: 15,025 Bytes - Last Modified: 2018-01-25T22:02:43+00:00
src/Drivers/AbstractDriver.php
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
Covered by 7 test(s):
90
Covered by 7 test(s):
9192
Covered by 7 test(s):
93949596979899100101102103
Covered by 7 test(s):
104
Covered by 7 test(s):
105
Covered by 7 test(s):
106
Covered by 7 test(s):
107
Covered by 7 test(s):
108
Covered by 7 test(s):
109110
Covered by 7 test(s):
111
Covered by 7 test(s):
112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
Covered by 3 test(s):
146147148149150151152153154155156
Covered by 177 test(s):
157158159160161162163164165166
Covered by 97 test(s):
167168169170171172173174175176
Covered by 9 test(s):
177178179180181182183184185186187
Covered by 2 test(s):
188189190191192193194195196197198199200201202203204205
Covered by 126 test(s):
206207208
Covered by 126 test(s):
209210211212
Covered by 126 test(s):
213214
Covered by 126 test(s):
215216
Covered by 126 test(s):
217218219
Covered by 126 test(s):
220221222223224225226227228229230231232
Covered by 123 test(s):
233
Covered by 123 test(s):
234235
Covered by 123 test(s):
236237238239240241242243244245246
Covered by 3 test(s):
247248249250251252253254255256257258
Covered by 201 test(s):
259260261262263264265
Covered by 201 test(s):
266
Covered by 201 test(s):
267268269
Covered by 201 test(s):
270271272
Covered by 201 test(s):
273274275
Covered by 201 test(s):
276277278279280281282283284285286
Covered by 195 test(s):
287288289
Covered by 195 test(s):
290291292293294295296297298299300
Covered by 195 test(s):
301302
Covered by 150 test(s):
303304305306
Covered by 195 test(s):
307308
Covered by 3 test(s):
309
Covered by 3 test(s):
310
Covered by 3 test(s):
311312313314
Covered by 195 test(s):
315
Covered by 195 test(s):
316317318
Covered by 195 test(s):
319320321
Covered by 195 test(s):
322
Covered by 195 test(s):
323
Covered by 195 test(s):
324325326
Covered by 3 test(s):
327328329
Covered by 3 test(s):
330331332
Covered by 195 test(s):
333334335336337338339340341342
Covered by 2 test(s):
343344345346347348349350351352
Covered by 6 test(s):
353
Covered by 6 test(s):
354
Covered by 6 test(s):
355356357358359360361362363364
Covered by 3 test(s):
365366367368369370371372373374
Covered by 3 test(s):
375
Covered by 3 test(s):
376
Covered by 3 test(s):
377378379380381382383384385386
Covered by 3 test(s):
387388389390391392393394395396
Covered by 3 test(s):
397398399400401402403404405406
Covered by 3 test(s):
407408409410411412413414415416
Covered by 3 test(s):
417418419420421422423424425426427
Covered by 3 test(s):
428429430431432433434435436437438
Covered by 3 test(s):
439440441442443444445446447448449
Covered by 3 test(s):
450451452453454455456457458459460
Covered by 3 test(s):
461462463464465466467468469470
Covered by 3 test(s):
471472473474475476477478479480481482483
Covered by 40 test(s):
484485
Covered by 30 test(s):
486487488489490
Covered by 40 test(s):
491492
Covered by 7 test(s):
493494495496
Covered by 33 test(s):
497498
Covered by 33 test(s):
499
Covered by 33 test(s):
500501
Covered by 33 test(s):
502503504505506507508509510511512
Covered by 9 test(s):
513
Covered by 9 test(s):
514515
Covered by 9 test(s):
516517
Covered by 6 test(s):
518
Covered by 6 test(s):
519520521
Covered by 3 test(s):
522523524525526527528529530531532533
Covered by 3 test(s):
534
Covered by 3 test(s):
535536537
Covered by 3 test(s):
538
Covered by 3 test(s):
539540
Covered by 3 test(s):
541542
Covered by 3 test(s):
543
Covered by 3 test(s):
544545
Covered by 3 test(s):
546
Covered by 3 test(s):
547
Covered by 3 test(s):
548549550
Covered by 3 test(s):
551
Covered by 3 test(s):
552
Covered by 3 test(s):
553554555
Covered by 3 test(s):
556557
Covered by 3 test(s):
558559560561562563564565566567568569570571
Covered by 3 test(s):
572
Covered by 3 test(s):
573
Covered by 3 test(s):
574575
Covered by 3 test(s):
576577578579
Covered by 3 test(s):
580581
Covered by 3 test(s):
582
Covered by 3 test(s):
583584
Covered by 3 test(s):
585586
Covered by 3 test(s):
587588589
Covered by 3 test(s):
590
Covered by 3 test(s):
591592593594
Covered by 3 test(s):
595596
Covered by 3 test(s):
597598
Covered by 3 test(s):
599
Covered by 3 test(s):
600601
Covered by 3 test(s):
602603
Covered by 3 test(s):
604
Covered by 3 test(s):
605
Covered by 3 test(s):
606
Covered by 3 test(s):
607608609610
Covered by 3 test(s):
611
Covered by 3 test(s):
612613
Covered by 3 test(s):
614615616
Covered by 3 test(s):
617618
Covered by 3 test(s):
619
Covered by 3 test(s):
620621
Covered by 3 test(s):
622623624625
Covered by 3 test(s):
626627
Covered by 3 test(s):
628
Covered by 3 test(s):
629630
Covered by 3 test(s):
631632633634635636637638639640641
Covered by 3 test(s):
642
Covered by 2 test(s):
643
Covered by 3 test(s):
644645
Covered by 3 test(s):
646647
Covered by 3 test(s):
648
Covered by 3 test(s):
649650651652653654655656657658659660661662663
Covered by 195 test(s):
664
Covered by 195 test(s):
665
Covered by 195 test(s):
666667
Covered by 195 test(s):
668
Covered by 195 test(s):
669670671672673674675676677678679680681
Covered by 201 test(s):
682683
Covered by 5 test(s):
684685686
Covered by 196 test(s):
687688
| <?php declare(strict_types=1); /** * Query * * SQL Query Builder / Database Abstraction Layer * * PHP version 7.1 * * @package Query * @author Timothy J. Warren <tim@timshomepage.net> * @copyright 2012 - 2018 Timothy J. Warren * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link https://git.timshomepage.net/aviat4ion/Query */ namespace Query\Drivers; use InvalidArgumentException; use PDO; use PDOStatement; /** * Base Database class * * Extends PDO to simplify cross-database issues */ abstract class AbstractDriver extends PDO implements DriverInterface { /** * Reference to the last executed query * @var PDOStatement */ protected $statement; /** * Start character to escape identifiers * @var string */ protected $escapeCharOpen = '"'; /** * End character to escape identifiers * @var string */ protected $escapeCharClose = '"'; /** * Reference to sql class * @var SQLInterface */ protected $sql; /** * Reference to util class * @var AbstractUtil */ protected $util; /** * Last query executed * @var string */ protected $lastQuery = ''; /** * Prefix to apply to table names * @var string */ protected $tablePrefix = ''; /** * Whether the driver supports 'TRUNCATE' * @var boolean */ protected $hasTruncate = TRUE; /** * PDO constructor wrapper * * @param string $dsn * @param string $username * @param string $password * @param array $driverOptions */ public function __construct(string $dsn, string $username=NULL, string $password=NULL, array $driverOptions=[]) { // Set PDO to display errors as exceptions, and apply driver options $driverOptions[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION; parent::__construct($dsn, $username, $password, $driverOptions); $this->_loadSubClasses(); } /** * Loads the subclasses for the driver * * @return void */ protected function _loadSubClasses(): void { // Load the sql and util class for the driver $thisClass = \get_class($this); $nsArray = explode("\\", $thisClass); array_pop($nsArray); $driver = array_pop($nsArray); $sqlClass = __NAMESPACE__ . "\\{$driver}\\SQL"; $utilClass = __NAMESPACE__ . "\\{$driver}\\Util"; $this->sql = new $sqlClass(); $this->util = new $utilClass($this); } /** * Allow invoke to work on table object * * @codeCoverageIgnore * @param string $name * @param array $args * @return mixed */ public function __call(string $name, array $args = []) { if ( isset($this->$name) && \is_object($this->$name) && method_exists($this->$name, '__invoke') ) { return \call_user_func_array([$this->$name, '__invoke'], $args); } } // -------------------------------------------------------------------------- // ! Accessors / Mutators // -------------------------------------------------------------------------- /** * Get the last sql query executed * * @return string */ public function getLastQuery(): string { return $this->lastQuery; } /** * Set the last query sql * * @param string $queryString * @return void */ public function setLastQuery(string $queryString): void { $this->lastQuery = $queryString; } /** * Get the SQL class for the current driver * * @return SQLInterface */ public function getSql(): SQLInterface { return $this->sql; } /** * Get the Util class for the current driver * * @return AbstractUtil */ public function getUtil(): AbstractUtil { return $this->util; } /** * Set the common table name prefix * * @param string $prefix * @return void */ public function setTablePrefix(string $prefix): void { $this->tablePrefix = $prefix; } // -------------------------------------------------------------------------- // ! Concrete functions that can be overridden in child classes // -------------------------------------------------------------------------- /** * Simplifies prepared statements for database queries * * @param string $sql * @param array $data * @return PDOStatement | FALSE * @throws InvalidArgumentException */ public function prepareQuery(string $sql, array $data): ?PDOStatement { // Prepare the sql, save the statement for easy access later $this->statement = $this->prepare($sql); // Bind the parameters foreach($data as $k => $value) { // Parameters are 1-based, the data is 0-based // So, if the key is numeric, add 1 if(is_numeric($k)) { $k++; } $this->statement->bindValue($k, $value); } return $this->statement; } /** * Create and execute a prepared statement with the provided parameters * * @param string $sql * @param array $params * @throws InvalidArgumentException * @return PDOStatement */ public function prepareExecute(string $sql, array $params): ?PDOStatement { $this->statement = $this->prepareQuery($sql, $params); $this->statement->execute(); return $this->statement; } /** * Returns number of rows affected by an INSERT, UPDATE, DELETE type query * * @return int */ public function affectedRows(): int { // Return number of rows affected return $this->statement->rowCount(); } /** * Prefixes a table if it is not already prefixed * @param string $table * @return string */ public function prefixTable(string $table): string { // Add the prefix to the table name // before quoting it if ( ! empty($this->tablePrefix)) { // Split identifier by period, will split into: // database.schema.table OR // schema.table OR // database.table OR // table $identifiers = explode('.', $table); $segments = count($identifiers); // Quote the last item, and add the database prefix $identifiers[$segments - 1] = $this->_prefix(end($identifiers)); // Rejoin $table = implode('.', $identifiers); } return $table; } /** * Quote database table name, and set prefix * * @param string $table * @return string */ public function quoteTable($table): string { $table = $this->prefixTable($table); // Finally, quote the table return $this->quoteIdent($table); } /** * Surrounds the string with the databases identifier escape characters * * @param mixed $identifier * @return string|array */ public function quoteIdent($identifier) { if (\is_array($identifier)) { return array_map([$this, __METHOD__], $identifier); } // Handle comma-separated identifiers if (strpos($identifier, ',') !== FALSE) { $parts = array_map('mb_trim', explode(',', $identifier)); $parts = array_map([$this, __METHOD__], $parts); $identifier = implode(',', $parts); } // Split each identifier by the period $hiers = explode('.', $identifier); $hiers = array_map('mb_trim', $hiers); // Re-compile the string $raw = implode('.', array_map([$this, '_quote'], $hiers)); // Fix functions $funcs = []; 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 $raw = str_replace($f[3], $this->quoteIdent($f[3]), $raw); } return $raw; } /** * Return schemas for databases that list them * * @return array */ public function getSchemas(): ?array { return NULL; } /** * Return list of tables for the current database * * @return array */ public function getTables(): ?array { $tables = $this->driverQuery('tableList'); natsort($tables); return $tables; } /** * Return list of dbs for the current connection, if possible * * @return array */ public function getDbs(): array { return $this->driverQuery('dbList'); } /** * Return list of views for the current database * * @return array */ public function getViews(): ?array { $views = $this->driverQuery('viewList'); sort($views); return $views; } /** * Return list of sequences for the current database, if they exist * * @return array */ public function getSequences(): ?array { return $this->driverQuery('sequenceList'); } /** * Return list of functions for the current database * * @return array */ public function getFunctions(): ?array { return $this->driverQuery('functionList', FALSE); } /** * Return list of stored procedures for the current database * * @return array */ public function getProcedures(): ?array { return $this->driverQuery('procedureList', FALSE); } /** * Return list of triggers for the current database * * @return array */ public function getTriggers(): ?array { return $this->driverQuery('triggerList', FALSE); } /** * Retrieves an array of non-user-created tables for * the connection/database * * @return array */ public function getSystemTables(): ?array { return $this->driverQuery('systemTableList'); } /** * Retrieve column information for the current database table * * @param string $table * @return array */ public function getColumns($table): ?array { return $this->driverQuery($this->getSql()->columnList($this->prefixTable($table)), FALSE); } /** * Retrieve foreign keys for the table * * @param string $table * @return array */ public function getFks($table): ?array { return $this->driverQuery($this->getSql()->fkList($table), FALSE); } /** * Retrieve indexes for the table * * @param string $table * @return array */ public function getIndexes($table): ?array { return $this->driverQuery($this->getSql()->indexList($this->prefixTable($table)), FALSE); } /** * Retrieve list of data types for the database * * @return array */ public function getTypes(): ?array { return $this->driverQuery('typeList', FALSE); } /** * Method to simplify retrieving db results for meta-data queries * * @param string|array|null $query * @param bool $filteredIndex * @return array|null */ public function driverQuery($query, $filteredIndex=TRUE): ?array { // Call the appropriate method, if it exists if (\is_string($query) && method_exists($this->sql, $query)) { $query = $this->getSql()->$query(); } // Return if the values are returned instead of a query, // or if the query doesn't apply to the driver if ( ! \is_string($query)) { return $query; } // Run the query! $res = $this->query($query); $flag = $filteredIndex ? PDO::FETCH_NUM : PDO::FETCH_ASSOC; $all = $res->fetchAll($flag); return $filteredIndex ? \dbFilter($all, 0) : $all; } /** * Return the number of rows returned for a SELECT query * * @see http://us3.php.net/manual/en/pdostatement.rowcount.php#87110 * @return int|null */ public function numRows(): ?int { $regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i'; $output = []; if (preg_match($regex, $this->lastQuery, $output) > 0) { $stmt = $this->query("SELECT COUNT(*) FROM {$output[1]}"); return (int) $stmt->fetchColumn(); } return NULL; } /** * Create sql for batch insert * * @param string $table * @param mixed $data * @return null|array<string|array|null> */ public function insertBatch(string $table, array $data=[]): array { $data = (array) $data; $firstRow = (array) current($data); // Values for insertion $vals = []; foreach($data as $group) { $vals = array_merge($vals, array_values($group)); } $table = $this->quoteTable($table); $fields = array_keys($firstRow); $sql = "INSERT INTO {$table} (" . implode(',', $this->quoteIdent($fields)) . ') VALUES '; // Create the placeholder groups $params = array_fill(0, count($fields), '?'); $paramString = '(' . implode(',', $params) . ')'; $paramList = array_fill(0, count($data), $paramString); // Append the placeholder groups to the query $sql .= implode(',', $paramList); return [$sql, $vals]; } /** * Creates a batch update, and executes it. * Returns the number of affected rows * * @param string $table The table to update * @param array $data an array of update values * @param string $where The where key * @return array<string,array,int> */ public function updateBatch(string $table, array $data, string $where): array { $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, function ($previous, $current) use (&$affectedRows, $where) { $affectedRows++; $keys = array_diff(array_keys($current), [$where]); if ($previous === NULL) { return $keys; } return array_merge($previous, $keys); }) ); // Create the CASE blocks for each data set foreach ($fields as $field) { $line = $this->quoteIdent($field) . " = CASE\n"; $cases = []; 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); 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]; } /** * Empty the passed table * * @param string $table * @return PDOStatement */ public function truncate(string $table): ?PDOStatement { $sql = $this->hasTruncate ? 'TRUNCATE TABLE ' : 'DELETE FROM '; $sql .= $this->quoteTable($table); $this->statement = $this->query($sql); return $this->statement; } /** * 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 ( \is_string($str) && strpos($str, $this->escapeCharOpen) !== 0 && strrpos($str, $this->escapeCharClose) !== 0 ) ? "{$this->escapeCharOpen}{$str}{$this->escapeCharClose}" : $str; } /** * Sets the table prefix on the passed string * * @param string $str * @return string */ protected function _prefix(string $str): string { // Don't prefix an already prefixed table if (strpos($str, $this->tablePrefix) !== FALSE) { return $str; } return $this->tablePrefix . $str; } } |