Query/src/AbstractQueryBuilder.php

611 lines
12 KiB
PHP
Raw Normal View History

2016-10-12 22:12:25 -04:00
<?php declare(strict_types=1);
2014-04-24 17:07:50 -04:00
/**
* Query
*
2016-09-07 13:17:17 -04:00
* SQL Query Builder / Database Abstraction Layer
2014-04-24 17:07:50 -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
2014-04-24 17:07:50 -04:00
*/
namespace Query;
2016-10-13 21:55:23 -04:00
use PDOStatement;
2014-04-24 17:07:50 -04:00
/**
* Abstract Class for internal implementation methods of the Query Builder
* @package Query
*/
2015-11-10 10:12:23 -05:00
abstract class AbstractQueryBuilder {
2014-04-24 17:07:50 -04:00
// --------------------------------------------------------------------------
// ! Constants
// --------------------------------------------------------------------------
2014-04-24 21:29:40 -04:00
const KEY = 0;
const VALUE = 1;
2014-04-24 21:29:40 -04:00
const BOTH = 2;
2014-04-24 17:07:50 -04:00
// --------------------------------------------------------------------------
// ! SQL Clause Strings
// --------------------------------------------------------------------------
/**
* Compiled 'select' clause
* @var string
*/
2016-10-13 21:55:23 -04:00
protected $selectString = '';
2014-04-24 17:07:50 -04:00
/**
* Compiled 'from' clause
* @var string
*/
2016-10-13 21:55:23 -04:00
protected $fromString = '';
2014-04-24 17:07:50 -04:00
/**
* Compiled arguments for insert / update
* @var string
*/
2016-10-13 21:55:23 -04:00
protected $setString;
2014-04-24 17:07:50 -04:00
/**
* Order by clause
* @var string
*/
2016-10-13 21:55:23 -04:00
protected $orderString;
2014-04-24 17:07:50 -04:00
/**
* Group by clause
* @var string
*/
2016-10-13 21:55:23 -04:00
protected $groupString;
2014-04-24 17:07:50 -04:00
// --------------------------------------------------------------------------
// ! SQL Clause Arrays
// --------------------------------------------------------------------------
/**
* Keys for insert/update statement
* @var array
*/
2016-10-13 21:55:23 -04:00
protected $setArrayKeys = [];
2014-04-24 17:07:50 -04:00
/**
* Key/val pairs for order by clause
* @var array
*/
2016-10-13 21:55:23 -04:00
protected $orderArray = [];
2014-04-24 17:07:50 -04:00
/**
* Key/val pairs for group by clause
* @var array
*/
2016-10-13 21:55:23 -04:00
protected $groupArray = [];
2014-04-24 17:07:50 -04:00
// --------------------------------------------------------------------------
// ! Other Class vars
// --------------------------------------------------------------------------
/**
* Values to apply to prepared statements
* @var array
*/
2016-09-07 13:10:03 -04:00
protected $values = [];
2014-04-24 17:07:50 -04:00
/**
* Values to apply to where clauses in prepared statements
* @var array
*/
2016-10-13 21:55:23 -04:00
protected $whereValues = [];
2014-04-24 17:07:50 -04:00
/**
* Value for limit string
* @var string
*/
protected $limit;
/**
* Value for offset in limit string
2016-09-07 13:10:03 -04:00
* @var integer
2014-04-24 17:07:50 -04:00
*/
protected $offset;
/**
* Query component order mapping
* for complex select queries
*
* Format:
* array(
* 'type' => 'where',
* 'conjunction' => ' AND ',
* 'string' => 'k=?'
* )
*
* @var array
*/
2016-10-13 21:55:23 -04:00
protected $queryMap = [];
2014-04-24 17:07:50 -04:00
/**
* Map for having clause
* @var array
*/
2016-10-13 21:55:23 -04:00
protected $havingMap;
2014-04-24 17:07:50 -04:00
/**
* Convenience property for connection management
* @var string
*/
2016-10-13 21:55:23 -04:00
public $connName = "";
2014-04-24 17:07:50 -04:00
/**
* List of queries executed
* @var array
*/
public $queries;
/**
* Whether to do only an explain on the query
2016-09-07 13:10:03 -04:00
* @var boolean
2014-04-24 17:07:50 -04:00
*/
protected $explain;
/**
* The current database driver
2016-09-07 17:39:19 -04:00
* @var \Query\Drivers\DriverInterface
*/
public $db;
/**
* Query parser class instance
2015-11-10 20:58:32 -05:00
* @var QueryParser
*/
2015-11-10 09:24:18 -05:00
public $parser;
/**
* Alias to driver util class
2016-09-07 17:39:19 -04:00
* @var \Query\Drivers\AbstractUtil
*/
2015-11-10 09:24:18 -05:00
public $util;
/**
* Alias to driver sql class
2016-09-07 17:39:19 -04:00
* @var \Query\Drivers\SQLInterface
*/
2015-11-10 09:24:18 -05:00
public $sql;
2014-04-24 17:07:50 -04:00
// --------------------------------------------------------------------------
// Methods
// --------------------------------------------------------------------------
/**
* Set values in the class, with either an array or key value pair
2014-04-24 17:07:50 -04:00
*
* @param array $var
* @param mixed $key
* @param mixed $val
2016-10-13 21:55:23 -04:00
* @param int $valType
* @return array
2014-04-24 17:07:50 -04:00
*/
2016-10-13 21:55:23 -04:00
protected function _mixedSet(array &$var, $key, $val=NULL, int $valType=self::BOTH): array
2014-04-24 17:07:50 -04:00
{
$arg = (is_scalar($key) && is_scalar($val))
2016-09-07 13:10:03 -04:00
? [$key => $val]
: $key;
2014-04-24 17:07:50 -04:00
foreach($arg as $k => $v)
2014-04-24 17:07:50 -04:00
{
2016-10-13 21:55:23 -04:00
if (in_array($valType, [self::KEY, self::VALUE]))
2014-04-24 17:07:50 -04:00
{
2016-10-13 21:55:23 -04:00
$var[] = ($valType === self::KEY)
2014-04-24 21:29:40 -04:00
? $k
: $v;
}
else
{
$var[$k] = $v;
2014-04-24 17:07:50 -04:00
}
}
return $var;
2014-04-24 17:07:50 -04:00
}
/**
* Method to simplify select_ methods
*
* @param string $field
* @param string|bool $as
* @return string
*/
2016-10-13 21:55:23 -04:00
protected function _select(string $field, $as = FALSE): string
2014-04-24 17:07:50 -04:00
{
// Escape the identifiers
2016-10-13 21:55:23 -04:00
$field = $this->db->quoteIdent($field);
2014-04-24 17:07:50 -04:00
2015-11-11 09:25:21 -05:00
if ( ! is_string($as))
{
return $field;
}
2014-04-24 17:07:50 -04:00
2016-10-13 21:55:23 -04:00
$as = $this->db->quoteIdent($as);
2014-04-24 17:07:50 -04:00
return "({$field}) AS {$as} ";
}
/**
* Helper function for returning sql strings
*
* @param string $type
* @param string $table
* @param bool $reset
* @return string
*/
2016-10-13 21:55:23 -04:00
protected function _getCompile(string $type, string $table, bool $reset): string
2014-04-24 17:07:50 -04:00
{
$sql = $this->_compile($type, $table);
// Reset the query builder for the next query
2015-11-11 09:25:21 -05:00
if ($reset)
{
2016-10-13 21:55:23 -04:00
$this->resetQuery();
2015-11-11 09:25:21 -05:00
}
2014-04-24 17:07:50 -04:00
return $sql;
}
/**
* Simplify 'like' methods
*
* @param string $field
* @param mixed $val
* @param string $pos
* @param string $like
* @param string $conj
2016-10-12 22:12:25 -04:00
* @return QueryBuilderInterface
2014-04-24 17:07:50 -04:00
*/
2016-10-13 21:55:23 -04:00
protected function _like(string $field, $val, string $pos, string $like='LIKE', string $conj='AND'): QueryBuilderInterface
2014-04-24 17:07:50 -04:00
{
2016-10-13 21:55:23 -04:00
$field = $this->db->quoteIdent($field);
2014-04-24 17:07:50 -04:00
// Add the like string into the order map
$like = $field. " {$like} ?";
2014-04-24 17:07:50 -04:00
if ($pos == 'before')
{
$val = "%{$val}";
}
elseif ($pos == 'after')
{
$val = "{$val}%";
}
else
{
$val = "%{$val}%";
}
2016-10-13 21:55:23 -04:00
$conj = (empty($this->queryMap)) ? ' WHERE ' : " {$conj} ";
$this->_appendMap($conj, $like, 'like');
2014-04-24 17:07:50 -04:00
// Add to the values array
2016-10-13 21:55:23 -04:00
$this->whereValues[] = $val;
2014-04-24 17:07:50 -04:00
return $this;
}
/**
* Simplify building having clauses
*
* @param mixed $key
* @param mixed $val
* @param string $conj
2016-10-12 22:12:25 -04:00
* @return QueryBuilderInterface
2014-04-24 17:07:50 -04:00
*/
2016-10-13 21:55:23 -04:00
protected function _having($key, $val=[], string $conj='AND'): QueryBuilderInterface
2014-04-24 17:07:50 -04:00
{
$where = $this->_where($key, $val);
// Create key/value placeholders
foreach($where as $f => $val)
{
// Split each key by spaces, in case there
// is an operator such as >, <, !=, etc.
2016-10-13 21:55:23 -04:00
$fArray = explode(' ', trim($f));
2014-04-24 17:07:50 -04:00
2016-10-13 21:55:23 -04:00
$item = $this->db->quoteIdent($fArray[0]);
2014-04-24 17:07:50 -04:00
// Simple key value, or an operator
2016-10-13 21:55:23 -04:00
$item .= (count($fArray) === 1) ? '=?' : " {$fArray[1]} ?";
2014-04-24 17:07:50 -04:00
// Put in the having map
2016-10-13 21:55:23 -04:00
$this->havingMap[] = [
'conjunction' => ( ! empty($this->havingMap)) ? " {$conj} " : ' HAVING ',
2014-04-24 17:07:50 -04:00
'string' => $item
2016-09-07 13:10:03 -04:00
];
2014-04-24 17:07:50 -04:00
}
return $this;
}
/**
2016-09-07 17:39:19 -04:00
* Do all the redundant stuff for where/having type methods
2014-04-24 17:07:50 -04:00
*
* @param mixed $key
* @param mixed $val
* @return array
*/
2016-10-13 21:55:23 -04:00
protected function _where($key, $val=[]): array
2014-04-24 17:07:50 -04:00
{
2016-09-07 13:10:03 -04:00
$where = [];
2016-10-13 21:55:23 -04:00
$this->_mixedSet($where, $key, $val, self::BOTH);
$this->_mixedSet($this->whereValues, $key, $val, self::VALUE);
2014-04-24 17:07:50 -04:00
return $where;
}
/**
* Simplify generating where string
*
* @param mixed $key
* @param mixed $val
2014-11-07 12:21:49 -05:00
* @param string $defaultConj
2016-10-12 22:12:25 -04:00
* @return QueryBuilderInterface
2014-04-24 17:07:50 -04:00
*/
2016-10-13 21:55:23 -04:00
protected function _whereString($key, $val=[], string $defaultConj='AND'): QueryBuilderInterface
2014-04-24 17:07:50 -04:00
{
// Create key/value placeholders
foreach($this->_where($key, $val) as $f => $val)
2014-04-24 17:07:50 -04:00
{
// Split each key by spaces, in case there
// is an operator such as >, <, !=, etc.
2016-10-13 21:55:23 -04:00
$fArray = explode(' ', trim($f));
2014-04-24 17:07:50 -04:00
2016-10-13 21:55:23 -04:00
$item = $this->db->quoteIdent($fArray[0]);
2014-04-24 17:07:50 -04:00
// Simple key value, or an operator
2016-10-13 21:55:23 -04:00
$item .= (count($fArray) === 1) ? '=?' : " {$fArray[1]} ?";
$lastItem = end($this->queryMap);
2014-04-24 17:07:50 -04:00
// Determine the correct conjunction
2016-10-13 21:55:23 -04:00
$conjunctionList = array_column($this->queryMap, 'conjunction');
if (empty($this->queryMap) || ( ! regex_in_array($conjunctionList, "/^ ?\n?WHERE/i")))
2014-04-24 17:07:50 -04:00
{
$conj = "\nWHERE ";
}
2016-10-13 21:55:23 -04:00
elseif ($lastItem['type'] === 'group_start')
2014-04-24 17:07:50 -04:00
{
$conj = '';
}
else
{
$conj = " {$defaultConj} ";
2014-04-24 17:07:50 -04:00
}
2016-10-13 21:55:23 -04:00
$this->_appendMap($conj, $item, 'where');
2014-04-24 17:07:50 -04:00
}
return $this;
}
/**
* Simplify where_in methods
*
* @param mixed $key
* @param mixed $val
* @param string $in - The (not) in fragment
* @param string $conj - The where in conjunction
2016-10-12 22:12:25 -04:00
* @return QueryBuilderInterface
2014-04-24 17:07:50 -04:00
*/
2016-10-13 21:55:23 -04:00
protected function _whereIn($key, $val=[], string $in='IN', string $conj='AND'): QueryBuilderInterface
2014-04-24 17:07:50 -04:00
{
2016-10-13 21:55:23 -04:00
$key = $this->db->quoteIdent($key);
2014-04-24 17:07:50 -04:00
$params = array_fill(0, count($val), '?');
foreach($val as $v)
{
2016-10-13 21:55:23 -04:00
$this->whereValues[] = $v;
2014-04-24 17:07:50 -04:00
}
2016-10-13 21:55:23 -04:00
$conjunction = ( ! empty($this->queryMap)) ? " {$conj} " : ' WHERE ';
2014-04-24 17:07:50 -04:00
$str = $key . " {$in} (".implode(',', $params).') ';
2016-10-13 21:55:23 -04:00
$this->_appendMap($conjunction, $str, 'where_in');
2014-04-24 17:07:50 -04:00
return $this;
}
/**
* Executes the compiled query
*
* @param string $type
* @param string $table
* @param string $sql
* @param array|null $vals
2016-09-07 17:39:19 -04:00
* @param boolean $reset
2016-10-13 21:55:23 -04:00
* @return PDOStatement
2014-04-24 17:07:50 -04:00
*/
2016-10-13 21:55:23 -04:00
protected function _run(string $type, string $table, $sql=NULL, $vals=NULL, bool $reset=TRUE): PDOStatement
2014-04-24 17:07:50 -04:00
{
if (is_null($sql))
{
$sql = $this->_compile($type, $table);
}
if (is_null($vals))
{
2016-10-13 21:55:23 -04:00
$vals = array_merge($this->values, (array) $this->whereValues);
2014-04-24 17:07:50 -04:00
}
2016-10-13 21:55:23 -04:00
$startTime = microtime(TRUE);
2014-04-24 17:07:50 -04:00
$res = (empty($vals))
? $this->db->query($sql)
2016-10-13 21:55:23 -04:00
: $this->db->prepareExecute($sql, $vals);
2014-04-24 17:07:50 -04:00
2016-10-13 21:55:23 -04:00
$endTime = microtime(TRUE);
$totalTime = number_format($endTime - $startTime, 5);
2014-04-24 17:07:50 -04:00
// Add this query to the list of executed queries
2016-10-13 21:55:23 -04:00
$this->_appendQuery($vals, $sql, (int) $totalTime);
2014-04-24 17:07:50 -04:00
// Reset class state for next query
2016-09-07 17:39:19 -04:00
if ($reset)
{
2016-10-13 21:55:23 -04:00
$this->resetQuery();
2016-09-07 17:39:19 -04:00
}
2014-04-24 17:07:50 -04:00
return $res;
}
/**
* Add an additional set of mapping pairs to a internal map
*
* @param string $conjunction
* @param string $string
* @param string $type
* @return void
*/
2016-10-13 21:55:23 -04:00
protected function _appendMap(string $conjunction = '', string $string = '', string $type = '')
2014-04-24 17:07:50 -04:00
{
2016-10-13 21:55:23 -04:00
array_push($this->queryMap, [
2014-04-24 17:07:50 -04:00
'type' => $type,
'conjunction' => $conjunction,
'string' => $string
2016-09-07 13:10:03 -04:00
]);
2014-04-24 17:07:50 -04:00
}
/**
* Convert the prepared statement into readable sql
*
* @param array $vals
* @param string $sql
2016-10-13 21:55:23 -04:00
* @param int $totalTime
2014-04-24 17:07:50 -04:00
* @return void
*/
2016-10-13 21:55:23 -04:00
protected function _appendQuery($vals, string $sql, int $totalTime)
2014-04-24 17:07:50 -04:00
{
2016-09-07 13:10:03 -04:00
$evals = (is_array($vals)) ? $vals : [];
2014-04-24 17:07:50 -04:00
$esql = str_replace('?', "%s", $sql);
// Quote string values
foreach($evals as &$v)
{
$v = ( ! is_numeric($v)) ? htmlentities($this->db->quote($v), ENT_NOQUOTES, 'utf-8') : $v;
2014-04-24 17:07:50 -04:00
}
// Add the query onto the array of values to pass
// as arguments to sprintf
array_unshift($evals, $esql);
// Add the interpreted query to the list of executed queries
2016-09-07 13:10:03 -04:00
$this->queries[] = [
2016-10-13 21:55:23 -04:00
'time' => $totalTime,
2014-04-24 17:07:50 -04:00
'sql' => call_user_func_array('sprintf', $evals),
2016-09-07 13:10:03 -04:00
];
2014-04-24 17:07:50 -04:00
2016-10-13 21:55:23 -04:00
$this->queries['total_time'] += $totalTime;
2014-04-24 17:07:50 -04:00
// Set the last query to get rowcounts properly
2016-10-13 21:55:23 -04:00
$this->db->setLastQuery($sql);
2014-04-24 17:07:50 -04:00
}
/**
* Sub-method for generating sql strings
*
* @param string $type
* @param string $table
* @return string
*/
2016-10-13 21:55:23 -04:00
protected function _compileType(string $type='', string $table=''): string
2014-04-24 17:07:50 -04:00
{
2016-09-07 17:39:19 -04:00
switch($type)
2014-04-24 17:07:50 -04:00
{
2016-09-07 17:39:19 -04:00
case "insert":
2016-10-13 21:55:23 -04:00
$paramCount = count($this->setArrayKeys);
$params = array_fill(0, $paramCount, '?');
2016-09-07 17:39:19 -04:00
$sql = "INSERT INTO {$table} ("
2016-10-13 21:55:23 -04:00
. implode(',', $this->setArrayKeys)
2016-09-07 17:39:19 -04:00
. ")\nVALUES (".implode(',', $params).')';
break;
case "update":
2016-10-13 21:55:23 -04:00
$sql = "UPDATE {$table}\nSET {$this->setString}";
2016-09-07 17:39:19 -04:00
break;
case "replace":
// @TODO implement
$sql = "";
break;
case "delete":
$sql = "DELETE FROM {$table}";
break;
// Get queries
default:
2016-10-13 21:55:23 -04:00
$sql = "SELECT * \nFROM {$this->fromString}";
2016-09-07 17:39:19 -04:00
// Set the select string
2016-10-13 21:55:23 -04:00
if ( ! empty($this->selectString))
2016-09-07 17:39:19 -04:00
{
// Replace the star with the selected fields
2016-10-13 21:55:23 -04:00
$sql = str_replace('*', $this->selectString, $sql);
2016-09-07 17:39:19 -04:00
}
break;
2014-04-24 17:07:50 -04:00
}
return $sql;
}
/**
* String together the sql statements for sending to the db
*
* @param string $type
* @param string $table
2015-07-30 13:13:12 -04:00
* @return string
2014-04-24 17:07:50 -04:00
*/
2016-10-13 21:55:23 -04:00
protected function _compile(string $type='', string $table=''): string
2014-04-24 17:07:50 -04:00
{
// Get the base clause for the query
2016-10-13 21:55:23 -04:00
$sql = $this->_compileType($type, $this->db->quoteTable($table));
2014-04-24 17:07:50 -04:00
2016-09-07 13:10:03 -04:00
$clauses = [
2016-10-13 21:55:23 -04:00
'queryMap',
'groupString',
'orderString',
'havingMap',
2016-09-07 13:10:03 -04:00
];
2014-04-24 17:07:50 -04:00
// Set each type of subclause
foreach($clauses as $clause)
{
$param = $this->$clause;
if (is_array($param))
{
foreach($param as $q)
{
$sql .= $q['conjunction'] . $q['string'];
}
}
else
{
$sql .= $param;
}
}
// Set the limit via the class variables
if (is_numeric($this->limit))
{
$sql = $this->sql->limit($sql, $this->limit, $this->offset);
}
// See if the query plan, rather than the
// query data should be returned
if ($this->explain === TRUE)
{
$sql = $this->sql->explain($sql);
}
return $sql;
}
2016-10-12 22:12:25 -04:00
}