-
-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathSqlBuilder.php
More file actions
568 lines (449 loc) · 14.9 KB
/
SqlBuilder.php
File metadata and controls
568 lines (449 loc) · 14.9 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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Database\Table;
use Nette;
use Nette\Database\ISupplementalDriver;
use Nette\Database\SqlLiteral;
use Nette\Database\IConventions;
use Nette\Database\Context;
use Nette\Database\IStructure;
/**
* Builds SQL query.
* SqlBuilder is based on great library NotORM http://www.notorm.com written by Jakub Vrana.
*/
class SqlBuilder extends Nette\Object
{
/** @var string */
protected $tableName;
/** @var IConventions */
protected $conventions;
/** @var string delimited table name */
protected $delimitedTable;
/** @var array of column to select */
protected $select = [];
/** @var array of where conditions */
protected $where = [];
/** @var array of where conditions for caching */
protected $conditions = [];
/** @var array of parameters passed to where conditions */
protected $parameters = [
'select' => [],
'where' => [],
'group' => [],
'having' => [],
'order' => [],
];
/** @var array or columns to order by */
protected $order = [];
/** @var int number of rows to fetch */
protected $limit = NULL;
/** @var int first row to fetch */
protected $offset = NULL;
/** @var string columns to grouping */
protected $group = '';
/** @var string grouping condition */
protected $having = '';
/** @var ISupplementalDriver */
private $driver;
/** @var IStructure */
private $structure;
/** @var array */
private $cacheTableList;
public function __construct($tableName, Context $context)
{
$this->tableName = $tableName;
$this->driver = $context->getConnection()->getSupplementalDriver();
$this->conventions = $context->getConventions();
$this->structure = $context->getStructure();
$this->delimitedTable = implode('.', array_map([$this->driver, 'delimite'], explode('.', $tableName)));
}
/**
* @return string
*/
public function getTableName()
{
return $this->tableName;
}
public function buildInsertQuery()
{
return "INSERT INTO {$this->delimitedTable}";
}
public function buildUpdateQuery()
{
if ($this->limit !== NULL || $this->offset) {
throw new Nette\NotSupportedException('LIMIT clause is not supported in UPDATE query.');
}
return "UPDATE {$this->delimitedTable} SET ?set" . $this->tryDelimite($this->buildConditions());
}
public function buildDeleteQuery()
{
if ($this->limit !== NULL || $this->offset) {
throw new Nette\NotSupportedException('LIMIT clause is not supported in DELETE query.');
}
return "DELETE FROM {$this->delimitedTable}" . $this->tryDelimite($this->buildConditions());
}
/**
* Returns SQL query.
* @param string list of columns
* @return string
*/
public function buildSelectQuery($columns = NULL)
{
if (!$this->order && ($this->limit !== NULL || $this->offset)) {
$this->order = array_map(
function ($col) { return "$this->tableName.$col"; },
(array) $this->conventions->getPrimary($this->tableName)
);
}
$queryCondition = $this->buildConditions();
$queryEnd = $this->buildQueryEnd();
$joins = [];
$this->parseJoins($joins, $queryCondition);
$this->parseJoins($joins, $queryEnd);
if ($this->select) {
$querySelect = $this->buildSelect($this->select);
$this->parseJoins($joins, $querySelect);
} elseif ($columns) {
$prefix = $joins ? "{$this->delimitedTable}." : '';
$cols = [];
foreach ($columns as $col) {
$cols[] = $prefix . $col;
}
$querySelect = $this->buildSelect($cols);
} elseif ($this->group && !$this->driver->isSupported(ISupplementalDriver::SUPPORT_SELECT_UNGROUPED_COLUMNS)) {
$querySelect = $this->buildSelect([$this->group]);
$this->parseJoins($joins, $querySelect);
} else {
$prefix = $joins ? "{$this->delimitedTable}." : '';
$querySelect = $this->buildSelect([$prefix . '*']);
}
$queryJoins = $this->buildQueryJoins($joins);
$query = "{$querySelect} FROM {$this->delimitedTable}{$queryJoins}{$queryCondition}{$queryEnd}";
$this->driver->applyLimit($query, $this->limit, $this->offset);
return $this->tryDelimite($query);
}
public function getParameters()
{
return array_merge(
$this->parameters['select'],
$this->parameters['where'],
$this->parameters['group'],
$this->parameters['having'],
$this->parameters['order']
);
}
public function importConditions(SqlBuilder $builder)
{
$this->where = $builder->where;
$this->parameters['where'] = $builder->parameters['where'];
$this->conditions = $builder->conditions;
}
/********************* SQL selectors ****************d*g**/
public function addSelect($columns, ...$params)
{
if (is_array($columns)) {
throw new Nette\InvalidArgumentException('Select column must be a string.');
}
$this->select[] = $columns;
$this->parameters['select'] = array_merge($this->parameters['select'], $params);
}
public function getSelect()
{
return $this->select;
}
public function addWhere($condition, ...$params)
{
if (is_array($condition) && !empty($params[0]) && is_array($params[0])) {
return $this->addWhereComposition($condition, $params[0]);
}
$hash = md5($condition . json_encode($params));
if (isset($this->conditions[$hash])) {
return FALSE;
}
$this->conditions[$hash] = $condition;
$placeholderCount = substr_count($condition, '?');
if ($placeholderCount > 1 && count($params) === 1 && is_array($params[0])) {
$params = $params[0];
}
$condition = trim($condition);
if ($placeholderCount === 0 && count($params) === 1) {
$condition .= ' ?';
} elseif ($placeholderCount !== count($params)) {
throw new Nette\InvalidArgumentException('Argument count does not match placeholder count.');
}
$replace = NULL;
$placeholderNum = 0;
foreach ($params as $arg) {
preg_match('#(?:.*?\?.*?){' . $placeholderNum . '}(((?:&|\||^|~|\+|-|\*|/|%|\(|,|<|>|=|(?<=\W|^)(?:REGEXP|ALL|AND|ANY|BETWEEN|EXISTS|IN|[IR]?LIKE|OR|NOT|SOME|INTERVAL))\s*)?(?:\(\?\)|\?))#s', $condition, $match, PREG_OFFSET_CAPTURE);
$hasOperator = ($match[1][0] === '?' && $match[1][1] === 0) ? TRUE : !empty($match[2][0]);
if ($arg === NULL) {
$replace = 'IS NULL';
if ($hasOperator) {
if (trim($match[2][0]) === 'NOT') {
$replace = 'IS NOT NULL';
} else {
throw new Nette\InvalidArgumentException('Column operator does not accept NULL argument.');
}
}
} elseif (is_array($arg) || $arg instanceof Selection) {
if ($hasOperator) {
if (trim($match[2][0]) === 'NOT') {
$match[2][0] = rtrim($match[2][0]) . ' IN ';
} elseif (trim($match[2][0]) !== 'IN') {
throw new Nette\InvalidArgumentException('Column operator does not accept array argument.');
}
} else {
$match[2][0] = 'IN ';
}
if ($arg instanceof Selection) {
$clone = clone $arg;
if (!$clone->getSqlBuilder()->select) {
try {
$clone->select($clone->getPrimary());
} catch (\LogicException $e) {
throw new Nette\InvalidArgumentException('Selection argument must have defined a select column.', 0, $e);
}
}
if ($this->driver->isSupported(ISupplementalDriver::SUPPORT_SUBSELECT)) {
$arg = NULL;
$replace = $match[2][0] . '(' . $clone->getSql() . ')';
$this->parameters['where'] = array_merge($this->parameters['where'], $clone->getSqlBuilder()->getParameters());
} else {
$arg = [];
foreach ($clone as $row) {
$arg[] = array_values(iterator_to_array($row));
}
}
}
if ($arg !== NULL) {
if (!$arg) {
$hasBrackets = strpos($condition, '(') !== FALSE;
$hasOperators = preg_match('#AND|OR#', $condition);
$hasNot = strpos($condition, 'NOT') !== FALSE;
$hasPrefixNot = strpos($match[2][0], 'NOT') !== FALSE;
if (!$hasBrackets && ($hasOperators || ($hasNot && !$hasPrefixNot))) {
throw new Nette\InvalidArgumentException('Possible SQL query corruption. Add parentheses around operators.');
}
if ($hasPrefixNot) {
$replace = 'IS NULL OR TRUE';
} else {
$replace = 'IS NULL AND FALSE';
}
$arg = NULL;
} else {
$replace = $match[2][0] . '(?)';
$this->parameters['where'][] = $arg;
}
}
} elseif ($arg instanceof SqlLiteral) {
$this->parameters['where'][] = $arg;
} else {
if (!$hasOperator) {
$replace = '= ?';
}
$this->parameters['where'][] = $arg;
}
if ($replace) {
$condition = substr_replace($condition, $replace, $match[1][1], strlen($match[1][0]));
$replace = NULL;
}
if ($arg !== NULL) {
$placeholderNum++;
}
}
$this->where[] = $condition;
return TRUE;
}
public function getConditions()
{
return array_values($this->conditions);
}
public function addOrder($columns, ...$params)
{
$this->order[] = $columns;
$this->parameters['order'] = array_merge($this->parameters['order'], $params);
}
public function setOrder(array $columns, array $parameters)
{
$this->order = $columns;
$this->parameters['order'] = $parameters;
}
public function getOrder()
{
return $this->order;
}
public function setLimit($limit, $offset)
{
$this->limit = $limit;
$this->offset = $offset;
}
public function getLimit()
{
return $this->limit;
}
public function getOffset()
{
return $this->offset;
}
public function setGroup($columns, ...$params)
{
$this->group = $columns;
$this->parameters['group'] = $params;
}
public function getGroup()
{
return $this->group;
}
public function setHaving($having, ...$params)
{
$this->having = $having;
$this->parameters['having'] = $params;
}
public function getHaving()
{
return $this->having;
}
/********************* SQL building ****************d*g**/
protected function buildSelect(array $columns)
{
return 'SELECT ' . implode(', ', $columns);
}
protected function parseJoins(& $joins, & $query)
{
$query = preg_replace_callback('~
(?(DEFINE)
(?P<word> [\w_]*[a-z][\w_]* )
(?P<del> [.:] )
(?P<node> (?&del)? (?&word) (\((?&word)\))? )
)
(?P<chain> (?!\.) (?&node)*) \. (?P<column> (?&word) | \* )
~xi', function ($match) use (& $joins) {
return $this->parseJoinsCb($joins, $match);
}, $query);
}
public function parseJoinsCb(& $joins, $match)
{
$chain = $match['chain'];
if (!empty($chain[0]) && ($chain[0] !== '.' && $chain[0] !== ':')) {
$chain = '.' . $chain; // unified chain format
}
preg_match_all('~
(?(DEFINE)
(?P<word> [\w_]*[a-z][\w_]* )
)
(?P<del> [.:])?(?P<key> (?&word))(\((?P<throughColumn> (?&word))\))?
~xi', $chain, $keyMatches, PREG_SET_ORDER);
$parent = $this->tableName;
$parentAlias = preg_replace('#^(.*\.)?(.*)$#', '$2', $this->tableName);
// join schema keyMatch and table keyMatch to schema.table keyMatch
if ($this->driver->isSupported(ISupplementalDriver::SUPPORT_SCHEMA) && count($keyMatches) > 1) {
$tables = $this->getCachedTableList();
if (!isset($tables[$keyMatches[0]['key']]) && isset($tables[$keyMatches[0]['key'] . '.' . $keyMatches[1]['key']])) {
$keyMatch = array_shift($keyMatches);
$keyMatches[0]['key'] = $keyMatch['key'] . '.' . $keyMatches[0]['key'];
$keyMatches[0]['del'] = $keyMatch['del'];
}
}
// do not make a join when referencing to the current table column - inner conditions
// check it only when not making backjoin on itself - outer condition
if ($keyMatches[0]['del'] === '.') {
if ($parent === $keyMatches[0]['key']) {
return "{$parent}.{$match['column']}";
} elseif ($parentAlias === $keyMatches[0]['key']) {
return "{$parentAlias}.{$match['column']}";
}
}
foreach ($keyMatches as $keyMatch) {
if ($keyMatch['del'] === ':') {
if (isset($keyMatch['throughColumn'])) {
$table = $keyMatch['key'];
$belongsTo = $this->conventions->getBelongsToReference($table, $keyMatch['throughColumn']);
if (!$belongsTo) {
throw new Nette\InvalidArgumentException("No reference found for \${$parent}->{$keyMatch['key']}.");
}
list(, $primary) = $belongsTo;
} else {
$hasMany = $this->conventions->getHasManyReference($parent, $keyMatch['key']);
if (!$hasMany) {
throw new Nette\InvalidArgumentException("No reference found for \${$parent}->related({$keyMatch['key']}).");
}
list($table, $primary) = $hasMany;
}
$column = $this->conventions->getPrimary($parent);
} else {
$belongsTo = $this->conventions->getBelongsToReference($parent, $keyMatch['key']);
if (!$belongsTo) {
throw new Nette\InvalidArgumentException("No reference found for \${$parent}->{$keyMatch['key']}.");
}
list($table, $column) = $belongsTo;
$foreign = $this->conventions->getForeign($parent, $column); //check for foreign key instead primary key in referenced table
$primary = $foreign == NULL ? $this->conventions->getPrimary($table) : $foreign;
}
$tableAlias = $keyMatch['key'] ?: preg_replace('#^(.*\.)?(.*)$#', '$2', $table);
// if we are joining itself (parent table), we must alias joining table
if ($parent === $table) {
$tableAlias = $parentAlias . '_ref';
}
$joins[$tableAlias . $column] = [$table, $tableAlias, $parentAlias, $column, $primary];
$parent = $table;
$parentAlias = $tableAlias;
}
return $tableAlias . ".{$match['column']}";
}
protected function buildQueryJoins(array $joins)
{
$return = '';
foreach ($joins as list($joinTable, $joinAlias, $table, $tableColumn, $joinColumn)) {
$return .=
" LEFT JOIN {$joinTable}" . ($joinTable !== $joinAlias ? " {$joinAlias}" : '') .
" ON {$table}.{$tableColumn} = {$joinAlias}.{$joinColumn}";
}
return $return;
}
protected function buildConditions()
{
return $this->where ? ' WHERE (' . implode(') AND (', $this->where) . ')' : '';
}
protected function buildQueryEnd()
{
$return = '';
if ($this->group) {
$return .= ' GROUP BY '. $this->group;
}
if ($this->having) {
$return .= ' HAVING '. $this->having;
}
if ($this->order) {
$return .= ' ORDER BY ' . implode(', ', $this->order);
}
return $return;
}
protected function tryDelimite($s)
{
return preg_replace_callback('#(?<=[^\w`"\[?]|^)[a-z_][a-z0-9_]*(?=[^\w`"(\]]|\z)#i', function ($m) {
return strtoupper($m[0]) === $m[0] ? $m[0] : $this->driver->delimite($m[0]);
}, $s);
}
protected function addWhereComposition(array $columns, array $parameters)
{
if ($this->driver->isSupported(ISupplementalDriver::SUPPORT_MULTI_COLUMN_AS_OR_COND)) {
$conditionFragment = '(' . implode(' = ? AND ', $columns) . ' = ?) OR ';
$condition = substr(str_repeat($conditionFragment, count($parameters)), 0, -4);
return $this->addWhere($condition, Nette\Utils\Arrays::flatten($parameters));
} else {
return $this->addWhere('(' . implode(', ', $columns) . ') IN', $parameters);
}
}
private function getCachedTableList()
{
if (!$this->cacheTableList) {
$this->cacheTableList = array_flip(array_map(function ($pair) {
return isset($pair['fullName']) ? $pair['fullName'] : $pair['name'];
}, $this->structure->getTables()));
}
return $this->cacheTableList;
}
}