This repository has been archived by the owner on May 11, 2021. It is now read-only.
/
Query.php
1416 lines (1181 loc) · 40.5 KB
/
Query.php
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace Atk4\Dsql;
use Doctrine\DBAL\Result as DbalResult;
/**
* Perform query operation on SQL server (such as select, insert, delete, etc).
*/
class Query extends Expression
{
/**
* Query will use one of the predefined templates. The $mode will contain
* name of template used. Basically it's part of Query property name -
* Query::template_[$mode].
*
* @var string
*/
public $mode = 'select';
/**
* If no fields are defined, this field is used.
*
* @var string|Expression
*/
public $defaultField = '*';
/** @var string Expression classname */
protected $expression_class = Expression::class;
/** @var bool */
public $wrapInParentheses = true;
/** @var string */
protected $template_select = '[with]select[option] [field] [from] [table][join][where][group][having][order][limit]';
/** @var string */
protected $template_insert = 'insert[option] into [table_noalias] ([set_fields]) values ([set_values])';
/** @var string */
protected $template_replace = 'replace[option] into [table_noalias] ([set_fields]) values ([set_values])';
/** @var string */
protected $template_delete = '[with]delete [from] [table_noalias][where][having]';
/** @var string */
protected $template_update = '[with]update [table_noalias] set [set] [where]';
/** @var string */
protected $template_truncate = 'truncate table [table_noalias]';
/**
* Name or alias of base table to use when using default join().
*
* This is set by table(). If you are using multiple tables,
* then $main_table is set to false as it is irrelevant.
*
* @var false|string|null
*/
protected $main_table;
// {{{ Field specification and rendering
/**
* Adds new column to resulting select by querying $field.
*
* Examples:
* $q->field('name');
*
* You can use a dot to prepend table name to the field:
* $q->field('user.name');
* $q->field('user.name')->field('address.line1');
*
* Array as a first argument will specify multiple fields, same as calling field() multiple times
* $q->field(['name', 'surname', 'address.line1']);
*
* You can pass first argument as Expression or Query
* $q->field( $q->expr('2+2'), 'alias'); // must always use alias
*
* You can use $q->dsql() for subqueries. Subqueries will be wrapped in
* brackets.
* $q->field( $q->dsql()->table('x')... , 'alias');
*
* Associative array will assume that "key" holds the field alias.
* Value may be field name, Expression or Query.
* $q->field(['alias' => 'name', 'alias2' => 'mother.surname']);
* $q->field(['alias' => $q->expr(..), 'alias2' => $q->dsql()->.. ]);
*
* If you need to use funky name for the field (e.g, one containing
* a dot or a space), you should wrap it into expression:
* $q->field($q->expr('{}', ['fun...ky.field']), 'f');
*
* @param mixed $field Specifies field to select
* @param string $alias Specify alias for this field
*
* @return $this
*/
public function field($field, $alias = null)
{
// field is passed as string, may contain commas
if (is_string($field) && strpos($field, ',') !== false) {
$field = explode(',', $field);
}
// recursively add array fields
if (is_array($field)) {
if ($alias !== null) {
throw (new Exception('Alias must not be specified when $field is an array'))
->addMoreInfo('alias', $alias);
}
foreach ($field as $alias => $f) {
$this->field($f, is_numeric($alias) ? null : $alias);
}
return $this;
}
// save field in args
$this->_set_args('field', $alias, $field);
return $this;
}
/**
* Returns template component for [field].
*
* @param bool $add_alias Should we add aliases, see _render_field_noalias()
*
* @return string Parsed template chunk
*/
protected function _render_field($add_alias = true): string
{
// will be joined for output
$ret = [];
// If no fields were defined, use defaultField
if (empty($this->args['field'])) {
if ($this->defaultField instanceof Expression) {
return $this->consume($this->defaultField);
}
return (string) $this->defaultField;
}
// process each defined field
foreach ($this->args['field'] as $alias => $field) {
// Do not add alias, if:
// - we don't want aliases OR
// - alias is the same as field OR
// - alias is numeric
if (
$add_alias === false
|| (is_string($field) && $alias === $field)
|| is_numeric($alias)
) {
$alias = null;
}
// Will parameterize the value and escape if necessary
$field = $this->consume($field, self::ESCAPE_IDENTIFIER_SOFT);
if ($alias) {
// field alias cannot be expression, so simply escape it
$field .= ' ' . $this->escapeIdentifier($alias);
}
$ret[] = $field;
}
return implode(', ', $ret);
}
protected function _render_field_noalias(): string
{
return $this->_render_field(false);
}
// }}}
// {{{ Table specification and rendering
/**
* Specify a table to be used in a query.
*
* @param mixed $table Specifies table
* @param string $alias Specify alias for this table
*
* @return $this
*/
public function table($table, $alias = null)
{
// comma-separated table names
if (is_string($table) && strpos($table, ',') !== false) {
$table = explode(',', $table);
}
// array of tables - recursively process each
if (is_array($table)) {
if ($alias !== null) {
throw (new Exception('You cannot use single alias with multiple tables'))
->addMoreInfo('alias', $alias);
}
foreach ($table as $alias => $t) {
if (is_numeric($alias)) {
$alias = null;
}
$this->table($t, $alias);
}
return $this;
}
// if table is set as sub-Query, then alias is mandatory
if ($table instanceof self && $alias === null) {
throw new Exception('If table is set as Query, then table alias is mandatory');
}
if (is_string($table) && $alias === null) {
$alias = $table;
}
// main_table will be set only if table() is called once.
// it's used as "default table" when joining with other tables, see join().
// on multiple calls, main_table will be false and we won't
// be able to join easily anymore.
$this->main_table = ($this->main_table === null && $alias !== null ? $alias : false);
// save table in args
$this->_set_args('table', $alias, $table);
return $this;
}
/**
* @param bool $add_alias Should we add aliases, see _render_table_noalias()
*/
protected function _render_table($add_alias = true): ?string
{
// will be joined for output
$ret = [];
if (empty($this->args['table'])) {
return '';
}
// process tables one by one
foreach ($this->args['table'] as $alias => $table) {
// throw exception if we don't want to add alias and table is defined as Expression
if ($add_alias === false && $table instanceof self) {
throw new Exception('Table cannot be Query in UPDATE, INSERT etc. query modes');
}
// Do not add alias, if:
// - we don't want aliases OR
// - alias is the same as table name OR
// - alias is numeric
if (
$add_alias === false
|| (is_string($table) && $alias === $table)
|| is_numeric($alias)
) {
$alias = null;
}
// consume or escape table
$table = $this->consume($table, self::ESCAPE_IDENTIFIER_SOFT);
// add alias if needed
if ($alias) {
$table .= ' ' . $this->escapeIdentifier($alias);
}
$ret[] = $table;
}
return implode(', ', $ret);
}
protected function _render_table_noalias(): ?string
{
return $this->_render_table(false);
}
protected function _render_from(): ?string
{
return empty($this->args['table']) ? '' : 'from';
}
/// }}}
// {{{ with()
/**
* Specify WITH query to be used.
*
* @param Query $cursor Specifies cursor query or array [alias=>query] for adding multiple
* @param string $alias Specify alias for this cursor
* @param array $fields Optional array of field names used in cursor
* @param bool $recursive Is it recursive?
*
* @return $this
*/
public function with(self $cursor, string $alias, array $fields = null, bool $recursive = false)
{
// save cursor in args
$this->_set_args('with', $alias, [
'cursor' => $cursor,
'fields' => $fields,
'recursive' => $recursive,
]);
return $this;
}
/**
* Recursive WITH query.
*
* @param Query $cursor Specifies cursor query or array [alias=>query] for adding multiple
* @param string $alias Specify alias for this cursor
* @param array $fields Optional array of field names used in cursor
*
* @return $this
*/
public function withRecursive(self $cursor, string $alias, array $fields = null)
{
return $this->with($cursor, $alias, $fields, true);
}
protected function _render_with(): ?string
{
// will be joined for output
$ret = [];
if (empty($this->args['with'])) {
return '';
}
// process each defined cursor
$isRecursive = false;
foreach ($this->args['with'] as $alias => ['cursor' => $cursor, 'fields' => $fields, 'recursive' => $recursive]) {
// cursor alias cannot be expression, so simply escape it
$s = $this->escapeIdentifier($alias) . ' ';
// set cursor fields
if ($fields !== null) {
$s .= '(' . implode(', ', array_map([$this, 'escapeIdentifier'], $fields)) . ') ';
}
// will parameterize the value and escape if necessary
$s .= 'as ' . $this->consume($cursor, self::ESCAPE_IDENTIFIER_SOFT);
// is at least one recursive ?
$isRecursive = $isRecursive || $recursive;
$ret[] = $s;
}
return 'with ' . ($isRecursive ? 'recursive ' : '') . implode(', ', $ret) . ' ';
}
/// }}}
// {{{ join()
/**
* Joins your query with another table. Join will use $main_table
* to reference the main table, unless you specify it explicitly.
*
* Examples:
* $q->join('address'); // on user.address_id=address.id
* $q->join('address.user_id'); // on address.user_id=user.id
* $q->join('address a'); // With alias
* $q->join(array('a'=>'address')); // Also alias
*
* Second argument may specify the field of the master table
* $q->join('address', 'billing_id');
* $q->join('address.code', 'code');
* $q->join('address.code', 'user.code');
*
* Third argument may specify which kind of join to use.
* $q->join('address', null, 'left');
* $q->join('address.code', 'user.code', 'inner');
*
* Using array syntax you can join multiple tables too
* $q->join(array('a'=>'address', 'p'=>'portfolio'));
*
* You can use expression for more complex joins
* $q->join('address',
* $q->orExpr()
* ->where('user.billing_id=address.id')
* ->where('user.technical_id=address.id')
* )
*
* @param string|array $foreign_table Table to join with
* @param mixed $master_field Field in master table
* @param string $join_kind 'left' or 'inner', etc
* @param string $_foreign_alias Internal, don't use
*
* @return $this
*/
public function join(
$foreign_table,
$master_field = null,
$join_kind = null,
$_foreign_alias = null
) {
// If array - add recursively
if (is_array($foreign_table)) {
foreach ($foreign_table as $alias => $foreign) {
if (is_numeric($alias)) {
$alias = null;
}
$this->join($foreign, $master_field, $join_kind, $alias);
}
return $this;
}
$j = [];
// try to find alias in foreign table definition. this behaviour should be deprecated
if ($_foreign_alias === null) {
[$foreign_table, $_foreign_alias] = array_pad(explode(' ', $foreign_table, 2), 2, null);
}
// Split and deduce fields
// NOTE that this will not allow table names with dots in there !!!
[$f1, $f2] = array_pad(explode('.', $foreign_table, 2), 2, null);
if (is_object($master_field)) {
$j['expr'] = $master_field;
} else {
// Split and deduce primary table
if ($master_field === null) {
[$m1, $m2] = [null, null];
} else {
[$m1, $m2] = array_pad(explode('.', $master_field, 2), 2, null);
}
if ($m2 === null) {
$m2 = $m1;
$m1 = null;
}
if ($m1 === null) {
$m1 = $this->main_table;
}
// Identify fields we use for joins
if ($f2 === null && $m2 === null) {
$m2 = $f1 . '_id';
}
if ($m2 === null) {
$m2 = 'id';
}
$j['m1'] = $m1;
$j['m2'] = $m2;
}
$j['f1'] = $f1;
if ($f2 === null) {
$f2 = 'id';
}
$j['f2'] = $f2;
$j['t'] = $join_kind ?: 'left';
$j['fa'] = $_foreign_alias;
$this->args['join'][] = $j;
return $this;
}
public function _render_join(): ?string
{
if (!isset($this->args['join'])) {
return '';
}
$joins = [];
foreach ($this->args['join'] as $j) {
$jj = '';
$jj .= $j['t'] . ' join ';
$jj .= $this->escapeIdentifierSoft($j['f1']);
if ($j['fa'] !== null) {
$jj .= ' ' . $this->escapeIdentifier($j['fa']);
}
$jj .= ' on ';
if (isset($j['expr'])) {
$jj .= $this->consume($j['expr']);
} else {
$jj .=
$this->escapeIdentifier($j['fa'] ?: $j['f1']) . '.' .
$this->escapeIdentifier($j['f2']) . ' = ' .
($j['m1'] === null ? '' : $this->escapeIdentifier($j['m1']) . '.') .
$this->escapeIdentifier($j['m2']);
}
$joins[] = $jj;
}
return ' ' . implode(' ', $joins);
}
// }}}
// {{{ where() and having() specification and rendering
/**
* Adds condition to your query.
*
* Examples:
* $q->where('id',1);
*
* By default condition implies equality. You can specify a different comparison
* operator by either including it along with the field or using 3-argument
* format:
* $q->where('id>','1');
* $q->where('id','>',1);
*
* You may use Expression as any part of the query.
* $q->where($q->expr('a=b'));
* $q->where('date>',$q->expr('now()'));
* $q->where($q->expr('length(password)'),'>',5);
*
* If you specify Query as an argument, it will be automatically
* surrounded by brackets:
* $q->where('user_id',$q->dsql()->table('users')->field('id'));
*
* To specify OR conditions:
* $q->where($q->orExpr()->where('a',1)->where('b',1));
*
* @param mixed $field Field or Expression
* @param mixed $cond Condition such as '=', '>' or 'is not'
* @param mixed $value Value. Will be quoted unless you pass expression
* @param string $kind Do not use directly. Use having()
* @param int $num_args when $kind is passed, we can't determine number of
* actual arguments, so this argument must be specified
*
* @return $this
*/
public function where($field, $cond = null, $value = null, $kind = 'where', $num_args = null)
{
// Number of passed arguments will be used to determine if arguments were specified or not
if ($num_args === null) {
$num_args = func_num_args();
}
// Array as first argument means we have to replace it with orExpr()
// remove in v2.5
if (is_array($field)) {
throw new Exception('Array input / OR conditions is no longer supported');
}
// first argument is string containing more than just a field name and no more than 2
// arguments means that we either have a string expression or embedded condition.
if ($num_args === 2 && is_string($field) && !preg_match('/^[.a-zA-Z0-9_]*$/', $field)) {
// field contains non-alphanumeric values. Look for condition
preg_match(
'/^([^ <>!=]*)([><!=]*|( *(not|is|in|like))*) *$/',
$field,
$matches
);
// matches[2] will contain the condition, but $cond will contain the value
$value = $cond;
$cond = $matches[2];
// if we couldn't clearly identify the condition, we might be dealing with
// a more complex expression. If expression is followed by another argument
// we need to add equation sign where('now()',123).
if (!$cond) {
$matches[1] = $this->expr($field);
$cond = '=';
} else {
++$num_args;
}
$field = $matches[1];
}
switch ($num_args) {
case 1:
if (is_string($field)) {
$field = $this->expr($field);
$field->wrapInParentheses = true;
} elseif (!$field->wrapInParentheses) {
$field = $this->expr('[]', [$field]);
$field->wrapInParentheses = true;
}
$this->args[$kind][] = [$field];
break;
case 2:
if (is_object($cond) && !$cond instanceof Expressionable) {
throw (new Exception('Value cannot be converted to SQL-compatible expression'))
->addMoreInfo('field', $field)
->addMoreInfo('value', $cond);
}
$this->args[$kind][] = [$field, $cond];
break;
case 3:
if (is_object($value) && !$value instanceof Expressionable) {
throw (new Exception('Value cannot be converted to SQL-compatible expression'))
->addMoreInfo('field', $field)
->addMoreInfo('cond', $cond)
->addMoreInfo('value', $value);
}
$this->args[$kind][] = [$field, $cond, $value];
break;
}
return $this;
}
/**
* Same syntax as where().
*
* @param mixed $field Field or Expression
* @param mixed $cond Condition such as '=', '>' or 'is not'
* @param mixed $value Value. Will be quoted unless you pass expression
*
* @return $this
*/
public function having($field, $cond = null, $value = null)
{
return $this->where($field, $cond, $value, 'having', func_num_args());
}
/**
* Subroutine which renders either [where] or [having].
*
* @param string $kind 'where' or 'having'
*
* @return string[]
*/
protected function _sub_render_where($kind): array
{
// will be joined for output
$ret = [];
// where() might have been called multiple times. Collect all conditions,
// then join them with AND keyword
foreach ($this->args[$kind] as $row) {
$ret[] = $this->_sub_render_condition($row);
}
return $ret;
}
protected function _sub_render_condition(array $row): string
{
if (count($row) === 3) {
[$field, $cond, $value] = $row;
} elseif (count($row) === 2) {
[$field, $cond] = $row;
} elseif (count($row) === 1) {
[$field] = $row;
} else {
throw new \InvalidArgumentException();
}
$field = $this->consume($field, self::ESCAPE_IDENTIFIER_SOFT);
if (count($row) === 1) {
// Only a single parameter was passed, so we simply include all
return $field;
}
// below are only cases when 2 or 3 arguments are passed
// if no condition defined - set default condition
if (count($row) === 2) {
$value = $cond; // @phpstan-ignore-line see https://github.com/phpstan/phpstan/issues/4173
if ($value instanceof Expressionable) {
$value = $value->getDsqlExpression($this);
}
if (is_array($value)) {
$cond = 'in';
} elseif ($value instanceof self && $value->mode === 'select') {
$cond = 'in';
} else {
$cond = '=';
}
} else {
$cond = trim(strtolower($cond)); // @phpstan-ignore-line see https://github.com/phpstan/phpstan/issues/4173
}
// below we can be sure that all 3 arguments has been passed
// special conditions (IS | IS NOT) if value is null
if ($value === null) { // @phpstan-ignore-line see https://github.com/phpstan/phpstan/issues/4173
if (in_array($cond, ['=', 'is'], true)) {
return $field . ' is null';
} elseif (in_array($cond, ['!=', '<>', 'not', 'is not'], true)) {
return $field . ' is not null';
}
}
// value should be array for such conditions
if (in_array($cond, ['in', 'not in', 'not'], true) && is_string($value)) {
$value = array_map('trim', explode(',', $value));
}
// special conditions (IN | NOT IN) if value is array
if (is_array($value)) {
$cond = in_array($cond, ['!=', '<>', 'not', 'not in'], true) ? 'not in' : 'in';
// special treatment of empty array condition
if (empty($value)) {
if ($cond === 'in') {
return '1 = 0'; // never true
}
return '1 = 1'; // always true
}
$value = '(' . implode(', ', array_map(function ($v) { return $this->escapeParam($v); }, $value)) . ')';
return $field . ' ' . $cond . ' ' . $value;
}
// if value is object, then it should be Expression or Query itself
// otherwise just escape value
$value = $this->consume($value, self::ESCAPE_PARAM);
return $field . ' ' . $cond . ' ' . $value;
}
protected function _render_where(): ?string
{
if (!isset($this->args['where'])) {
return null;
}
return ' where ' . implode(' and ', $this->_sub_render_where('where'));
}
protected function _render_orwhere(): ?string
{
if (isset($this->args['where']) && isset($this->args['having'])) {
throw new Exception('Mixing of WHERE and HAVING conditions not allowed in query expression');
}
foreach (['where', 'having'] as $kind) {
if (isset($this->args[$kind])) {
return implode(' or ', $this->_sub_render_where($kind));
}
}
return null;
}
protected function _render_andwhere(): ?string
{
if (isset($this->args['where']) && isset($this->args['having'])) {
throw new Exception('Mixing of WHERE and HAVING conditions not allowed in query expression');
}
foreach (['where', 'having'] as $kind) {
if (isset($this->args[$kind])) {
return implode(' and ', $this->_sub_render_where($kind));
}
}
return null;
}
protected function _render_having(): ?string
{
if (!isset($this->args['having'])) {
return null;
}
return ' having ' . implode(' and ', $this->_sub_render_where('having'));
}
// }}}
// {{{ group()
/**
* Implements GROUP BY functionality. Simply pass either field name
* as string or expression.
*
* @param mixed $group Group by this
*
* @return $this
*/
public function group($group)
{
// Case with comma-separated fields
if (is_string($group) && !$this->isUnescapablePattern($group) && strpos($group, ',') !== false) {
$group = explode(',', $group);
}
if (is_array($group)) {
foreach ($group as $g) {
$this->args['group'][] = $g;
}
return $this;
}
$this->args['group'][] = $group;
return $this;
}
protected function _render_group(): ?string
{
if (!isset($this->args['group'])) {
return '';
}
$g = array_map(function ($a) {
return $this->consume($a, self::ESCAPE_IDENTIFIER_SOFT);
}, $this->args['group']);
return ' group by ' . implode(', ', $g);
}
// }}}
// {{{ Set field implementation
/**
* Sets field value for INSERT or UPDATE statements.
*
* @param string|Expression|Expressionable|array $field Name of the field
* @param mixed $value Value of the field
*
* @return $this
*/
public function set($field, $value = null)
{
if (is_array($value)) {
throw (new Exception('Array values are not supported by SQL'))
->addMoreInfo('field', $field)
->addMoreInfo('value', $value);
}
if (is_array($field)) {
foreach ($field as $key => $value) {
$this->set($key, $value);
}
return $this;
}
if (is_string($field) || $field instanceof Expressionable) {
$this->args['set'][] = [$field, $value];
} else {
throw (new Exception('Field name should be string or Expressionable'))
->addMoreInfo('field', $field);
}
return $this;
}
protected function _render_set(): ?string
{
// will be joined for output
$ret = [];
if (isset($this->args['set']) && $this->args['set']) {
foreach ($this->args['set'] as [$field, $value]) {
$field = $this->consume($field, self::ESCAPE_IDENTIFIER);
$value = $this->consume($value, self::ESCAPE_PARAM);
$ret[] = $field . '=' . $value;
}
}
return implode(', ', $ret);
}
protected function _render_set_fields(): ?string
{
// will be joined for output
$ret = [];
if ($this->args['set']) {
foreach ($this->args['set'] as [$field/*, $value*/]) {
$field = $this->consume($field, self::ESCAPE_IDENTIFIER);
$ret[] = $field;
}
}
return implode(', ', $ret);
}
protected function _render_set_values(): ?string
{
// will be joined for output
$ret = [];
if ($this->args['set']) {
foreach ($this->args['set'] as [/*$field*/ , $value]) {
$value = $this->consume($value, self::ESCAPE_PARAM);
$ret[] = $value;
}
}
return implode(', ', $ret);
}
// }}}
// {{{ Option
/**
* Set options for particular mode.
*
* @param mixed $option
* @param string $mode select|insert|replace
*
* @return $this
*/
public function option($option, $mode = 'select')
{
// Case with comma-separated options
if (is_string($option) && strpos($option, ',') !== false) {
$option = explode(',', $option);
}
if (is_array($option)) {
foreach ($option as $opt) {
$this->args['option'][$mode][] = $opt;
}
return $this;
}
$this->args['option'][$mode][] = $option;
return $this;
}
protected function _render_option(): ?string
{
if (!isset($this->args['option'][$this->mode])) {
return '';
}
return ' ' . implode(' ', $this->args['option'][$this->mode]);
}
// }}}
// {{{ Query Modes
/**
* Execute select statement.
*
* @return DbalResult|\PDOStatement PDOStatement iff for DBAL 2.x
*/
public function select(): object
{
return $this->mode('select')->execute();
}
/**
* Execute insert statement.
*
* @return DbalResult|\PDOStatement PDOStatement iff for DBAL 2.x
*/
public function insert(): object
{
return $this->mode('insert')->execute();
}
/**
* Execute update statement.
*
* @return DbalResult|\PDOStatement PDOStatement iff for DBAL 2.x
*/
public function update(): object
{
return $this->mode('update')->execute();
}
/**
* Execute replace statement.
*