Source of file QueryBuilder.php
Size: 29,234 Bytes - Last Modified: 2018-01-24T20:17:51+00:00
src/QueryBuilder.php
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
Covered by 2 test(s):
78
Covered by 2 test(s):
798081
Covered by 2 test(s):
828384858687888990919293949596979899100101102103
Covered by 45 test(s):
104105
Covered by 42 test(s):
106107108
Covered by 3 test(s):
109110111112113114115116117118119120121122123124
Covered by 60 test(s):
125
Covered by 60 test(s):
126127128
Covered by 60 test(s):
129130
Covered by 60 test(s):
131132
Covered by 54 test(s):
133
Covered by 60 test(s):
134135136137138
Covered by 60 test(s):
139140
Covered by 60 test(s):
141142143
Covered by 60 test(s):
144145
Covered by 60 test(s):
146147
Covered by 54 test(s):
148149150151
Covered by 60 test(s):
152153
Covered by 60 test(s):
154155156157158159160161162163164165166
Covered by 3 test(s):
167
Covered by 3 test(s):
168169170171172173174175176177178179180
Covered by 3 test(s):
181
Covered by 3 test(s):
182183184185186187188189190191192193194
Covered by 3 test(s):
195
Covered by 3 test(s):
196197198199200201202203204205206207208
Covered by 6 test(s):
209
Covered by 6 test(s):
210211212213214215216217218219220
Covered by 3 test(s):
221
Covered by 3 test(s):
222223224225226227228229230231
Covered by 3 test(s):
232
Covered by 3 test(s):
233234235236237238239240241242243244
Covered by 147 test(s):
245
Covered by 147 test(s):
246247248
Covered by 147 test(s):
249
Covered by 147 test(s):
250251252
Covered by 147 test(s):
253254
Covered by 147 test(s):
255256257258259260261262263264265266267268269270271
Covered by 18 test(s):
272273274275276277278279280281282283284
Covered by 3 test(s):
285286287288289290291292293294295296297
Covered by 3 test(s):
298299300301302303304305306307308309310
Covered by 3 test(s):
311312313314315316317318319320321322323324325326
Covered by 6 test(s):
327328329330331332333334335336337338
Covered by 3 test(s):
339340341342343344345346347348349350351352353354355356357
Covered by 81 test(s):
358359360361362363364365366367368369
Covered by 6 test(s):
370371372373374375376377378379380381
Covered by 3 test(s):
382383384385386387388389390391392393
Covered by 3 test(s):
394395396397398399400401402403404405
Covered by 3 test(s):
406407408409410411412413414415416417
Covered by 3 test(s):
418419420421422423424425426427428429430431432433
Covered by 24 test(s):
434435
Covered by 6 test(s):
436437438439
Covered by 18 test(s):
440441442
Covered by 24 test(s):
443
Covered by 24 test(s):
444445
Covered by 24 test(s):
446
Covered by 24 test(s):
447448449450
Covered by 24 test(s):
451
Covered by 24 test(s):
452453454455
Covered by 24 test(s):
456
Covered by 24 test(s):
457458
Covered by 24 test(s):
459460
Covered by 24 test(s):
461462463464465466467468469470471472473474
Covered by 12 test(s):
475
Covered by 12 test(s):
476
Covered by 12 test(s):
477
Covered by 12 test(s):
478479480
Covered by 12 test(s):
481
Covered by 12 test(s):
482483
Covered by 12 test(s):
484485
Covered by 12 test(s):
486487488489490491492493494495496
Covered by 12 test(s):
497498
Covered by 3 test(s):
499
Covered by 3 test(s):
500
Covered by 3 test(s):
501502503504505
Covered by 12 test(s):
506507508
Covered by 12 test(s):
509510
Covered by 12 test(s):
511512513514515516517518519520521522523524
Covered by 12 test(s):
525526
Covered by 3 test(s):
527
Covered by 3 test(s):
528529530531
Covered by 12 test(s):
532
Covered by 12 test(s):
533534
Covered by 12 test(s):
535536537
Covered by 12 test(s):
538539
Covered by 12 test(s):
540541542543
Covered by 12 test(s):
544
Covered by 9 test(s):
545
Covered by 12 test(s):
546547
Covered by 12 test(s):
548549
Covered by 12 test(s):
550551552553554555556557558559560561
Covered by 57 test(s):
562
Covered by 57 test(s):
563564
Covered by 57 test(s):
565566567568569570571572573574575576577578
Covered by 15 test(s):
579580
Covered by 15 test(s):
581582
Covered by 15 test(s):
583584585586587588589590591592593
Covered by 6 test(s):
594595
Covered by 6 test(s):
596597
Covered by 6 test(s):
598599600601602603604605606607608
Covered by 3 test(s):
609610
Covered by 3 test(s):
611612613614615616617618619620621
Covered by 6 test(s):
622623
Covered by 6 test(s):
624625626627628629630631632633
Covered by 18 test(s):
634635
Covered by 18 test(s):
636637638639640641642643644645646647648649650651652653654
Covered by 141 test(s):
655656
Covered by 48 test(s):
657658659660
Covered by 141 test(s):
661662
Covered by 21 test(s):
663664665
Covered by 141 test(s):
666667668669670671672673674675676677678679680
Covered by 3 test(s):
681682683
Covered by 3 test(s):
684685686687688689690691692693694
Covered by 4 test(s):
695
Covered by 4 test(s):
696
Covered by 4 test(s):
697698699700701702703704705706707708709710
Covered by 6 test(s):
711712
Covered by 3 test(s):
713714715
Covered by 6 test(s):
716
Covered by 6 test(s):
717718
Covered by 6 test(s):
719720721722723724725726727728729730
Covered by 9 test(s):
731732
Covered by 3 test(s):
733734735
Covered by 9 test(s):
736737738739740741742743744745746747748
Covered by 3 test(s):
749750
Covered by 3 test(s):
751
Covered by 3 test(s):
752
Covered by 3 test(s):
753754755756757758759760761762763764
Covered by 9 test(s):
765766
Covered by 3 test(s):
767768769
Covered by 9 test(s):
770771772773774775776777778779780781782783784
Covered by 3 test(s):
785786
Covered by 3 test(s):
787788
Covered by 3 test(s):
789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
Covered by 6 test(s):
819820
Covered by 6 test(s):
821822823
Covered by 6 test(s):
824825826827828829830831832833834835836837838839840
Covered by 3 test(s):
841842
Covered by 3 test(s):
843844845
Covered by 3 test(s):
846847848849850851852853854855856857
Covered by 3 test(s):
858859860861862863864865866867868869
Covered by 3 test(s):
870871872873874875876877878879880881
Covered by 3 test(s):
882883884885886887888889890891892893894895
Covered by 183 test(s):
896
Covered by 183 test(s):
897898899900901902903904905906907908909
Covered by 15 test(s):
910911
Covered by 15 test(s):
912913914915916
Covered by 15 test(s):
917
Covered by 15 test(s):
918919920921922923924925926927928929930
Covered by 12 test(s):
931932933
Covered by 12 test(s):
934935
Covered by 12 test(s):
936937938
Covered by 12 test(s):
939940941942943944945946947948949950951952953
Covered by 18 test(s):
954955956
Covered by 18 test(s):
957958
Covered by 18 test(s):
959960
Covered by 9 test(s):
961962
Covered by 15 test(s):
963964
Covered by 3 test(s):
965966967968
Covered by 12 test(s):
969970971
Covered by 18 test(s):
972
Covered by 18 test(s):
973974975
Covered by 18 test(s):
976977
Covered by 18 test(s):
978979980981982983984985986987988989990
Covered by 6 test(s):
991992993
Covered by 6 test(s):
994995996997
Covered by 6 test(s):
998999
Covered by 6 test(s):
100010011002
Covered by 6 test(s):
100310041005
Covered by 6 test(s):
1006
Covered by 6 test(s):
1007
Covered by 6 test(s):
1008
Covered by 6 test(s):
1009
Covered by 6 test(s):
1010101110121013
Covered by 6 test(s):
101410151016101710181019102010211022102310241025
Covered by 87 test(s):
1026
Covered by 87 test(s):
10271028
Covered by 87 test(s):
10291030
Covered by 75 test(s):
1031103210331034
Covered by 18 test(s):
103510361037
Covered by 87 test(s):
10381039
Covered by 87 test(s):
1040
Covered by 87 test(s):
104110421043
Covered by 87 test(s):
10441045104610471048104910501051105210531054105510561057
Covered by 81 test(s):
10581059
Covered by 81 test(s):
1060106110621063
Covered by 81 test(s):
10641065
Covered by 81 test(s):
106610671068
Covered by 81 test(s):
1069
Covered by 81 test(s):
107010711072
Covered by 81 test(s):
1073
Covered by 81 test(s):
10741075
Covered by 63 test(s):
10761077
Covered by 45 test(s):
10781079
Covered by 18 test(s):
1080108110821083
Covered by 42 test(s):
108410851086
Covered by 81 test(s):
108710881089
Covered by 81 test(s):
10901091109210931094109510961097109810991100110111021103
Covered by 12 test(s):
1104
Covered by 12 test(s):
1105
Covered by 12 test(s):
11061107
Covered by 12 test(s):
1108
Covered by 12 test(s):
11091110
Covered by 12 test(s):
11111112
Covered by 12 test(s):
111311141115111611171118111911201121112211231124112511261127
Covered by 174 test(s):
11281129
Covered by 171 test(s):
113011311132
Covered by 174 test(s):
11331134
Covered by 171 test(s):
113511361137
Covered by 174 test(s):
11381139
Covered by 174 test(s):
1140
Covered by 57 test(s):
1141
Covered by 174 test(s):
11421143
Covered by 174 test(s):
1144
Covered by 174 test(s):
114511461147
Covered by 174 test(s):
114811491150
Covered by 174 test(s):
11511152
Covered by 174 test(s):
115311541155
Covered by 174 test(s):
1156115711581159116011611162116311641165116611671168
Covered by 174 test(s):
1169
Covered by 174 test(s):
117011711172
Covered by 174 test(s):
11731174
Covered by 117 test(s):
1175
Covered by 48 test(s):
1176
Covered by 117 test(s):
11771178117911801181
Covered by 174 test(s):
118211831184
Covered by 174 test(s):
1185
Covered by 174 test(s):
1186
Covered by 174 test(s):
118711881189
Covered by 174 test(s):
119011911192
Covered by 174 test(s):
119311941195119611971198119912001201120212031204
Covered by 180 test(s):
1205
Covered by 180 test(s):
120612071208
Covered by 12 test(s):
1209
Covered by 12 test(s):
1210
Covered by 12 test(s):
1211
Covered by 12 test(s):
1212
Covered by 12 test(s):
1213
Covered by 12 test(s):
121412151216
Covered by 12 test(s):
1217
Covered by 12 test(s):
1218
Covered by 12 test(s):
12191220122112221223122412251226
Covered by 9 test(s):
1227
Covered by 9 test(s):
1228122912301231
Covered by 147 test(s):
1232
Covered by 147 test(s):
12331234
Covered by 147 test(s):
123512361237
Covered by 147 test(s):
123812391240
Covered by 75 test(s):
12411242
Covered by 147 test(s):
124312441245
Covered by 180 test(s):
1246124712481249125012511252125312541255125612571258
Covered by 180 test(s):
125912601261
Covered by 180 test(s):
1262126312641265126612671268
Covered by 180 test(s):
12691270
Covered by 180 test(s):
1271
Covered by 180 test(s):
1272
Covered by 180 test(s):
12731274
Covered by 180 test(s):
12751276
Covered by 180 test(s):
12771278127912801281
Covered by 180 test(s):
12821283128412851286
Covered by 180 test(s):
1287
Covered by 180 test(s):
12881289
Covered by 57 test(s):
12901291129212931294
Covered by 180 test(s):
12951296
Covered by 3 test(s):
129712981299
Covered by 180 test(s):
130013011302
| <?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; use BadMethodCallException; use PDOStatement; use Query\Drivers\DriverInterface; /** * Convenience class for creating sql queries */ class QueryBuilder implements QueryBuilderInterface { /** * Convenience property for connection management * @var string */ public $connName = ''; /** * List of queries executed * @var array */ public $queries = [ 'total_time' => 0 ]; /** * Whether to do only an explain on the query * @var boolean */ protected $explain = FALSE; /** * The current database driver * @var DriverInterface */ public $driver; /** * Query parser class instance * @var QueryParser */ protected $parser; /** * Query Builder state * @var State */ protected $state; // -------------------------------------------------------------------------- // ! Methods // -------------------------------------------------------------------------- /** * Constructor * * @param DriverInterface $driver * @param QueryParser $parser */ public function __construct(DriverInterface $driver, QueryParser $parser) { // Inject driver and parser $this->driver = $driver; $this->parser = $parser; // Create new State object $this->state = new State(); } /** * Destructor * @codeCoverageIgnore */ public function __destruct() { $this->driver = NULL; } /** * Calls a function further down the inheritance chain * * @param string $name * @param array $params * @return mixed * @throws BadMethodCallException */ public function __call(string $name, array $params) { if (method_exists($this->driver, $name)) { return \call_user_func_array([$this->driver, $name], $params); } throw new BadMethodCallException('Method does not exist'); } // -------------------------------------------------------------------------- // ! Select Queries // -------------------------------------------------------------------------- /** * Specifies rows to select in a query * * @param string $fields * @return QueryBuilderInterface */ public function select(string $fields): QueryBuilderInterface { // Split fields by comma $fieldsArray = explode(',', $fields); $fieldsArray = array_map('mb_trim', $fieldsArray); // Split on 'As' foreach ($fieldsArray as $key => $field) { if (stripos($field, 'as') !== FALSE) { $fieldsArray[$key] = preg_split('` as `i', $field); $fieldsArray[$key] = array_map('mb_trim', $fieldsArray[$key]); } } // Quote the identifiers $safeArray = $this->driver->quoteIdent($fieldsArray); unset($fieldsArray); // Join the strings back together for($i = 0, $c = count($safeArray); $i < $c; $i++) { if (\is_array($safeArray[$i])) { $safeArray[$i] = implode(' AS ', $safeArray[$i]); } } $this->state->appendSelectString(implode(', ', $safeArray)); return $this; } /** * Selects the maximum value of a field from a query * * @param string $field * @param string|bool $as * @return QueryBuilderInterface */ public function selectMax(string $field, $as=FALSE): QueryBuilderInterface { // Create the select string $this->state->appendSelectString(' MAX'.$this->_select($field, $as)); return $this; } /** * Selects the minimum value of a field from a query * * @param string $field * @param string|bool $as * @return QueryBuilderInterface */ public function selectMin(string $field, $as=FALSE): QueryBuilderInterface { // Create the select string $this->state->appendSelectString(' MIN'.$this->_select($field, $as)); return $this; } /** * Selects the average value of a field from a query * * @param string $field * @param string|bool $as * @return QueryBuilderInterface */ public function selectAvg(string $field, $as=FALSE): QueryBuilderInterface { // Create the select string $this->state->appendSelectString(' AVG'.$this->_select($field, $as)); return $this; } /** * Selects the sum of a field from a query * * @param string $field * @param string|bool $as * @return QueryBuilderInterface */ public function selectSum(string $field, $as=FALSE): QueryBuilderInterface { // Create the select string $this->state->appendSelectString(' SUM'.$this->_select($field, $as)); return $this; } /** * Adds the 'distinct' keyword to a query * * @return QueryBuilderInterface */ public function distinct(): QueryBuilderInterface { // Prepend the keyword to the select string $this->state->setSelectString(' DISTINCT' . $this->state->getSelectString()); return $this; } /** * Tell the database to give you the query plan instead of result set * * @return QueryBuilderInterface */ public function explain(): QueryBuilderInterface { $this->explain = TRUE; return $this; } /** * Specify the database table to select from * * @param string $tblname * @return QueryBuilderInterface */ public function from(string $tblname): QueryBuilderInterface { // Split identifiers on spaces $identArray = explode(' ', \mb_trim($tblname)); $identArray = array_map('\\mb_trim', $identArray); // Quote the identifiers $identArray[0] = $this->driver->quoteTable($identArray[0]); $identArray = $this->driver->quoteIdent($identArray); // Paste it back together $this->state->setFromString(implode(' ', $identArray)); return $this; } // -------------------------------------------------------------------------- // ! 'Like' methods // -------------------------------------------------------------------------- /** * Creates a Like clause in the sql statement * * @param string $field * @param mixed $val * @param string $pos * @return QueryBuilderInterface */ public function like(string $field, $val, string $pos='both'): QueryBuilderInterface { return $this->_like($field, $val, $pos); } /** * Generates an OR Like clause * * @param string $field * @param mixed $val * @param string $pos * @return QueryBuilderInterface */ public function orLike(string $field, $val, string $pos='both'): QueryBuilderInterface { return $this->_like($field, $val, $pos, 'LIKE', 'OR'); } /** * Generates a NOT LIKE clause * * @param string $field * @param mixed $val * @param string $pos * @return QueryBuilderInterface */ public function notLike(string $field, $val, string $pos='both'): QueryBuilderInterface { return $this->_like($field, $val, $pos, 'NOT LIKE'); } /** * Generates a OR NOT LIKE clause * * @param string $field * @param mixed $val * @param string $pos * @return QueryBuilderInterface */ public function orNotLike(string $field, $val, string $pos='both'): QueryBuilderInterface { return $this->_like($field, $val, $pos, 'NOT LIKE', 'OR'); } // -------------------------------------------------------------------------- // ! Having methods // -------------------------------------------------------------------------- /** * Generates a 'Having' clause * * @param mixed $key * @param mixed $val * @return QueryBuilderInterface */ public function having($key, $val=[]): QueryBuilderInterface { return $this->_having($key, $val); } /** * Generates a 'Having' clause prefixed with 'OR' * * @param mixed $key * @param mixed $val * @return QueryBuilderInterface */ public function orHaving($key, $val=[]): QueryBuilderInterface { return $this->_having($key, $val, 'OR'); } // -------------------------------------------------------------------------- // ! 'Where' methods // -------------------------------------------------------------------------- /** * Specify condition(s) in the where clause of a query * Note: this function works with key / value, or a * passed array with key / value pairs * * @param mixed $key * @param mixed $val * @param mixed $escape * @return QueryBuilderInterface */ public function where($key, $val=[], $escape=NULL): QueryBuilderInterface { return $this->_whereString($key, $val); } /** * Where clause prefixed with "OR" * * @param string $key * @param mixed $val * @return QueryBuilderInterface */ public function orWhere($key, $val=[]): QueryBuilderInterface { return $this->_whereString($key, $val, 'OR'); } /** * Where clause with 'IN' statement * * @param mixed $field * @param mixed $val * @return QueryBuilderInterface */ public function whereIn($field, $val=[]): QueryBuilderInterface { return $this->_whereIn($field, $val); } /** * Where in statement prefixed with "or" * * @param string $field * @param mixed $val * @return QueryBuilderInterface */ public function orWhereIn($field, $val=[]): QueryBuilderInterface { return $this->_whereIn($field, $val, 'IN', 'OR'); } /** * WHERE NOT IN (FOO) clause * * @param string $field * @param mixed $val * @return QueryBuilderInterface */ public function whereNotIn($field, $val=[]): QueryBuilderInterface { return $this->_whereIn($field, $val, 'NOT IN'); } /** * OR WHERE NOT IN (FOO) clause * * @param string $field * @param mixed $val * @return QueryBuilderInterface */ public function orWhereNotIn($field, $val=[]): QueryBuilderInterface { return $this->_whereIn($field, $val, 'NOT IN', 'OR'); } // -------------------------------------------------------------------------- // ! Other Query Modifier methods // -------------------------------------------------------------------------- /** * Sets values for inserts / updates / deletes * * @param mixed $key * @param mixed $val * @return QueryBuilderInterface */ public function set($key, $val = NULL): QueryBuilderInterface { if (is_scalar($key)) { $pairs = [$key => $val]; } else { $pairs = $key; } $keys = array_keys($pairs); $values = array_values($pairs); $this->state->appendSetArrayKeys($keys); $this->state->appendValues($values); // Use the keys of the array to make the insert/update string // Escape the field names $this->state->setSetArrayKeys( array_map([$this->driver, '_quote'], $this->state->getSetArrayKeys()) ); // Generate the "set" string $setString = implode('=?,', $this->state->getSetArrayKeys()); $setString .= '=?'; $this->state->setSetString($setString); return $this; } /** * Creates a join phrase in a compiled query * * @param string $table * @param string $condition * @param string $type * @return QueryBuilderInterface */ public function join(string $table, string $condition, string $type=''): QueryBuilderInterface { // Prefix and quote table name $table = explode(' ', mb_trim($table)); $table[0] = $this->driver->quoteTable($table[0]); $table = $this->driver->quoteIdent($table); $table = implode(' ', $table); // Parse out the join condition $parsedCondition = $this->parser->compileJoin($condition); $condition = $table . ' ON ' . $parsedCondition; $this->state->appendMap("\n" . strtoupper($type) . ' JOIN ', $condition, 'join'); return $this; } /** * Group the results by the selected field(s) * * @param mixed $field * @return QueryBuilderInterface */ public function groupBy($field): QueryBuilderInterface { if ( ! is_scalar($field)) { $newGroupArray = array_map([$this->driver, 'quoteIdent'], $field); $this->state->setGroupArray( array_merge($this->state->getGroupArray(), $newGroupArray) ); } else { $this->state->appendGroupArray($this->driver->quoteIdent($field)); } $this->state->setGroupString(' GROUP BY ' . implode(',', $this->state->getGroupArray())); return $this; } /** * Order the results by the selected field(s) * * @param string $field * @param string $type * @return QueryBuilderInterface */ public function orderBy(string $field, string $type=''): QueryBuilderInterface { // When ordering by random, do an ascending order if the driver // doesn't support random ordering if (stripos($type, 'rand') !== FALSE) { $rand = $this->driver->getSql()->random(); $type = $rand ?? 'ASC'; } // Set fields for later manipulation $field = $this->driver->quoteIdent($field); $this->state->setOrderArray($field, $type); $orderClauses = []; // Flatten key/val pairs into an array of space-separated pairs foreach($this->state->getOrderArray() as $k => $v) { $orderClauses[] = $k . ' ' . strtoupper($v); } // Set the final string $orderString = ! isset($rand) ? "\nORDER BY ".implode(', ', $orderClauses) : "\nORDER BY".$rand; $this->state->setOrderString($orderString); return $this; } /** * Set a limit on the current sql statement * * @param int $limit * @param int|bool $offset * @return QueryBuilderInterface */ public function limit(int $limit, $offset=FALSE): QueryBuilderInterface { $this->state->setLimit($limit); $this->state->setOffset($offset); return $this; } // -------------------------------------------------------------------------- // ! Query Grouping Methods // -------------------------------------------------------------------------- /** * Adds a paren to the current query for query grouping * * @return QueryBuilderInterface */ public function groupStart(): QueryBuilderInterface { $conj = empty($this->state->getQueryMap()) ? ' WHERE ' : ' '; $this->state->appendMap($conj, '(', 'group_start'); return $this; } /** * Adds a paren to the current query for query grouping, * prefixed with 'NOT' * * @return QueryBuilderInterface */ public function notGroupStart(): QueryBuilderInterface { $conj = empty($this->state->getQueryMap()) ? ' WHERE ' : ' AND '; $this->state->appendMap($conj, ' NOT (', 'group_start'); return $this; } /** * Adds a paren to the current query for query grouping, * prefixed with 'OR' * * @return QueryBuilderInterface */ public function orGroupStart(): QueryBuilderInterface { $this->state->appendMap('', ' OR (', 'group_start'); return $this; } /** * Adds a paren to the current query for query grouping, * prefixed with 'OR NOT' * * @return QueryBuilderInterface */ public function orNotGroupStart(): QueryBuilderInterface { $this->state->appendMap('', ' OR NOT (', 'group_start'); return $this; } /** * Ends a query group * * @return QueryBuilderInterface */ public function groupEnd(): QueryBuilderInterface { $this->state->appendMap('', ')', 'group_end'); return $this; } // -------------------------------------------------------------------------- // ! Query execution methods // -------------------------------------------------------------------------- /** * Select and retrieve all records from the current table, and/or * execute current compiled query * * @param string $table * @param int|bool $limit * @param int|bool $offset * @return PDOStatement */ public function get(string $table='', $limit=FALSE, $offset=FALSE): ?PDOStatement { // Set the table if ( ! empty($table)) { $this->from($table); } // Set the limit, if it exists if (\is_int($limit)) { $this->limit($limit, $offset); } return $this->_run('get', $table); } /** * Convenience method for get() with a where clause * * @param string $table * @param mixed $where * @param int|bool $limit * @param int|bool $offset * @return PDOStatement */ public function getWhere(string $table, $where=[], $limit=FALSE, $offset=FALSE): ?PDOStatement { // Create the where clause $this->where($where); // Return the result return $this->get($table, $limit, $offset); } /** * Retrieve the number of rows in the selected table * * @param string $table * @return int */ public function countAll(string $table): int { $sql = 'SELECT * FROM '.$this->driver->quoteTable($table); $res = $this->driver->query($sql); return (int) count($res->fetchAll()); } /** * Retrieve the number of results for the generated query - used * in place of the get() method * * @param string $table * @param boolean $reset * @return int */ public function countAllResults(string $table='', bool $reset = TRUE): int { // Set the table if ( ! empty($table)) { $this->from($table); } $result = $this->_run('get', $table, NULL, NULL, $reset); $rows = $result->fetchAll(); return (int) count($rows); } /** * Creates an insert clause, and executes it * * @param string $table * @param mixed $data * @return PDOStatement */ public function insert(string $table, $data=[]): ?PDOStatement { if ( ! empty($data)) { $this->set($data); } return $this->_run('insert', $table); } /** * Creates and executes a batch insertion query * * @param string $table * @param array $data * @return PDOStatement */ public function insertBatch(string $table, $data=[]): ?PDOStatement { // Get the generated values and sql string [$sql, $data] = $this->driver->insertBatch($table, $data); return $sql !== NULL ? $this->_run('', $table, $sql, $data) : NULL; } /** * Creates an update clause, and executes it * * @param string $table * @param mixed $data * @return PDOStatement */ public function update(string $table, $data=[]): PDOStatement { if ( ! empty($data)) { $this->set($data); } return $this->_run('update', $table); } /** * Creates a batch update, and executes it. * Returns the number of affected rows * * @param string $table * @param array|object $data * @param string $where * @return PDOStatement|null */ public function updateBatch(string $table, $data, $where): ?PDOStatement { // Get the generated values and sql string list($sql, $data) = $this->driver->updateBatch($table, $data, $where); return $sql !== NULL ? $this->_run('', $table, $sql, $data) : NULL; } /** * Insertion with automatic overwrite, rather than attempted duplication * * @param string $table * @param array $data * @return \PDOStatement|null */ public function replace(string $table, $data=[]): ?PDOStatement { if ( ! empty($data)) { $this->set($data); } return $this->_run('replace', $table); } /** * Deletes data from a table * * @param string $table * @param mixed $where * @return PDOStatement */ public function delete(string $table, $where=''): ?PDOStatement { // Set the where clause if ( ! empty($where)) { $this->where($where); } return $this->_run('delete', $table); } // -------------------------------------------------------------------------- // ! SQL Returning Methods // -------------------------------------------------------------------------- /** * Returns the generated 'select' sql query * * @param string $table * @param bool $reset * @return string */ public function getCompiledSelect(string $table='', bool $reset=TRUE): string { // Set the table if ( ! empty($table)) { $this->from($table); } return $this->_getCompile('select', $table, $reset); } /** * Returns the generated 'insert' sql query * * @param string $table * @param bool $reset * @return string */ public function getCompiledInsert(string $table, bool $reset=TRUE): string { return $this->_getCompile('insert', $table, $reset); } /** * Returns the generated 'update' sql query * * @param string $table * @param bool $reset * @return string */ public function getCompiledUpdate(string $table='', bool $reset=TRUE): string { return $this->_getCompile('update', $table, $reset); } /** * Returns the generated 'delete' sql query * * @param string $table * @param bool $reset * @return string */ public function getCompiledDelete(string $table='', bool $reset=TRUE): string { return $this->_getCompile('delete', $table, $reset); } // -------------------------------------------------------------------------- // ! Miscellaneous Methods // -------------------------------------------------------------------------- /** * Clear out the class variables, so the next query can be run * * @return void */ public function resetQuery(): void { $this->state = new State(); $this->explain = FALSE; } /** * Method to simplify select_ methods * * @param string $field * @param string|bool $as * @return string */ protected function _select(string $field, $as = FALSE): string { // Escape the identifiers $field = $this->driver->quoteIdent($field); if ( ! \is_string($as)) { return $field; } $as = $this->driver->quoteIdent($as); return "({$field}) AS {$as} "; } /** * Helper function for returning sql strings * * @param string $type * @param string $table * @param bool $reset * @return string */ protected function _getCompile(string $type, string $table, bool $reset): string { $sql = $this->_compile($type, $table); // Reset the query builder for the next query if ($reset) { $this->resetQuery(); } return $sql; } /** * Simplify 'like' methods * * @param string $field * @param mixed $val * @param string $pos * @param string $like * @param string $conj * @return self */ protected function _like(string $field, $val, string $pos, string $like='LIKE', string $conj='AND'): self { $field = $this->driver->quoteIdent($field); // Add the like string into the order map $like = $field. " {$like} ?"; if ($pos === 'before') { $val = "%{$val}"; } elseif ($pos === 'after') { $val = "{$val}%"; } else { $val = "%{$val}%"; } $conj = empty($this->state->getQueryMap()) ? ' WHERE ' : " {$conj} "; $this->state->appendMap($conj, $like, 'like'); // Add to the values array $this->state->appendWhereValues($val); return $this; } /** * Simplify building having clauses * * @param mixed $key * @param mixed $values * @param string $conj * @return self */ protected function _having($key, $values=[], string $conj='AND'): self { $where = $this->_where($key, $values); // Create key/value placeholders foreach($where as $f => $val) { // Split each key by spaces, in case there // is an operator such as >, <, !=, etc. $fArray = explode(' ', trim($f)); $item = $this->driver->quoteIdent($fArray[0]); // Simple key value, or an operator $item .= (count($fArray) === 1) ? '=?' : " {$fArray[1]} ?"; // Put in the having map $this->state->appendHavingMap([ 'conjunction' => empty($this->state->getHavingMap()) ? ' HAVING ' : " {$conj} ", 'string' => $item ]); } return $this; } /** * Do all the redundant stuff for where/having type methods * * @param mixed $key * @param mixed $val * @return array */ protected function _where($key, $val=[]): array { $where = []; $pairs = []; if (is_scalar($key)) { $pairs[$key] = $val; } else { $pairs = $key; } foreach($pairs as $k => $v) { $where[$k] = $v; $this->state->appendWhereValues($v); } return $where; } /** * Simplify generating where string * * @param mixed $key * @param mixed $values * @param string $defaultConj * @return self */ protected function _whereString($key, $values=[], string $defaultConj='AND'): self { // Create key/value placeholders foreach($this->_where($key, $values) as $f => $val) { $queryMap = $this->state->getQueryMap(); // Split each key by spaces, in case there // is an operator such as >, <, !=, etc. $fArray = explode(' ', trim($f)); $item = $this->driver->quoteIdent($fArray[0]); // Simple key value, or an operator $item .= (count($fArray) === 1) ? '=?' : " {$fArray[1]} ?"; $lastItem = end($queryMap); // Determine the correct conjunction $conjunctionList = array_column($queryMap, 'conjunction'); if (empty($queryMap) || ( ! \regexInArray($conjunctionList, "/^ ?\n?WHERE/i"))) { $conj = "\nWHERE "; } elseif ($lastItem['type'] === 'group_start') { $conj = ''; } else { $conj = " {$defaultConj} "; } $this->state->appendMap($conj, $item, 'where'); } 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 * @return self */ protected function _whereIn($key, $val=[], string $in='IN', string $conj='AND'): self { $key = $this->driver->quoteIdent($key); $params = array_fill(0, count($val), '?'); $this->state->appendWhereValues($val); $conjunction = empty($this->state->getQueryMap()) ? ' WHERE ' : " {$conj} "; $str = $key . " {$in} (".implode(',', $params).') '; $this->state->appendMap($conjunction, $str, 'where_in'); return $this; } /** * Executes the compiled query * * @param string $type * @param string $table * @param string $sql * @param array|null $vals * @param boolean $reset * @return PDOStatement */ protected function _run(string $type, string $table, string $sql=NULL, array $vals=NULL, bool $reset=TRUE): PDOStatement { if ($sql === NULL) { $sql = $this->_compile($type, $table); } if ($vals === NULL) { $vals = array_merge($this->state->getValues(), $this->state->getWhereValues()); } $startTime = microtime(TRUE); $res = empty($vals) ? $this->driver->query($sql) : $this->driver->prepareExecute($sql, $vals); $endTime = microtime(TRUE); $totalTime = number_format($endTime - $startTime, 5); // Add this query to the list of executed queries $this->_appendQuery($vals, $sql, (int) $totalTime); // Reset class state for next query if ($reset) { $this->resetQuery(); } return $res; } /** * Convert the prepared statement into readable sql * * @param array $vals * @param string $sql * @param int $totalTime * @return void */ protected function _appendQuery(array $vals = NULL, string $sql, int $totalTime) { $evals = \is_array($vals) ? $vals : []; $esql = str_replace('?', "%s", $sql); // Quote string values foreach($evals as &$v) { $v = ( ! is_numeric($v)) ? htmlentities($this->driver->quote($v), ENT_NOQUOTES, 'utf-8') : $v; } // 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 $this->queries[] = [ 'time' => $totalTime, 'sql' => sprintf(...$evals) ]; $this->queries['total_time'] += $totalTime; // Set the last query to get rowcounts properly $this->driver->setLastQuery($sql); } /** * Sub-method for generating sql strings * * @param string $type * @param string $table * @return string */ protected function _compileType(string $type='', string $table=''): string { $setArrayKeys = $this->state->getSetArrayKeys(); switch($type) { case 'insert': $paramCount = count($setArrayKeys); $params = array_fill(0, $paramCount, '?'); $sql = "INSERT INTO {$table} (" . implode(',', $setArrayKeys) . ")\nVALUES (".implode(',', $params).')'; break; case 'update': $setString = $this->state->getSetString(); $sql = "UPDATE {$table}\nSET {$setString}"; break; case 'replace': // @TODO implement $sql = ''; break; case 'delete': $sql = "DELETE FROM {$table}"; break; // Get queries default: $fromString = $this->state->getFromString(); $selectString = $this->state->getSelectString(); $sql = "SELECT * \nFROM {$fromString}"; // Set the select string if ( ! empty($selectString)) { // Replace the star with the selected fields $sql = str_replace('*', $selectString, $sql); } break; } return $sql; } /** * String together the sql statements for sending to the db * * @param string $type * @param string $table * @return string */ protected function _compile(string $type='', string $table=''): string { // Get the base clause for the query $sql = $this->_compileType($type, $this->driver->quoteTable($table)); $clauses = [ 'queryMap', 'groupString', 'orderString', 'havingMap', ]; // Set each type of subclause foreach($clauses as $clause) { $func = 'get' . ucFirst($clause); $param = $this->state->$func(); if (\is_array($param)) { foreach($param as $q) { $sql .= $q['conjunction'] . $q['string']; } } else { $sql .= $param; } } // Set the limit via the class variables $limit = $this->state->getLimit(); if (is_numeric($limit)) { $sql = $this->driver->getSql()->limit($sql, $limit, $this->state->getOffset()); } // See if the query plan, rather than the // query data should be returned if ($this->explain === TRUE) { $sql = $this->driver->getSql()->explain($sql); } return $sql; } } |