-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuilder.php
More file actions
2720 lines (2263 loc) · 88.4 KB
/
Builder.php
File metadata and controls
2720 lines (2263 loc) · 88.4 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
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
namespace Utopia\Query;
use Closure;
use Utopia\Query\AST\Call\Func;
use Utopia\Query\AST\Definition\Cte as CteDefinition;
use Utopia\Query\AST\Expression;
use Utopia\Query\AST\Expression\Aliased;
use Utopia\Query\AST\Expression\Between;
use Utopia\Query\AST\Expression\Binary;
use Utopia\Query\AST\Expression\In;
use Utopia\Query\AST\Expression\Unary;
use Utopia\Query\AST\JoinClause as AstJoinClause;
use Utopia\Query\AST\Literal;
use Utopia\Query\AST\OrderByItem;
use Utopia\Query\AST\Parser;
use Utopia\Query\AST\Raw;
use Utopia\Query\AST\Reference\Column;
use Utopia\Query\AST\Reference\Table;
use Utopia\Query\AST\Serializer;
use Utopia\Query\AST\Star;
use Utopia\Query\AST\Statement\Select;
use Utopia\Query\Builder\Case\Expression as CaseExpression;
use Utopia\Query\Builder\Case\Kind as CaseKind;
use Utopia\Query\Builder\Case\WhenClause;
use Utopia\Query\Builder\ColumnPredicate;
use Utopia\Query\Builder\Condition;
use Utopia\Query\Builder\CteClause;
use Utopia\Query\Builder\ExistsSubquery;
use Utopia\Query\Builder\Feature;
use Utopia\Query\Builder\JoinBuilder;
use Utopia\Query\Builder\JoinType;
use Utopia\Query\Builder\LateralJoin;
use Utopia\Query\Builder\LockMode;
use Utopia\Query\Builder\ParsedQuery;
use Utopia\Query\Builder\Statement;
use Utopia\Query\Builder\SubSelect;
use Utopia\Query\Builder\UnionClause;
use Utopia\Query\Builder\WhereInSubquery;
use Utopia\Query\Builder\WindowDefinition;
use Utopia\Query\Builder\WindowSelect;
use Utopia\Query\Exception\UnsupportedException;
use Utopia\Query\Exception\ValidationException;
use Utopia\Query\Hook\Attribute;
use Utopia\Query\Hook\Filter;
use Utopia\Query\Hook\Join\Filter as JoinFilter;
use Utopia\Query\Hook\Join\Placement;
use Utopia\Query\Tokenizer\Tokenizer;
abstract class Builder implements
Compiler,
Feature\Selects,
Feature\Aggregates,
Feature\Joins,
Feature\Unions,
Feature\CTEs,
Feature\Inserts,
Feature\Updates,
Feature\Deletes,
Feature\Hooks,
Feature\Windows
{
use Builder\Trait\Aggregates;
use Builder\Trait\CTEs;
use Builder\Trait\Deletes;
use Builder\Trait\Hooks;
use Builder\Trait\Inserts;
use Builder\Trait\Joins;
use Builder\Trait\Selects;
use Builder\Trait\Unions;
use Builder\Trait\Updates;
use Builder\Trait\Windows;
/** @var list<string> */
protected const COLUMN_PREDICATE_OPERATORS = ['=', '!=', '<>', '<', '>', '<=', '>='];
protected string $table = '';
protected string $alias = '';
/**
* @var array<Query>
*/
protected array $pendingQueries = [];
/**
* @var list<mixed>
*/
protected array $bindings = [];
/**
* @var list<UnionClause>
*/
protected array $unions = [];
/** @var list<Filter> */
protected array $filterHooks = [];
/** @var list<Attribute> */
protected array $attributeHooks = [];
/**
* Per-build memo of resolveAttribute() results keyed by raw name.
*
* Populated on first resolution, cleared at the top of build() and on
* reset(). The same attribute is resolved many times per build (SELECT,
* WHERE, GROUP BY, ORDER BY, JOIN ON, UPDATE SET) and each resolution
* iterates every registered attribute hook.
*
* @var array<string, string>
*/
protected array $resolvedAttributeCache = [];
/** @var list<JoinFilter> */
protected array $joinFilterHooks = [];
/** @var list<array<string, mixed>> */
protected array $rows = [];
/** @var array<string, string> */
protected array $rawSets = [];
/** @var array<string, list<mixed>> */
protected array $rawSetBindings = [];
protected ?LockMode $lockMode = null;
protected ?string $lockOfTable = null;
protected ?Builder $insertSelectSource = null;
/** @var list<string> */
protected array $insertSelectColumns = [];
/** @var list<CteClause> */
protected array $ctes = [];
/** @var list<Condition> */
protected array $rawSelects = [];
/** @var list<WindowSelect> */
protected array $windowSelects = [];
/** @var list<WindowDefinition> */
protected array $windowDefinitions = [];
/** @var ?array{percent: float, method: string} */
protected ?array $sample = null;
/** @var list<CaseExpression> */
protected array $cases = [];
/** @var array<string, CaseExpression> */
protected array $caseSets = [];
/** @var array<string, string> Column-specific expressions for INSERT (e.g. 'location' => 'ST_GeomFromText(?)') */
protected array $insertColumnExpressions = [];
/** @var array<string, list<mixed>> Extra bindings for insert column expressions */
protected array $insertColumnExpressionBindings = [];
protected string $insertAlias = '';
/** @var list<WhereInSubquery> */
protected array $whereInSubqueries = [];
/** @var list<SubSelect> */
protected array $subSelects = [];
protected ?SubSelect $fromSubquery = null;
protected bool $tableless = false;
/** @var list<Condition> */
protected array $rawOrders = [];
/** @var list<Condition> */
protected array $rawGroups = [];
/** @var list<Condition> */
protected array $rawHavings = [];
/** @var list<Condition> */
protected array $rawWheres = [];
/** @var list<ColumnPredicate> */
protected array $columnPredicates = [];
/** @var array<int, JoinBuilder> */
protected array $joins = [];
/** @var list<ExistsSubquery> */
protected array $existsSubqueries = [];
/** @var list<LateralJoin> */
protected array $lateralJoins = [];
/** @var list<Closure> */
protected array $beforeBuildCallbacks = [];
/** @var list<Closure(Statement): Statement> */
protected array $afterBuildCallbacks = [];
/** @var (\Closure(Statement): (array<mixed>|int))|null */
protected ?\Closure $executor = null;
protected bool $qualify = false;
/** @var array<string, true> */
protected array $aggregationAliases = [];
protected ?int $fetchCount = null;
protected bool $fetchWithTies = false;
abstract protected function quote(string $identifier): string;
/**
* Compile a random ordering expression (e.g. RAND() or rand())
*/
abstract protected function compileRandom(): string;
/**
* Compile a regex filter
*
* @param array<mixed> $values
*/
abstract protected function compileRegex(string $attribute, array $values): string;
protected function buildTableClause(): string
{
if ($this->tableless) {
return '';
}
$fromSub = $this->fromSubquery;
if ($fromSub !== null) {
$subResult = $fromSub->subquery->build();
$this->addBindings($subResult->bindings);
return 'FROM (' . $subResult->query . ') AS ' . $this->quote($fromSub->alias);
}
$sql = 'FROM ' . $this->quote($this->table);
if ($this->alias !== '') {
$sql .= ' AS ' . $this->quote($this->alias);
}
if ($this->sample !== null) {
$sql .= ' TABLESAMPLE ' . $this->sample['method'] . '(' . $this->sample['percent'] . ')';
}
return $sql;
}
/**
* Hook called after JOIN clauses and before WHERE. Override to inject
* dialect-specific clauses such as PREWHERE (ClickHouse) or ARRAY JOIN.
* Implementations must add any bindings they emit via $this->addBindings()
* at the moment their fragment is emitted so ordering is preserved.
*/
protected function buildAfterJoinsClause(ParsedQuery $grouped): string
{
return '';
}
/**
* Hook called after GROUP BY and before HAVING. Override to emit
* dialect-specific group-by modifiers (e.g. ClickHouse WITH TOTALS).
*/
protected function buildAfterGroupByClause(): string
{
return '';
}
/**
* Hook called after ORDER BY and before LIMIT. Override to emit
* dialect-specific clauses that bind between ordering and pagination
* (e.g. ClickHouse LIMIT BY).
*/
protected function buildAfterOrderByClause(): string
{
return '';
}
/**
* Hook called at the very end of the SELECT statement (just before any
* UNION suffix). Override to emit dialect-specific settings fragments
* (e.g. ClickHouse SETTINGS).
*/
protected function buildSettingsClause(): string
{
return '';
}
/**
* Compile a CASE expression to SQL, appending bindings to $this->bindings
* in the order WHEN-value, THEN-value, ..., ELSE-value.
*/
protected function compileCase(CaseExpression $case): string
{
$whens = $case->getWhens();
if ($whens === []) {
throw new ValidationException('CASE expression requires at least one WHEN clause.');
}
$sql = 'CASE';
foreach ($whens as $when) {
$sql .= ' WHEN ' . $this->compileWhenCondition($when) . ' THEN ?';
$this->addBinding($when->then);
}
if ($case->hasElse()) {
$sql .= ' ELSE ?';
$this->addBinding($case->getElse());
}
$sql .= ' END';
$alias = $case->getAlias();
if ($alias !== '') {
$sql .= ' AS ' . $this->quote($alias);
}
return $sql;
}
/**
* Compile the predicate of a single WHEN clause, adding any operand
* bindings to $this->bindings in left-to-right order.
*/
private function compileWhenCondition(WhenClause $when): string
{
switch ($when->kind) {
case CaseKind::Comparison:
if ($when->column === null || $when->operator === null) {
throw new ValidationException('Comparison WHEN clause requires column and operator.');
}
$this->addBinding($when->value);
return $this->quote($when->column) . ' ' . $when->operator->sqlOperator() . ' ?';
case CaseKind::Null:
if ($when->column === null) {
throw new ValidationException('Null WHEN clause requires column.');
}
return $this->quote($when->column) . ' IS NULL';
case CaseKind::NotNull:
if ($when->column === null) {
throw new ValidationException('NotNull WHEN clause requires column.');
}
return $this->quote($when->column) . ' IS NOT NULL';
case CaseKind::In:
if ($when->column === null) {
throw new ValidationException('In WHEN clause requires column.');
}
if ($when->values === []) {
throw new ValidationException('In WHEN clause requires at least one value.');
}
$placeholders = \implode(', ', \array_fill(0, \count($when->values), '?'));
foreach ($when->values as $value) {
$this->addBinding($value);
}
return $this->quote($when->column) . ' IN (' . $placeholders . ')';
case CaseKind::Raw:
if ($when->rawCondition === null) {
throw new ValidationException('Raw WHEN clause requires condition.');
}
foreach ($when->rawBindings as $binding) {
$this->addBinding($binding);
}
return $when->rawCondition;
}
}
#[\Override]
public function build(): Statement
{
$this->bindings = [];
$this->resolvedAttributeCache = [];
foreach ($this->beforeBuildCallbacks as $callback) {
$callback($this);
}
$this->validateTable();
$ctePrefix = $this->buildCtePrefix();
$grouped = Query::groupByType($this->pendingQueries);
$this->prepareAliasQualification($grouped);
$joinFilterWhereClauses = [];
$parts = [$this->buildSelectClause($grouped)];
$this->appendIfNotEmpty($parts, $this->buildFromClause());
$this->appendIfNotEmpty($parts, $this->buildJoinsClause($grouped, $joinFilterWhereClauses));
$this->appendIfNotEmpty($parts, $this->buildAfterJoinsClause($grouped));
$this->appendIfNotEmpty($parts, $this->buildWhereClause($grouped, $joinFilterWhereClauses));
$this->appendIfNotEmpty($parts, $this->buildGroupByClause($grouped));
$this->appendIfNotEmpty($parts, $this->buildAfterGroupByClause());
$this->appendIfNotEmpty($parts, $this->buildHavingClause($grouped));
$this->appendIfNotEmpty($parts, $this->buildWindowClause());
$this->appendIfNotEmpty($parts, $this->buildOrderByClause());
$this->appendIfNotEmpty($parts, $this->buildAfterOrderByClause());
$this->appendIfNotEmpty($parts, $this->buildLimitClause($grouped));
$this->appendIfNotEmpty($parts, $this->buildLockingClause());
$this->appendIfNotEmpty($parts, $this->buildSettingsClause());
$sql = \implode(' ', $parts);
$unionSuffix = $this->buildUnionSuffix();
if ($unionSuffix !== '') {
$sql = $this->wrapUnionMember($sql) . $unionSuffix;
}
$sql = $ctePrefix . $sql;
$result = new Statement($sql, $this->bindings, readOnly: true, executor: $this->executor);
foreach ($this->afterBuildCallbacks as $callback) {
$result = $callback($result);
}
return $result;
}
/**
* Append $fragment to $parts only when it is a non-empty string.
* Keeps build() free of repetitive `if ($fragment !== '')` guards.
*
* @param list<string> $parts
*/
private function appendIfNotEmpty(array &$parts, string $fragment): void
{
if ($fragment !== '') {
$parts[] = $fragment;
}
}
/**
* Build the optional WITH / WITH RECURSIVE prefix. Adds CTE bindings to
* $this->bindings in document order. Returns an empty string when no
* CTEs are registered.
*/
private function buildCtePrefix(): string
{
if (empty($this->ctes)) {
return '';
}
$hasRecursive = false;
$cteParts = [];
foreach ($this->ctes as $cte) {
if ($cte->recursive) {
$hasRecursive = true;
}
$this->addBindings($cte->bindings);
$cteName = $this->quote($cte->name);
if (! empty($cte->columns)) {
$cteName .= '(' . \implode(', ', \array_map(fn (string $col): string => $this->quote($col), $cte->columns)) . ')';
}
$cteParts[] = $cteName . ' AS (' . $cte->query . ')';
}
$keyword = $hasRecursive ? 'WITH RECURSIVE' : 'WITH';
return $keyword . ' ' . \implode(', ', $cteParts) . ' ';
}
/**
* Configure alias-qualification state prior to emitting SELECT. When joins
* are present and the base table has an alias, column references must be
* fully qualified — except aggregation aliases, which are captured here
* so they can be emitted bare.
*/
private function prepareAliasQualification(ParsedQuery $grouped): void
{
$this->qualify = false;
$this->aggregationAliases = [];
if (empty($grouped->joins) || $this->alias === '') {
return;
}
$this->qualify = true;
foreach ($grouped->aggregations as $agg) {
/** @var string $aggAlias */
$aggAlias = $agg->getValue('');
if ($aggAlias !== '') {
$this->aggregationAliases[$aggAlias] = true;
}
}
}
/**
* Compile the SELECT [DISTINCT] ... clause, including aggregations,
* column selections, sub-selects, raw selects, window function selects,
* and CASE selects. Always returns a non-empty fragment (falls back
* to `SELECT *`).
*/
private function buildSelectClause(ParsedQuery $grouped): string
{
$selectParts = [];
foreach ($grouped->aggregations as $agg) {
$selectParts[] = $this->compileAggregate($agg);
}
if (! empty($grouped->selections)) {
$selectParts[] = $this->compileSelect($grouped->selections[0]);
}
foreach ($this->subSelects as $subSelect) {
$subResult = $subSelect->subquery->build();
$selectParts[] = '(' . $subResult->query . ') AS ' . $this->quote($subSelect->alias);
$this->addBindings($subResult->bindings);
}
foreach ($this->rawSelects as $rawSelect) {
$selectParts[] = $rawSelect->expression;
$this->addBindings($rawSelect->bindings);
}
foreach ($this->windowSelects as $win) {
$selectParts[] = $this->compileWindowSelect($win);
}
foreach ($this->cases as $caseSelect) {
$selectParts[] = $this->compileCase($caseSelect);
}
$selectSQL = ! empty($selectParts) ? \implode(', ', $selectParts) : '*';
$selectKeyword = $grouped->distinct ? 'SELECT DISTINCT' : 'SELECT';
return $selectKeyword . ' ' . $selectSQL;
}
/**
* Compile a single window-function SELECT item (inline or named window).
*/
private function compileWindowSelect(WindowSelect $win): string
{
if ($win->windowName !== null) {
return $win->function . ' OVER ' . $this->quote($win->windowName) . ' AS ' . $this->quote($win->alias);
}
$overParts = [];
if ($win->partitionBy !== null && $win->partitionBy !== []) {
$partCols = \array_map(
fn (string $col): string => $this->resolveAndWrap($col),
$win->partitionBy
);
$overParts[] = 'PARTITION BY ' . \implode(', ', $partCols);
}
if ($win->orderBy !== null && $win->orderBy !== []) {
$overParts[] = 'ORDER BY ' . $this->compileOrderByList($win->orderBy);
}
if ($win->frame !== null) {
$overParts[] = $win->frame->toSql();
}
return $win->function . ' OVER (' . \implode(' ', $overParts) . ') AS ' . $this->quote($win->alias);
}
/**
* Compile a list of ORDER BY column tokens (prefixed with '-' for DESC)
* into a comma-separated SQL fragment.
*
* @param list<string> $orderBy
*/
private function compileOrderByList(array $orderBy): string
{
$orderCols = [];
foreach ($orderBy as $col) {
if (\str_starts_with($col, '-')) {
$orderCols[] = $this->resolveAndWrap(\substr($col, 1)) . ' DESC';
} else {
$orderCols[] = $this->resolveAndWrap($col) . ' ASC';
}
}
return \implode(', ', $orderCols);
}
/**
* Compile the FROM clause. Delegates the table/subquery portion to
* buildTableClause() so dialects can override it precisely.
*/
private function buildFromClause(): string
{
return $this->buildTableClause();
}
/**
* Compile the JOIN section, including any lateral joins. Deferred join
* filter conditions that must land in WHERE are appended to the
* $joinFilterWhereClauses out-parameter.
*
* @param list<Condition> $joinFilterWhereClauses
*/
private function buildJoinsClause(ParsedQuery $grouped, array &$joinFilterWhereClauses): string
{
$joinParts = [];
if (! empty($grouped->joins)) {
$joinQueryIndices = [];
foreach ($this->pendingQueries as $idx => $pq) {
if ($pq->getMethod()->isJoin()) {
$joinQueryIndices[] = $idx;
}
}
foreach ($grouped->joins as $joinIdx => $joinQuery) {
$pendingIdx = $joinQueryIndices[$joinIdx] ?? -1;
$joinBuilder = $this->joins[$pendingIdx] ?? null;
if ($joinBuilder !== null) {
$joinSQL = $this->compileJoinWithBuilder($joinQuery, $joinBuilder);
} else {
$joinSQL = $this->compileJoin($joinQuery);
}
$joinTable = $joinQuery->getAttribute();
$joinType = match ($joinQuery->getMethod()) {
Method::Join => JoinType::Inner,
Method::LeftJoin => JoinType::Left,
Method::RightJoin => JoinType::Right,
Method::CrossJoin => JoinType::Cross,
Method::FullOuterJoin => JoinType::FullOuter,
Method::NaturalJoin => JoinType::Natural,
default => throw new UnsupportedException('Unsupported join method: ' . $joinQuery->getMethod()->value),
};
$isCrossJoin = $joinType === JoinType::Cross || $joinType === JoinType::Natural;
$joinValues = $joinQuery->getValues();
if ($isCrossJoin) {
/** @var string $joinAlias */
$joinAlias = $joinValues[0] ?? '';
} else {
/** @var string $joinAlias */
$joinAlias = $joinValues[3] ?? '';
}
$effectiveJoinTable = $joinAlias !== '' ? $joinAlias : $joinTable;
foreach ($this->joinFilterHooks as $hook) {
$result = $hook->filterJoin($effectiveJoinTable, $joinType);
if ($result === null) {
continue;
}
$placement = $this->resolveJoinFilterPlacement($result->placement, $isCrossJoin);
if ($placement === Placement::On) {
$joinSQL .= ' AND ' . $result->condition->expression;
$this->addBindings($result->condition->bindings);
} else {
$joinFilterWhereClauses[] = $result->condition;
}
}
$joinParts[] = $joinSQL;
}
}
foreach ($this->lateralJoins as $lateral) {
$subResult = $lateral->subquery->build();
$this->addBindings($subResult->bindings);
$joinKeyword = match ($lateral->type) {
JoinType::Left => 'LEFT JOIN',
default => 'JOIN',
};
$joinParts[] = $joinKeyword . ' LATERAL (' . $subResult->query . ') AS ' . $this->quote($lateral->alias) . ' ON true';
}
return \implode(' ', $joinParts);
}
/**
* Compile the WHERE clause from query filters, filter hooks, deferred
* join-filter conditions, WHERE IN / NOT IN subqueries, EXISTS
* subqueries, and cursor pagination.
*
* @param list<Condition> $joinFilterWhereClauses
*/
private function buildWhereClause(ParsedQuery $grouped, array $joinFilterWhereClauses): string
{
$whereClauses = [];
foreach ($grouped->filters as $filter) {
$whereClauses[] = $this->compileFilter($filter);
}
foreach ($this->filterHooks as $hook) {
$condition = $hook->filter($this->alias ?: $this->table);
$whereClauses[] = $condition->expression;
$this->addBindings($condition->bindings);
}
foreach ($joinFilterWhereClauses as $condition) {
$whereClauses[] = $condition->expression;
$this->addBindings($condition->bindings);
}
foreach ($this->whereInSubqueries as $sub) {
$subResult = $sub->subquery->build();
$prefix = $sub->not ? 'NOT IN' : 'IN';
$whereClauses[] = $this->resolveAndWrap($sub->column) . ' ' . $prefix . ' (' . $subResult->query . ')';
$this->addBindings($subResult->bindings);
}
foreach ($this->existsSubqueries as $sub) {
$subResult = $sub->subquery->build();
$prefix = $sub->not ? 'NOT EXISTS' : 'EXISTS';
$whereClauses[] = $prefix . ' (' . $subResult->query . ')';
$this->addBindings($subResult->bindings);
}
if ($grouped->cursor !== null && $grouped->cursorDirection !== null) {
$cursorQueries = Query::getCursorQueries($this->pendingQueries, false);
if (! empty($cursorQueries)) {
$cursorSQL = $this->compileCursor($cursorQueries[0]);
if ($cursorSQL !== '') {
$whereClauses[] = $cursorSQL;
}
}
}
foreach ($this->rawWheres as $rawWhere) {
$whereClauses[] = $rawWhere->expression;
$this->addBindings($rawWhere->bindings);
}
foreach ($this->columnPredicates as $predicate) {
$whereClauses[] = $this->resolveAndWrap($predicate->left)
. ' ' . $predicate->operator . ' '
. $this->resolveAndWrap($predicate->right);
}
if (empty($whereClauses)) {
return '';
}
return 'WHERE ' . \implode(' AND ', $whereClauses);
}
/**
* Compile the GROUP BY clause, including any raw group expressions.
*/
private function buildGroupByClause(ParsedQuery $grouped): string
{
$groupByParts = [];
if (! empty($grouped->groupBy)) {
foreach ($grouped->groupBy as $col) {
$groupByParts[] = $this->resolveAndWrap($col);
}
}
foreach ($this->rawGroups as $rawGroup) {
$groupByParts[] = $rawGroup->expression;
$this->addBindings($rawGroup->bindings);
}
if (empty($groupByParts)) {
return '';
}
return 'GROUP BY ' . \implode(', ', $groupByParts);
}
/**
* Compile the HAVING clause, resolving aggregation aliases to their
* underlying expressions so filters against alias names work portably.
*/
private function buildHavingClause(ParsedQuery $grouped): string
{
$aliasToExpr = $this->buildAggregationAliasMap($grouped);
$havingClauses = [];
if (! empty($grouped->having)) {
foreach ($grouped->having as $havingQuery) {
foreach ($havingQuery->getValues() as $subQuery) {
/** @var Query $subQuery */
$attr = $subQuery->getAttribute();
if (isset($aliasToExpr[$attr])) {
$havingClauses[] = $this->compileHavingCondition($subQuery, $aliasToExpr[$attr]);
} else {
$havingClauses[] = $this->compileFilter($subQuery);
}
}
}
}
foreach ($this->rawHavings as $rawHaving) {
$havingClauses[] = $rawHaving->expression;
$this->addBindings($rawHaving->bindings);
}
if (empty($havingClauses)) {
return '';
}
return 'HAVING ' . \implode(' AND ', $havingClauses);
}
/**
* Build a map of aggregation alias -> compiled aggregate expression so
* HAVING can refer to aliases portably across dialects that don't allow
* SELECT-list aliases in HAVING.
*
* @return array<string, string>
*/
private function buildAggregationAliasMap(ParsedQuery $grouped): array
{
$aliasToExpr = [];
foreach ($grouped->aggregations as $agg) {
/** @var string $alias */
$alias = $agg->getValue('');
if ($alias === '') {
continue;
}
$method = $agg->getMethod();
$attr = $agg->getAttribute();
$col = match (true) {
$attr === '*', $attr === '' => '*',
\is_numeric($attr) => $attr,
default => $this->resolveAndWrap($attr),
};
if ($method === Method::CountDistinct) {
$aliasToExpr[$alias] = 'COUNT(DISTINCT ' . $col . ')';
continue;
}
$func = $method->sqlFunction() ?? $method->value;
$aliasToExpr[$alias] = $func . '(' . $col . ')';
}
return $aliasToExpr;
}
/**
* Compile the named-window (WINDOW w AS (...)) clause.
*/
private function buildWindowClause(): string
{
if (empty($this->windowDefinitions)) {
return '';
}
$windowParts = [];
foreach ($this->windowDefinitions as $winDef) {
$overParts = [];
if ($winDef->partitionBy !== null && $winDef->partitionBy !== []) {
$partCols = \array_map(fn (string $col): string => $this->resolveAndWrap($col), $winDef->partitionBy);
$overParts[] = 'PARTITION BY ' . \implode(', ', $partCols);
}
if ($winDef->orderBy !== null && $winDef->orderBy !== []) {
$overParts[] = 'ORDER BY ' . $this->compileOrderByList($winDef->orderBy);
}
if ($winDef->frame !== null) {
$overParts[] = $winDef->frame->toSql();
}
$windowParts[] = $this->quote($winDef->name) . ' AS (' . \implode(' ', $overParts) . ')';
}
return 'WINDOW ' . \implode(', ', $windowParts);
}
/**
* Compile the ORDER BY clause, including vector-distance ordering, raw
* order expressions, and ordinary ORDER ASC/DESC/RANDOM queries.
*/
private function buildOrderByClause(): string
{
$orderClauses = [];
$vectorOrderExpr = $this->compileVectorOrderExpr();
if ($vectorOrderExpr !== null) {
$orderClauses[] = $vectorOrderExpr->expression;
$this->addBindings($vectorOrderExpr->bindings);
}
foreach ($this->rawOrders as $rawOrder) {
$orderClauses[] = $rawOrder->expression;
$this->addBindings($rawOrder->bindings);
}
$orderQueries = Query::getByType($this->pendingQueries, [
Method::OrderAsc,
Method::OrderDesc,
Method::OrderRandom,
], false);
foreach ($orderQueries as $orderQuery) {
$orderClauses[] = $this->compileOrder($orderQuery);
}
if (empty($orderClauses)) {
return '';
}
return 'ORDER BY ' . \implode(', ', $orderClauses);
}
/**
* Compile the LIMIT / OFFSET / FETCH FIRST pagination tail. Emitted as
* a single space-joined fragment so bindings are added in document order.
*/
private function buildLimitClause(ParsedQuery $grouped): string
{
$limitParts = [];
if ($grouped->limit !== null) {
$limitParts[] = 'LIMIT ?';
$this->addBinding($grouped->limit);
}
if ($this->shouldEmitOffset($grouped->offset, $grouped->limit)) {
$limitParts[] = 'OFFSET ?';
$this->addBinding($grouped->offset);
}
if ($this->fetchCount !== null) {
$this->addBinding($this->fetchCount);
$limitParts[] = $this->fetchWithTies
? 'FETCH FIRST ? ROWS WITH TIES'
: 'FETCH FIRST ? ROWS ONLY';
}
return \implode(' ', $limitParts);
}
/**
* Compile the locking clause (FOR UPDATE / FOR SHARE / ...), optionally
* scoped with OF <table>.
*/
private function buildLockingClause(): string
{
if ($this->lockMode === null) {
return '';
}
$lockSql = $this->lockMode->toSql();
if ($this->lockOfTable !== null) {
$lockSql .= ' OF ' . $this->quote($this->lockOfTable);
}
return $lockSql;
}
/**
* Compile the trailing UNION chain. Returns the suffix to concatenate
* after the parenthesized primary query (including the leading space),
* or an empty string when no unions are registered.
*/
private function buildUnionSuffix(): string
{
if (empty($this->unions)) {
return '';
}
$suffix = '';
foreach ($this->unions as $union) {
$suffix .= ' ' . $union->type->value . ' ' . $this->wrapUnionMember($union->query);
$this->addBindings($union->bindings);
}
return $suffix;
}
/**
* Wrap a compound-SELECT member for inclusion in a UNION chain. The
* default wraps each arm in parentheses, matching the shape most
* dialects expect. Override in dialects whose parsers reject the
* parenthesised form (e.g. SQLite).
*/
protected function wrapUnionMember(string $sql): string
{