Repository navigation
Expand file tree
/
Copy pathopt_qualify_columns.go
More file actions
1481 lines (1277 loc) · 43.3 KB
/
Copy pathopt_qualify_columns.go
File metadata and controls
1481 lines (1277 loc) · 43.3 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
package sqlengine
import (
"fmt"
"regexp"
"strconv"
"strings"
)
// Port of sqlglot/optimizer/qualify_columns.py (plus simplify_parens from simplify.py).
// QualifyColumns mirrors qualify_columns(expression, schema, expand_alias_refs, expand_stars,
// infer_schema, allow_partial_qualification, dialect).
//
// It rewrites the AST to have fully qualified columns. inferSchema TriNone means "infer the schema
// iff it is empty". A nil schema is replaced by an empty MappingSchema for d (ensure_schema); d is
// otherwise unused, like in Python (the schema dialect drives the qualification).
//
// Notes:
// - Currently only handles a single PIVOT or UNPIVOT operator
func QualifyColumns(expression *Expr, schema *MappingSchema, expandAliasRefs, expandStars bool, inferSchema Tri, allowPartialQualification bool, d *Dialect) *Expr {
if schema == nil {
schema = NewMappingSchema(nil, nil, d, true, nil)
}
// TypeAnnotator(schema) is created lazily: it is stateless until first used.
var annotator *TypeAnnotator
getAnnotator := func() *TypeAnnotator {
if annotator == nil {
annotator = newTypeAnnotator(schema, nil, nil, nil, true)
}
return annotator
}
infer := inferSchema == TriTrue
if inferSchema == TriNone {
infer = schema.Empty()
}
dialect := schema.Dialect()
if dialect == nil {
dialect = prototype("")
}
pseudocolumns := dialect.S.PSEUDOCOLUMNS
for _, scope := range TraverseScope(expression) {
if dialect.S.PREFER_CTE_ALIAS_COLUMN {
PushdownCTEAliasColumns(scope)
}
scopeExpression := scope.Expression
isSelect := scopeExpression.IsA(KSelect)
qcSeparatePseudocolumns(scope, pseudocolumns)
resolver := NewResolver(scope, schema, infer)
qcPopTableColumnAliases(scope.CTEs())
qcPopTableColumnAliases(scope.DerivedTables())
usingColumnTables := qcExpandUsing(scope, resolver)
if (schema.Empty() || dialect.S.FORCE_EARLY_ALIAS_REF_EXPANSION) && expandAliasRefs {
qcExpandAliasRefs(scope, resolver, dialect, dialect.S.EXPAND_ONLY_GROUP_ALIAS_REF)
}
qcConvertColumnsToDots(scope, resolver)
qcQualifyColumns(scope, resolver, allowPartialQualification)
if !schema.Empty() && expandAliasRefs {
qcExpandAliasRefs(scope, resolver, dialect, false)
}
if isSelect {
if expandStars {
qcExpandStars(scope, resolver, usingColumnTables, pseudocolumns, getAnnotator)
}
QualifyOutputsScope(scope, dialect)
}
qcExpandGroupBy(scope, dialect)
// DISTINCT ON and ORDER BY follow the same rules (tested in DuckDB, Postgres, ClickHouse)
// https://www.postgresql.org/docs/current/sql-select.html#SQL-DISTINCT
qcExpandOrderByAndDistinctOn(scope, resolver)
if dialect.S.ANNOTATE_ALL_SCOPES {
getAnnotator().annotateScope(scope)
}
}
return expression
}
// ValidateQualifyColumns mirrors validate_qualify_columns(expression, sql): it raises an
// OptimizeError if any columns aren't qualified. sql "" means None.
func ValidateQualifyColumns(expression *Expr, sql string) *Expr {
var allUnqualifiedColumns []*Expr
for _, scope := range TraverseScope(expression) {
if scope.Expression.IsA(KSelect) {
unqualifiedColumns := scope.UnqualifiedColumns()
if len(scope.ExternalColumns()) > 0 && !scope.IsCorrelatedSubquery() && len(scope.Pivots()) == 0 {
column := scope.ExternalColumns()[0]
forTable := ""
if column.TableName() != "" {
forTable = fmt.Sprintf(" for table: '%s'", column.TableName())
}
line, col, start, end := qcPositions(column.This())
errorMsg := fmt.Sprintf("Column '%s' could not be resolved%s.", column.Name(), forTable)
if truthy(line) && truthy(col) {
errorMsg += fmt.Sprintf(" Line: %v, Col: %v", line, col)
}
if sql != "" && start != nil && end != nil {
formattedSQL := qcHighlight(sql, start, end)
errorMsg += "\n " + formattedSQL
}
panic(&OptimizeError{Msg: errorMsg})
}
allUnqualifiedColumns = append(allUnqualifiedColumns, unqualifiedColumns...)
}
}
if len(allUnqualifiedColumns) > 0 {
firstColumn := allUnqualifiedColumns[0]
line, col, start, end := qcPositions(firstColumn.This())
errorMsg := fmt.Sprintf("Ambiguous column '%s'", firstColumn.Name())
if truthy(line) && truthy(col) {
errorMsg += fmt.Sprintf(" (Line: %v, Col: %v)", line, col)
}
if sql != "" && start != nil && end != nil {
formattedSQL := qcHighlight(sql, start, end)
errorMsg += "\n " + formattedSQL
}
panic(&OptimizeError{Msg: errorMsg})
}
return expression
}
// qcPositions reads the line/col/start/end position metadata of a node (nil when absent).
func qcPositions(e *Expr) (line, col, start, end any) {
if e == nil {
return nil, nil, nil, nil
}
return e.MetaGet("line"), e.MetaGet("col"), e.MetaGet("start"), e.MetaGet("end")
}
// qcHighlight mirrors highlight_sql(sql, [(start, end)])[0].
func qcHighlight(sql string, start, end any) string {
s, _ := start.(int)
e, _ := end.(int)
formatted, _, _, _ := highlightSQL([]rune(sql), [][2]int{{s, e}}, errorMessageContextDefault)
return formatted
}
func qcSeparatePseudocolumns(scope *Scope, pseudocolumns StrSet) {
if len(pseudocolumns) == 0 {
return
}
hasPseudocolumns := false
scopeExpression := scope.Expression
for _, column := range scope.Columns() {
name := pyUpper(column.Name())
if !pseudocolumns.Has(name) {
continue
}
if name != "LEVEL" || (scopeExpression.IsA(KSelect) && scopeExpression.ArgB("connect")) {
kv := []any{}
for _, k := range column.ArgKeys() {
kv = append(kv, k, column.Arg(k))
}
column.Replace(New(KPseudocolumn, kv...))
hasPseudocolumns = true
}
}
if hasPseudocolumns {
scope.ClearCache()
}
}
// qcPopTableColumnAliases mirrors _pop_table_column_aliases: remove table column aliases.
//
// For example, `col1` and `col2` will be dropped in SELECT ... FROM (SELECT ...) AS foo(col1, col2).
func qcPopTableColumnAliases(derivedTables []*Expr) {
for _, derivedTable := range derivedTables {
if derivedTable.Parent().IsA(KWith) && derivedTable.Parent().ArgB("recursive") {
continue
}
if tableAlias := derivedTable.ArgE("alias"); tableAlias != nil {
tableAlias.Set("columns", nil)
}
}
}
// usingColumnTables mirrors the dict[str, dict[str, None]] returned by _expand_using: automatically
// joined column names mapped to an ordered set of source names.
type usingColumnTables = omap[*omap[struct{}]]
func qcExpandUsing(scope *Scope, resolver *Resolver) *usingColumnTables {
columns := newOMap[string]()
updateSourceColumns := func(sourceName string) {
for _, columnName := range resolver.GetSourceColumns(sourceName, false) {
if !columns.Has(columnName) {
columns.Set(columnName, sourceName)
}
}
}
var joins []*Expr
for j := range scope.FindAll(KJoin) {
joins = append(joins, j)
}
if len(joins) == 0 {
return newOMap[*omap[struct{}]]()
}
names := newStrSet()
var namesOrdered []string
for _, join := range joins {
if n := join.AliasOrName(); !names.Has(n) {
names.Add(n)
namesOrdered = append(namesOrdered, n)
}
}
var ordered []string
for _, key := range scope.SelectedSources().Keys() {
if !names.Has(key) {
ordered = append(ordered, key)
}
}
if len(names) > 0 && len(ordered) == 0 {
reprs := make([]string, len(namesOrdered))
for i, n := range namesOrdered {
reprs[i] = pyRepr(n)
}
panic(&OptimizeError{Msg: fmt.Sprintf("Joins {%s} missing source table %s", strings.Join(reprs, ", "), chunkFPyStr(scope.Expression))})
}
// Mapping of automatically joined column names to an ordered set of source names (dict).
columnTables := newOMap[*omap[struct{}]]()
anyUsing := false
for _, join := range joins {
if join.ArgB("using") || join.MethodText() == "NATURAL" {
anyUsing = true
break
}
}
if !anyUsing {
return columnTables
}
for _, sourceName := range ordered {
updateSourceColumns(sourceName)
}
for i, join := range joins {
sourceTable := ordered[len(ordered)-1]
if sourceTable != "" {
updateSourceColumns(sourceTable)
}
joinTable := join.AliasOrName()
ordered = append(ordered, joinTable)
joinColumns := resolver.GetSourceColumns(joinTable, false)
usingArg := join.Arg("using")
using := join.ArgL("using")
if usingArg == nil && join.MethodText() == "NATURAL" {
// A NATURAL JOIN is a USING join over the columns common to both sides; when
// those can't be determined (unknown schema, no common columns), NATURAL stays
if columns.Len() > 0 && !columns.Has("*") && len(joinColumns) > 0 && !containsStr(joinColumns, "*") {
using = nil
for _, columnName := range columns.Keys() {
if containsStr(joinColumns, columnName) {
using = append(using, ToIdentifier(columnName, nil))
}
}
if len(using) > 0 {
join.Set("method", nil)
}
}
}
if len(using) == 0 {
continue
}
var conditions []*Expr
usingIdentifierCount := len(using)
isSemiOrAntiJoin := join.IsSemiOrAntiJoin()
for _, identifierExpr := range using {
identifier := identifierExpr.Name()
table, _ := columns.Get(identifier)
if table == "" || !containsStr(joinColumns, identifier) {
if (columns.Len() > 0 && !columns.Has("*")) && len(joinColumns) > 0 {
panic(&OptimizeError{Msg: "Cannot automatically join: " + identifier})
}
}
if table == "" {
table = sourceTable
}
var lhs *Expr
if i == 0 || usingIdentifierCount == 1 {
lhs = ColumnExpr(identifier, table, nil, nil, nil, nil, true)
} else {
var coalesceColumns []*Expr
for _, t := range ordered[:len(ordered)-1] {
if containsStr(resolver.GetSourceColumns(t, false), identifier) {
coalesceColumns = append(coalesceColumns, ColumnExpr(identifier, t, nil, nil, nil, nil, true))
}
}
if len(coalesceColumns) > 1 {
lhs = qcCoalesce(coalesceColumns)
} else {
lhs = ColumnExpr(identifier, table, nil, nil, nil, nil, true)
}
}
conditions = append(conditions, qcEQ(lhs, ColumnExpr(identifier, joinTable, nil, nil, nil, nil, true)))
// Set all values in the dict to None, because we only care about the key ordering
tables, ok := columnTables.Get(identifier)
if !ok {
tables = newOMap[struct{}]()
columnTables.Set(identifier, tables)
}
// Do not update the dict if this was a SEMI/ANTI join in
// order to avoid generating COALESCE columns for this join pair
if !isSemiOrAntiJoin {
if !tables.Has(table) {
tables.Set(table, struct{}{})
}
if !tables.Has(joinTable) {
tables.Set(joinTable, struct{}{})
}
}
}
join.Set("using", nil)
join.Set("on", AndExprOpts(conditions, false, true))
}
if columnTables.Len() > 0 {
for _, column := range scope.Columns() {
if column.TableName() == "" && columnTables.Has(column.Name()) {
tables, _ := columnTables.Get(column.Name())
var coalesceArgs []*Expr
for _, table := range tables.Keys() {
coalesceArgs = append(coalesceArgs, ColumnExpr(column.Name(), table, nil, nil, nil, nil, true))
}
replacement := qcCoalesce(coalesceArgs)
if column.Parent().IsA(KSelect) {
// Ensure the USING column keeps its name if it's projected
replacement = AliasExpr(replacement, column.Name(), nil, false)
} else if column.Parent().IsA(KStruct) {
// Ensure the USING column keeps its name if it's an anonymous STRUCT field
replacement = New(KPropertyEQ, "this", ToIdentifier(column.Name(), nil), "expression", replacement)
}
scope.Replace(column, replacement)
}
}
}
return columnTables
}
// qcCoalesce mirrors exp.func("coalesce", *args) (base dialect parser: build_coalesce).
func qcCoalesce(args []*Expr) *Expr {
converted := make([]*Expr, 0, len(args))
for _, a := range args {
converted = append(converted, a.Copy())
}
var function *Expr
if len(converted) > 0 {
function = New(KCoalesce, "this", converted[0], "expressions", converted[1:], "is_nvl", nil, "is_null", nil)
} else {
function = New(KCoalesce)
}
for _, msg := range function.ErrorMessages(converted) {
panic(&ValueError{Msg: msg})
}
return function
}
// qcEQ mirrors this.eq(other) (Expr._binop(EQ, other)).
func qcEQ(this, other *Expr) *Expr {
this = this.Copy()
other = other.Copy()
if !this.IsA(KEQ) && !other.IsA(KEQ) {
this = wrapIfKind(this, KBinary)
other = wrapIfKind(other, KBinary)
}
return New(KEQ, "this", this, "expression", other)
}
type qcAliasRef struct {
expr *Expr
index int
}
// qcExpandAliasRefs mirrors _expand_alias_refs: expand references to aliases.
//
// Example:
//
// SELECT y.foo AS bar, bar * 2 AS baz FROM y
// => SELECT y.foo AS bar, y.foo * 2 AS baz FROM y
func qcExpandAliasRefs(scope *Scope, resolver *Resolver, dialect *Dialect, expandOnlyGroupby bool) {
expression := scope.Expression
if !expression.IsA(KSelect) || dialect.S.DISABLES_ALIAS_REF_EXPANSION {
return
}
aliasToExpression := map[string]qcAliasRef{}
projections := newStrSet()
for _, s := range expression.Selects() {
projections.Add(s.AliasOrName())
}
replaced := false
replaceColumns := func(node *Expr, resolveTable bool, literalIndex bool) {
isGroupBy := node.IsA(KGroup)
isHaving := node.IsA(KHaving)
isQualify := node.IsA(KQualify)
if node == nil || (expandOnlyGroupby && !isGroupBy) {
return
}
for column := range WalkInScope(node, func(n *Expr) bool { return n.IsStar() }) {
if !column.IsA(KColumn) {
continue
}
// BigQuery's GROUP BY allows alias expansion only for standalone names, e.g:
// SELECT FUNC(col) AS col FROM t GROUP BY col --> Can be expanded
// SELECT FUNC(col) AS col FROM t GROUP BY FUNC(col) --> Shouldn't be expanded, will result to FUNC(FUNC(col))
// This not required for the HAVING clause as it can evaluate expressions using both the alias & the table columns
if expandOnlyGroupby && isGroupBy && column.Parent() != node {
continue
}
skipReplace := false
var table *Expr
if resolveTable && column.TableName() == "" {
table = resolver.GetTableByName(column.Name())
}
ref, hasAlias := aliasToExpression[column.Name()]
aliasExpr, i := ref.expr, ref.index
if !hasAlias {
aliasExpr, i = nil, 1
}
if aliasExpr != nil {
skipReplace = aliasExpr.Find(KAggFunc) != nil &&
column.FindAncestor(KAggFunc) != nil &&
!column.FindAncestor(KWindow, KSelect).IsA(KWindow)
// BigQuery's having clause gets confused if an alias matches a source.
// SELECT x.a, max(x.b) as x FROM x GROUP BY 1 HAVING x > 1;
// If "HAVING x" is expanded to "HAVING max(x.b)", BQ would blindly replace the "x" reference with the projection MAX(x.b)
// i.e HAVING MAX(MAX(x.b).b), resulting in the error: "Aggregations of aggregations are not allowed"
if (isHaving || isQualify) && dialect.S.PROJECTION_ALIASES_SHADOW_SOURCE_NAMES {
if !skipReplace {
for c := range aliasExpr.FindAll(KColumn) {
if projections.Has(c.Parts()[0].Name()) {
skipReplace = true
break
}
}
}
}
} else if dialect.S.PROJECTION_ALIASES_SHADOW_SOURCE_NAMES && (isGroupBy || isHaving || isQualify) {
columnTable := column.TableName()
if table != nil {
columnTable = table.Name()
}
if projections.Has(columnTable) {
// BigQuery's GROUP BY and HAVING clauses get confused if the column name
// matches a source name and a projection. For instance:
// SELECT id, ARRAY_AGG(col) AS custom_fields FROM custom_fields GROUP BY id HAVING id >= 1
// We should not qualify "id" with "custom_fields" in either clause, since the aggregation shadows the actual table
// and we'd get the error: "Column custom_fields contains an aggregation function, which is not allowed in GROUP BY clause"
column.Replace(ToIdentifier(column.Name(), nil))
replaced = true
return
}
}
if table != nil && (aliasExpr == nil || skipReplace) {
column.Set("table", table)
} else if column.TableName() == "" && aliasExpr != nil && !skipReplace {
if (aliasExpr.IsA(KLiteral) || aliasExpr.IsNumber()) && (literalIndex || resolveTable) {
if literalIndex {
column.Replace(LiteralInt(i))
replaced = true
}
} else {
replaced = true
column = column.Replace(ParenExpr(aliasExpr, true))
simplified := SimplifyParens(column, dialect)
if simplified != column {
column.Replace(simplified)
}
}
}
}
}
for i, projection := range expression.Selects() {
replaceColumns(projection, false, false)
if projection.IsA(KAlias) {
aliasToExpression[projection.Alias()] = qcAliasRef{projection.This(), i + 1}
}
}
childScope := scope
parentScope := scope
onRightSubTree := false
for parentScope != nil && !parentScope.IsCTE() {
childScope = parentScope
parentScope = parentScope.Parent
if parentScope != nil {
if parentScope.Expression.IsA(KUnion) {
// Access the arg directly instead of the right property, because set operation
// operands aren't guaranteed to be Query nodes, e.g. SELECT 1 UNION ALL VALUES (2).
// Unnest to see through parenthesized operands, whose scope is the inner query
onRightSubTree = unnestMethod(parentScope.Expression.Expression()) == childScope.Expression
}
}
}
// We shouldn't expand aliases if they match the recursive CTE's columns
// and we are in the recursive part (right sub tree) of the CTE
if parentScope != nil && onRightSubTree {
if cte := parentScope.Expression.Parent(); cte != nil {
with := cte.FindAncestor(KWith)
if with != nil && with.ArgB("recursive") {
recursiveColumns := cte.ArgE("alias").ArgL("columns")
if len(recursiveColumns) == 0 {
recursiveColumns = cte.This().Selects()
}
for _, recursiveCTEColumn := range recursiveColumns {
delete(aliasToExpression, recursiveCTEColumn.OutputName())
}
}
}
}
replaceColumns(expression.ArgE("where"), false, false)
replaceColumns(expression.ArgE("group"), false, true)
replaceColumns(expression.ArgE("having"), true, false)
replaceColumns(expression.ArgE("qualify"), true, false)
if dialect.S.SUPPORTS_ALIAS_REFS_IN_JOIN_CONDITIONS {
for _, join := range expression.ArgL("joins") {
replaceColumns(join, false, false)
}
}
if replaced {
scope.ClearCache()
}
}
func qcExpandGroupBy(scope *Scope, dialect *Dialect) {
expression := scope.Expression
group := expression.ArgE("group")
if group == nil {
return
}
group.Set("expressions", qcExpandPositionalReferences(scope, group.Expressions(), dialect, false))
expression.Set("group", group)
}
func qcExpandOrderByAndDistinctOn(scope *Scope, resolver *Resolver) {
expression := scope.Expression
if !expression.IsA(KSelectable) {
return
}
for _, modifierKey := range []string{"order", "distinct"} {
modifier := expression.ArgE(modifierKey)
if modifier.IsA(KDistinct) {
modifier = modifier.ArgE("on")
}
if modifier == nil {
continue
}
modifierExpressions := modifier.Expressions()
if modifierKey == "order" {
thisList := make([]*Expr, len(modifierExpressions))
for i, ordered := range modifierExpressions {
thisList[i] = ordered.This()
}
modifierExpressions = thisList
}
expandedList := qcExpandPositionalReferences(scope, modifierExpressions, resolver.dialect, true)
for i := 0; i < len(modifierExpressions) && i < len(expandedList); i++ {
original, expanded := modifierExpressions[i], expandedList[i]
for agg := range original.FindAll(KAggFunc) {
for col := range agg.FindAll(KColumn) {
if col.TableName() == "" {
col.Set("table", resolver.GetTableByName(col.Name()))
}
}
}
original.Replace(expanded)
}
if expression.ArgB("group") {
type selectEntry struct{ key, value *Expr }
var selects []selectEntry
for _, s := range expression.Selects() {
selects = append(selects, selectEntry{s.This(), ColumnExpr(s.AliasOrName(), nil, nil, nil, nil, nil, true)})
}
lookup := func(node *Expr) *Expr {
// dict semantics: the value of the last entry whose key equals node
for j := len(selects) - 1; j >= 0; j-- {
if selects[j].key != nil && selects[j].key.Equal(node) {
return selects[j].value
}
}
return node
}
for _, node := range modifierExpressions {
if node.IsInt() {
node.Replace(ToIdentifier(qcSelectByPos(expression, node).Alias(), nil))
} else {
node.Replace(lookup(node))
}
}
}
}
}
func qcExpandPositionalReferences(scope *Scope, expressions []*Expr, dialect *Dialect, alias bool) []*Expr {
newNodes := []*Expr{}
var ambiguousProjections StrSet
expression := scope.Expression
if !expression.IsA(KSelectable) {
return newNodes
}
for _, node := range expressions {
if node.IsInt() && node.IsA(KLiteral) {
sel := qcSelectByPos(expression, node)
if alias {
newNodes = append(newNodes, ColumnExpr(sel.ArgE("alias").Copy(), nil, nil, nil, nil, nil, true))
} else {
selectExpr := sel.This()
ambiguous := false
if dialect.S.PROJECTION_ALIASES_SHADOW_SOURCE_NAMES {
if ambiguousProjections == nil {
// When a projection name is also a source name and it is referenced in the
// GROUP BY clause, BQ can't understand what the identifier corresponds to
ambiguousProjections = newStrSet()
for _, s := range expression.Selects() {
if scope.SelectedSources().Has(s.AliasOrName()) {
ambiguousProjections.Add(s.AliasOrName())
}
}
}
for column := range selectExpr.FindAll(KColumn) {
if ambiguousProjections.Has(column.Parts()[0].Name()) {
ambiguous = true
break
}
}
}
if selectExpr.IsA(KLiteral, KBoolean, KNull) ||
selectExpr.IsNumber() ||
selectExpr.Find(KExplode, KUnnest) != nil ||
ambiguous {
newNodes = append(newNodes, node)
} else {
newNodes = append(newNodes, selectExpr.Copy())
}
}
} else {
newNodes = append(newNodes, node)
}
}
return newNodes
}
// qcSelectByPos mirrors _select_by_pos (Python list indexing semantics, including negative indexes).
func qcSelectByPos(expression *Expr, node *Expr) *Expr {
selects := expression.Selects()
n, err := strconv.Atoi(strings.ReplaceAll(pyStrip(node.ThisS()), "_", ""))
idx := n - 1
if idx < 0 {
idx += len(selects)
}
if err != nil || idx < 0 || idx >= len(selects) {
panic(&OptimizeError{Msg: "Unknown output column: " + node.Name()})
}
return chunkFAssertIs(selects[idx], KAlias)
}
// qcConvertColumnsToDots mirrors _convert_columns_to_dots.
//
// Converts `Column` instances that represent STRUCT or JSON field lookup into chained `Dots`.
//
// These lookups may be parsed as columns (e.g. "col"."field"."field2"), but they need to be
// normalized to `Dot(Dot(...(<table>.<column>, field1), field2, ...))` to be qualified properly.
func qcConvertColumnsToDots(scope *Scope, resolver *Resolver) {
converted := false
all := append(append([]*Expr{}, scope.Columns()...), scope.Stars()...)
for _, column := range all {
if column.IsA(KDot) {
continue
}
columnTableName := column.TableName()
meta := column.Meta()
dotParts, _ := meta["dot_parts"].([]string)
delete(meta, "dot_parts")
if columnTableName != "" &&
!scope.SelectedSources().Has(columnTableName) &&
(scope.Parent == nil ||
!scope.Parent.Sources.Has(columnTableName) ||
!scope.IsCorrelatedSubquery()) {
parts := column.Parts()
root, parts := parts[0], parts[1:]
var columnTable *Expr
var wasQualified bool
if root.IsA(KIdentifier) && scope.SelectedSources().Has(root.Name()) {
// The struct is already qualified, but we still need to change the AST
columnTable = root
if len(parts) == 0 {
panic(&ValueError{Msg: "not enough values to unpack (expected at least 1, got 0)"})
}
root, parts = parts[0], parts[1:]
wasQualified = true
} else {
columnTable = resolver.GetTableByName(root.Name())
wasQualified = false
}
if columnTable != nil {
converted = true
newColumn := ColumnExpr(root, columnTable, nil, nil, nil, nil, true)
if len(dotParts) > 0 {
// Remove the actual column parts from the rest of dot parts
skip := 1
if wasQualified {
skip = 2
}
rest := []string{}
if skip < len(dotParts) {
rest = append(rest, dotParts[skip:]...)
}
newColumn.Meta()["dot_parts"] = rest
}
column.Replace(DotBuild(append([]*Expr{newColumn}, parts...)))
}
}
}
if converted {
// We want to re-aggregate the converted columns, otherwise they'd be skipped in
// a `for column in scope.columns` iteration, even though they shouldn't be
scope.ClearCache()
}
}
// qcQualifyColumns mirrors _qualify_columns: disambiguate columns, ensuring each column specifies a source.
func qcQualifyColumns(scope *Scope, resolver *Resolver, allowPartialQualification bool) {
for _, column := range scope.Columns() {
columnTable := column.TableName()
columnName := column.Name()
if columnTable != "" && scope.Sources.Has(columnTable) {
columnSource, _ := scope.Sources.Get(columnTable)
sourceColumns := resolver.GetSourceColumns(columnTable, false)
// For pivoted sources, source_columns are pre-pivot; validate against the post-pivot set.
if columnSource.Table != nil {
if pivots := columnSource.Table.ArgL("pivots"); len(pivots) > 0 {
sourceColumns = PivotOutputColumns(pivots[0], sourceColumns).Keys()
}
}
if !allowPartialQualification &&
len(sourceColumns) > 0 &&
!containsStr(sourceColumns, columnName) &&
!containsStr(sourceColumns, "*") {
panic(&OptimizeError{Msg: "Unknown column: " + columnName})
}
}
if columnTable == "" {
if pivots := scope.Pivots(); len(pivots) > 0 && column.FindAncestor(KPivot) == nil {
// If the column is under the Pivot expression, we need to qualify it
// using the name of the pivoted source instead of the pivot's alias
column.Set("table", ToIdentifier(pivots[0].Alias(), nil))
continue
}
// column_table can be a '' because bigquery unnest has no table alias
table := resolver.GetTable(column)
if table != nil {
if source, ok := scope.Sources.Get(table.Name()); ok && source.Scope != nil {
if _, inIndex := source.Scope.ColumnIndex()[column]; inIndex {
continue
}
}
}
if table != nil {
column.Set("table", table)
} else if resolver.dialect.S.TABLES_REFERENCEABLE_AS_COLUMNS &&
len(column.Parts()) == 1 &&
scope.SelectedSources().Has(columnName) {
// BigQuery and Postgres allow tables to be referenced as columns, treating them as structs/records
scope.Replace(column, New(KTableColumn, "this", column.This()))
}
}
}
for _, pivot := range scope.Pivots() {
for column := range pivot.FindAll(KColumn) {
if column.TableName() == "" && resolver.AllColumns().Has(column.Name()) {
if table := resolver.GetTableByName(column.Name()); table != nil {
column.Set("table", table)
}
}
}
}
}
// qcIsType mirrors Expr.is_type(dtype) (the annotated type) for a single DType.
func qcIsType(e *Expr, dtype DType) bool {
t := e.Type()
return t != nil && DataTypeIsType(t, []any{dtype}, false)
}
// qcExpandStructStarsNoParens mirrors _expand_struct_stars_no_parens:
// [BigQuery] Expand/Flatten foo.bar.* where bar is a struct column.
func qcExpandStructStarsNoParens(expression *Expr) []*Expr {
dotColumn := expression.Find(KColumn)
if !dotColumn.IsA(KColumn) || !qcIsType(dotColumn, DT_STRUCT) {
return nil
}
// All nested struct values are ColumnDefs, so normalize the first exp.Column in one
dotColumn = dotColumn.Copy()
startingStruct := New(KColumnDef, "this", dotColumn.This(), "kind", dotColumn.Type())
// First part is the table name and last part is the star so they can be dropped
allParts := expression.Parts()
var dotParts []*Expr
if len(allParts) > 2 {
dotParts = allParts[1 : len(allParts)-1]
}
// If we're expanding a nested struct eg. t.c.f1.f2.* find the last struct (f2 in this case)
if len(dotParts) > 1 {
for _, part := range dotParts[1:] {
found := false
for _, field := range startingStruct.ArgE("kind").Expressions() {
// Unable to expand star unless all fields are named
if !field.This().IsA(KIdentifier) {
return nil
}
if field.Name() == part.Name() && field.ArgE("kind") != nil && DataTypeIsType(field.ArgE("kind"), []any{DT_STRUCT}, false) {
startingStruct = field
found = true
break
}
}
if !found {
// There is no matching field in the struct
return nil
}
}
}
takenNames := newStrSet()
var newSelections []*Expr
for _, field := range startingStruct.ArgE("kind").Expressions() {
name := field.Name()
// Ambiguous or anonymous fields can't be expanded
if takenNames.Has(name) || !field.This().IsA(KIdentifier) {
return nil
}
takenNames.Add(name)
this := field.This().Copy()
var copied []*Expr
for _, part := range dotParts {
copied = append(copied, part.Copy())
}
copied = append(copied, this.Copy())
root, rest := copied[0], copied[1:]
fields := make([]any, len(rest))
for i, p := range rest {
fields[i] = p
}
var table any
if t := dotColumn.ArgE("table"); t != nil {
table = t
}
newColumn := ColumnExpr(root, table, nil, nil, fields, nil, true)
newSelections = append(newSelections, chunkFAssertIs(AliasExpr(newColumn, this, nil, false), KAlias))
}
return newSelections
}
// qcExpandStructStarsWithParens mirrors _expand_struct_stars_with_parens:
// [RisingWave] Expand/Flatten (<exp>.bar).*, where bar is a struct column.
func qcExpandStructStarsWithParens(expression *Expr) []*Expr {
// it is not (<sub_exp>).* pattern, which means we can't expand
if !expression.This().IsA(KParen) {
return nil
}
// find column definition to get data-type
dotColumn := expression.Find(KColumn)
if !dotColumn.IsA(KColumn) || !qcIsType(dotColumn, DT_STRUCT) {
return nil
}
parent := dotColumn.Parent()
startingStruct := dotColumn.Type()
// walk up AST and down into struct definition in sync
for parent != nil {
if parent.IsA(KParen) {
parent = parent.Parent()
continue
}
// if parent is not a dot, then something is wrong
if !parent.IsA(KDot) {
return nil
}
// if the rhs of the dot is star we are done
rhs := parent.Right()
if rhs.IsA(KStar) {
break
}
// if it is not identifier, then something is wrong
if !rhs.IsA(KIdentifier) {
return nil
}
// Check if current rhs identifier is in struct
matched := false
for _, structFieldDef := range startingStruct.Expressions() {
if structFieldDef.Name() == rhs.Name() {
matched = true
startingStruct = structFieldDef.ArgE("kind") // update struct
break
}
}
if !matched {