-
-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathBaseAdapter.php
More file actions
542 lines (464 loc) · 16 KB
/
BaseAdapter.php
File metadata and controls
542 lines (464 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
<?php namespace Pixie\QueryBuilder\Adapters;
use Pixie\Connection;
use Pixie\Exception;
use Pixie\QueryBuilder\Raw;
abstract class BaseAdapter
{
/**
* @var \Pixie\Connection
*/
protected $connection;
/**
* @var \Viocon\Container
*/
protected $container;
public function __construct(Connection $connection)
{
$this->connection = $connection;
$this->container = $this->connection->getContainer();
}
/**
* Build select query string and bindings
*
* @param $statements
*
* @throws Exception
* @return array
*/
public function select($statements)
{
if (!array_key_exists('tables', $statements)) {
throw new Exception('No table specified.', 3);
} elseif (!array_key_exists('selects', $statements)) {
$statements['selects'][] = '*';
}
// From
$tables = $this->arrayStr($statements['tables'], ', ');
// Select
$selects = $this->arrayStr($statements['selects'], ', ');
// Wheres
list($whereCriteria, $whereBindings) = $this->buildCriteriaWithType($statements, 'wheres', 'WHERE');
// Group bys
$groupBys = '';
if (isset($statements['groupBys']) && $groupBys = $this->arrayStr($statements['groupBys'], ', ')) {
$groupBys = 'GROUP BY ' . $groupBys;
}
// Order bys
$orderBys = '';
if (isset($statements['orderBys']) && is_array($statements['orderBys'])) {
foreach ($statements['orderBys'] as $orderBy) {
$orderBys .= $this->wrapSanitizer($orderBy['field']) . ' ' . $orderBy['type'] . ', ';
}
if ($orderBys = trim($orderBys, ', ')) {
$orderBys = 'ORDER BY ' . $orderBys;
}
}
// Limit and offset
$limit = isset($statements['limit']) ? 'LIMIT ' . $statements['limit'] : '';
$offset = isset($statements['offset']) ? 'OFFSET ' . $statements['offset'] : '';
// Having
list($havingCriteria, $havingBindings) = $this->buildCriteriaWithType($statements, 'havings', 'HAVING');
// Joins
$joinString = $this->buildJoin($statements);
$sqlArray = array(
'SELECT' . (isset($statements['distinct']) ? ' DISTINCT' : ''),
$selects,
'FROM',
$tables,
$joinString,
$whereCriteria,
$groupBys,
$havingCriteria,
$orderBys,
$limit,
$offset
);
$sql = $this->concatenateQuery($sqlArray);
$bindings = array_merge(
$whereBindings,
$havingBindings
);
return compact('sql', 'bindings');
}
/**
* Build just criteria part of the query
*
* @param $statements
* @param bool $bindValues
*
* @return array
*/
public function criteriaOnly($statements, $bindValues = true)
{
$sql = $bindings = array();
if (!isset($statements['criteria'])) {
return compact('sql', 'bindings');
}
list($sql, $bindings) = $this->buildCriteria($statements['criteria'], $bindValues);
return compact('sql', 'bindings');
}
/**
* Build a generic insert/ignore/replace query
*
* @param $statements
* @param array $data
*
* @return array
* @throws Exception
*/
private function doInsert($statements, array $data, $type)
{
if (!isset($statements['tables'])) {
throw new Exception('No table specified', 3);
}
$table = end($statements['tables']);
$bindings = $keys = $values = array();
foreach ($data as $key => $value) {
$keys[] = $key;
if ($value instanceof Raw) {
$values[] = (string) $value;
$bindings = array_merge($bindings, $value->getBindings());
} else {
$values[] = '?';
$bindings[] = $value;
}
}
$sqlArray = array(
$type . ' INTO',
$this->wrapSanitizer($table),
'(' . $this->arrayStr($keys, ',') . ')',
'VALUES',
'(' . $this->arrayStr($values, ',', false) . ')',
);
if (isset($statements['onduplicate'])) {
if (count($statements['onduplicate']) < 1) {
throw new Exception('No data given.', 4);
}
list($updateStatement, $updateBindings) = $this->getUpdateStatement($statements['onduplicate']);
$sqlArray[] = 'ON DUPLICATE KEY UPDATE ' . $updateStatement;
$bindings = array_merge($bindings, $updateBindings);
}
$sql = $this->concatenateQuery($sqlArray);
return compact('sql', 'bindings');
}
/**
* Build Insert query
*
* @param $statements
* @param array $data
*
* @return array
* @throws Exception
*/
public function insert($statements, array $data)
{
return $this->doInsert($statements, $data, 'INSERT');
}
/**
* Build Insert Ignore query
*
* @param $statements
* @param array $data
*
* @return array
* @throws Exception
*/
public function insertIgnore($statements, array $data)
{
return $this->doInsert($statements, $data, 'INSERT IGNORE');
}
/**
* Build Insert Ignore query
*
* @param $statements
* @param array $data
*
* @return array
* @throws Exception
*/
public function replace($statements, array $data)
{
return $this->doInsert($statements, $data, 'REPLACE');
}
/**
* Build fields assignment part of SET ... or ON DUBLICATE KEY UPDATE ... statements
*
* @param array $data
*
* @return array
*/
private function getUpdateStatement($data)
{
$bindings = array();
$statement = '';
foreach ($data as $key => $value) {
if ($value instanceof Raw) {
$statement .= $this->wrapSanitizer($key) . '=' . $value . ',';
$bindings = array_merge($bindings, $value->getBindings());
} else {
$statement .= $this->wrapSanitizer($key) . '=?,';
$bindings[] = $value;
}
}
$statement = trim($statement, ',');
return array($statement, $bindings);
}
/**
* Build update query
*
* @param $statements
* @param array $data
*
* @return array
* @throws Exception
*/
public function update($statements, array $data)
{
if (!isset($statements['tables'])) {
throw new Exception('No table specified', 3);
} elseif (count($data) < 1) {
throw new Exception('No data given.', 4);
}
$table = end($statements['tables']);
// Update statement
list($updateStatement, $bindings) = $this->getUpdateStatement($data);
// Wheres
list($whereCriteria, $whereBindings) = $this->buildCriteriaWithType($statements, 'wheres', 'WHERE');
// Limit
$limit = isset($statements['limit']) ? 'LIMIT ' . $statements['limit'] : '';
$sqlArray = array(
'UPDATE',
$this->wrapSanitizer($table),
'SET ' . $updateStatement,
$whereCriteria,
$limit
);
$sql = $this->concatenateQuery($sqlArray);
$bindings = array_merge($bindings, $whereBindings);
return compact('sql', 'bindings');
}
/**
* Build delete query
*
* @param $statements
*
* @return array
* @throws Exception
*/
public function delete($statements)
{
if (!isset($statements['tables'])) {
throw new Exception('No table specified', 3);
}
$table = end($statements['tables']);
// Wheres
list($whereCriteria, $whereBindings) = $this->buildCriteriaWithType($statements, 'wheres', 'WHERE');
// Limit
$limit = isset($statements['limit']) ? 'LIMIT ' . $statements['limit'] : '';
$sqlArray = array('DELETE FROM', $this->wrapSanitizer($table), $whereCriteria);
$sql = $this->concatenateQuery($sqlArray);
$bindings = $whereBindings;
return compact('sql', 'bindings');
}
/**
* Array concatenating method, like implode.
* But it does wrap sanitizer and trims last glue
*
* @param array $pieces
* @param $glue
* @param bool $wrapSanitizer
*
* @return string
*/
protected function arrayStr(array $pieces, $glue, $wrapSanitizer = true)
{
$str = '';
foreach ($pieces as $key => $piece) {
if ($wrapSanitizer) {
$piece = $this->wrapSanitizer($piece);
}
if (!is_int($key)) {
$piece = ($wrapSanitizer ? $this->wrapSanitizer($key) : $key) . ' AS ' . $piece;
}
$str .= $piece . $glue;
}
return trim($str, $glue);
}
/**
* Join different part of queries with a space.
*
* @param array $pieces
*
* @return string
*/
protected function concatenateQuery(array $pieces)
{
$str = '';
foreach ($pieces as $piece) {
$str = trim($str) . ' ' . trim($piece);
}
return trim($str);
}
/**
* Build generic criteria string and bindings from statements, like "a = b and c = ?"
*
* @param $statements
* @param bool $bindValues
*
* @return array
*/
protected function buildCriteria($statements, $bindValues = true)
{
$criteria = '';
$bindings = array();
foreach ($statements as $statement) {
$key = $this->wrapSanitizer($statement['key']);
$value = $statement['value'];
if (is_null($value) && $key instanceof \Closure) {
// We have a closure, a nested criteria
// Build a new NestedCriteria class, keep it by reference so any changes made
// in the closure should reflect here
$nestedCriteria = $this->container->build(
'\\Pixie\\QueryBuilder\\NestedCriteria',
array($this->connection)
);
$nestedCriteria = & $nestedCriteria;
// Call the closure with our new nestedCriteria object
$key($nestedCriteria);
// Get the criteria only query from the nestedCriteria object
$queryObject = $nestedCriteria->getQuery('criteriaOnly', true);
// Merge the bindings we get from nestedCriteria object
$bindings = array_merge($bindings, $queryObject->getBindings());
// Append the sql we get from the nestedCriteria object
$criteria .= $statement['joiner'] . ' (' . $queryObject->getSql() . ') ';
} elseif (is_array($value)) {
// where_in or between like query
$criteria .= $statement['joiner'] . ' ' . $key . ' ' . $statement['operator'];
switch ($statement['operator']) {
case 'BETWEEN':
$bindings = array_merge($bindings, $statement['value']);
$criteria .= ' ? AND ? ';
break;
default:
$valuePlaceholder = '';
foreach ($statement['value'] as $subValue) {
$valuePlaceholder .= '?, ';
$bindings[] = $subValue;
}
$valuePlaceholder = trim($valuePlaceholder, ', ');
$criteria .= ' (' . $valuePlaceholder . ') ';
break;
}
} elseif ($value instanceof Raw) {
$criteria .= "{$statement['joiner']} {$key} {$statement['operator']} $value ";
if ($bindValues) {
$bindings = array_merge($bindings, $value->getBindings());
}
} else {
// Usual where like criteria
if (!$bindValues) {
// Specially for joins
// We are not binding values, lets sanitize then
$value = $this->wrapSanitizer($value);
$criteria .= $statement['joiner'] . ' ' . $key . ' ' . $statement['operator'] . ' ' . $value . ' ';
} elseif ($statement['key'] instanceof Raw) {
$criteria .= $statement['joiner'] . ' ' . $key . ' ';
$bindings = array_merge($bindings, $statement['key']->getBindings());
} else {
// For wheres
$valuePlaceholder = '?';
$bindings[] = $value;
$criteria .= $statement['joiner'] . ' ' . $key . ' ' . $statement['operator'] . ' '
. $valuePlaceholder . ' ';
}
}
}
// Clear all white spaces, and, or from beginning and white spaces from ending
$criteria = preg_replace('/^(\s?AND ?|\s?OR ?)|\s$/i', '', $criteria);
return array($criteria, $bindings);
}
/**
* Wrap values with adapter's sanitizer like, '`'
*
* @param $value
*
* @return string
*/
public function wrapSanitizer($value)
{
// Its a raw query, just cast as string, object has __toString()
if ($value instanceof Raw) {
return (string)$value;
} elseif ($value instanceof \Closure) {
return $value;
}
// Separate our table and fields which are joined with a ".",
// like my_table.id
$valueArr = explode('.', $value, 2);
foreach ($valueArr as $key => $subValue) {
// Don't wrap if we have *, which is not a usual field
$valueArr[$key] = trim($subValue) == '*' ? $subValue : $this->sanitizer . $subValue . $this->sanitizer;
}
// Join these back with "." and return
return implode('.', $valueArr);
}
/**
* Build criteria string and binding with various types added, like WHERE and Having
*
* @param $statements
* @param $key
* @param $type
* @param bool $bindValues
*
* @return array
*/
protected function buildCriteriaWithType($statements, $key, $type, $bindValues = true)
{
$criteria = '';
$bindings = array();
if (isset($statements[$key])) {
// Get the generic/adapter agnostic criteria string from parent
list($criteria, $bindings) = $this->buildCriteria($statements[$key], $bindValues);
if ($criteria) {
$criteria = $type . ' ' . $criteria;
}
}
return array($criteria, $bindings);
}
/**
* Build join string
*
* @param $statements
*
* @return array
*/
protected function buildJoin($statements)
{
$sql = '';
if (!array_key_exists('joins', $statements) || !is_array($statements['joins'])) {
return $sql;
}
foreach ($statements['joins'] as $joinArr) {
if (is_array($joinArr['table'])) {
$mainTable = $joinArr['table'][0];
$aliasTable = $joinArr['table'][1];
$table = $this->wrapSanitizer($mainTable) . ' AS ' . $this->wrapSanitizer($aliasTable);
} else {
$table = $joinArr['table'] instanceof Raw ?
(string) $joinArr['table'] :
$this->wrapSanitizer($joinArr['table']);
}
$joinBuilder = $joinArr['joinBuilder'];
$sqlArr = array(
$sql,
strtoupper($joinArr['type']),
'JOIN',
$table,
'ON',
$joinBuilder->getQuery('criteriaOnly', false)->getSql()
);
$sql = $this->concatenateQuery($sqlArr);
}
return $sql;
}
}