-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
scope.go
1598 lines (1423 loc) · 50.4 KB
/
scope.go
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
// Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package optbuilder
import (
"bytes"
"context"
"fmt"
"strings"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/opt"
"github.com/cockroachdb/cockroach/pkg/sql/opt/cat"
"github.com/cockroachdb/cockroach/pkg/sql/opt/memo"
"github.com/cockroachdb/cockroach/pkg/sql/opt/props"
"github.com/cockroachdb/cockroach/pkg/sql/opt/props/physical"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqlerrors"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/errors"
)
// scope is used for the build process and maintains the variables that have
// been bound within the current scope as columnProps. Variables bound in the
// parent scope are also visible in this scope.
//
// See builder.go for more details.
type scope struct {
builder *Builder
parent *scope
cols []scopeColumn
// groupby is the structure that keeps the grouping metadata when this scope
// includes aggregate functions or GROUP BY.
groupby *groupby
// inAgg is true within the body of an aggregate function. inAgg is used
// to ensure that nested aggregates are disallowed.
// TODO(radu): this, together with some other fields below, belongs in a
// context that is threaded through the calls instead of setting and resetting
// it in the scope.
inAgg bool
// windows contains the set of window functions encountered while building
// the current SELECT statement.
windows []scopeColumn
// windowDefs is the set of named window definitions present in the nearest
// SELECT.
windowDefs []*tree.WindowDef
// ordering records the ORDER BY columns associated with this scope. Each
// column is either in cols or in extraCols.
// Must not be modified in-place after being set.
ordering opt.Ordering
// distinctOnCols records the DISTINCT ON columns by ID.
distinctOnCols opt.ColSet
// extraCols contains columns specified by the ORDER BY or DISTINCT ON clauses
// which don't appear in cols.
extraCols []scopeColumn
// expr is the SQL node built with this scope.
expr memo.RelExpr
// Desired number of columns for subqueries found during name resolution and
// type checking. This only applies to the top-level subqueries that are
// anchored directly to a relational expression.
columns int
// If replaceSRFs is true, replace raw SRFs with an srf struct. See
// the replaceSRF() function for more details.
replaceSRFs bool
// singleSRFColumn is true if this scope has a single column that comes from
// an SRF. The flag is used to allow renaming the column to the table alias.
singleSRFColumn bool
// srfs contains all the SRFs that were replaced in this scope. It will be
// used by the Builder to convert the input from the FROM clause to a lateral
// cross join between the input and a Zip of all the srfs in this slice.
srfs []*srf
// ctes contains the CTEs which were created at this scope. This set
// is not exhaustive because expressions can reference CTEs from parent
// scopes.
ctes map[string]*cteSource
// context is the current context in the SQL query (e.g., "SELECT" or
// "HAVING"). It is used for error messages and to identify scoping errors
// (e.g., aggregates are not allowed in the FROM clause of their own query
// level).
context exprKind
// atRoot is whether we are currently at a root context.
atRoot bool
}
// cteSource represents a CTE in the given query.
type cteSource struct {
id opt.WithID
name tree.AliasClause
cols physical.Presentation
originalExpr tree.Statement
expr memo.RelExpr
mtr tree.MaterializeClause
// If set, this function is called when a CTE is referenced. It can throw an
// error.
onRef func()
}
// exprKind is used to represent the kind of the current expression in the
// SQL query.
type exprKind int8
const (
exprKindNone exprKind = iota
exprKindAlterTableSplitAt
exprKindDistinctOn
exprKindFrom
exprKindGroupBy
exprKindHaving
exprKindLateralJoin
exprKindLimit
exprKindOffset
exprKindOn
exprKindOrderBy
exprKindReturning
exprKindSelect
exprKindValues
exprKindWhere
exprKindWindowFrameStart
exprKindWindowFrameEnd
)
var exprKindName = [...]string{
exprKindNone: "",
exprKindAlterTableSplitAt: "ALTER TABLE SPLIT AT",
exprKindDistinctOn: "DISTINCT ON",
exprKindFrom: "FROM",
exprKindGroupBy: "GROUP BY",
exprKindHaving: "HAVING",
exprKindLateralJoin: "LATERAL JOIN",
exprKindLimit: "LIMIT",
exprKindOffset: "OFFSET",
exprKindOn: "ON",
exprKindOrderBy: "ORDER BY",
exprKindReturning: "RETURNING",
exprKindSelect: "SELECT",
exprKindValues: "VALUES",
exprKindWhere: "WHERE",
exprKindWindowFrameStart: "WINDOW FRAME START",
exprKindWindowFrameEnd: "WINDOW FRAME END",
}
func (k exprKind) String() string {
if k < 0 || k > exprKind(len(exprKindName)-1) {
return fmt.Sprintf("exprKind(%d)", k)
}
return exprKindName[k]
}
// initGrouping initializes the groupby information for this scope.
func (s *scope) initGrouping() {
if s.groupby != nil {
panic(errors.AssertionFailedf("grouping initialized twice"))
}
s.groupby = &groupby{
aggInScope: s.replace(),
aggOutScope: s.replace(),
}
}
// inGroupingContext returns true if initGrouping was called. This is the
// case when the builder is building expressions in a SELECT list, and
// aggregates, GROUP BY, or HAVING are present. This is also true when the
// builder is building expressions inside the HAVING clause. When
// inGroupingContext returns true, groupByStrSet will be utilized to enforce
// scoping rules. See the comment above groupByStrSet for more details.
func (s *scope) inGroupingContext() bool {
return s.groupby != nil
}
// push creates a new scope with this scope as its parent.
func (s *scope) push() *scope {
r := s.builder.allocScope()
r.parent = s
return r
}
// replace creates a new scope with the parent of this scope as its parent.
func (s *scope) replace() *scope {
r := s.builder.allocScope()
r.parent = s.parent
return r
}
// appendColumnsFromScope adds newly bound variables to this scope.
// The expressions in the new columns are reset to nil.
func (s *scope) appendColumnsFromScope(src *scope) {
l := len(s.cols)
s.cols = append(s.cols, src.cols...)
// We want to reset the expressions, as these become pass-through columns in
// the new scope.
for i := l; i < len(s.cols); i++ {
s.cols[i].scalar = nil
}
}
// appendOrdinaryColumnsFromTable adds all non-mutation and non-system columns from the
// given table metadata to this scope.
func (s *scope) appendOrdinaryColumnsFromTable(tabMeta *opt.TableMeta, alias *tree.TableName) {
tab := tabMeta.Table
if s.cols == nil {
s.cols = make([]scopeColumn, 0, tab.ColumnCount())
}
for i, n := 0, tab.ColumnCount(); i < n; i++ {
tabCol := tab.Column(i)
if tabCol.Kind() != cat.Ordinary {
continue
}
s.cols = append(s.cols, scopeColumn{
name: tabCol.ColName(),
table: *alias,
typ: tabCol.DatumType(),
id: tabMeta.MetaID.ColumnID(i),
visibility: tabCol.Visibility(),
})
}
}
// appendColumns adds newly bound variables to this scope.
// The expressions in the new columns are reset to nil.
func (s *scope) appendColumns(cols []scopeColumn) {
l := len(s.cols)
s.cols = append(s.cols, cols...)
// We want to reset the expressions, as these become pass-through columns in
// the new scope.
for i := l; i < len(s.cols); i++ {
s.cols[i].scalar = nil
}
}
// appendColumn adds a newly bound variable to this scope.
// The expression in the new column is reset to nil.
func (s *scope) appendColumn(col *scopeColumn) {
s.cols = append(s.cols, *col)
// We want to reset the expression, as this becomes a pass-through column in
// the new scope.
s.cols[len(s.cols)-1].scalar = nil
}
// addExtraColumns adds the given columns as extra columns, ignoring any
// duplicate columns that are already in the scope.
func (s *scope) addExtraColumns(cols []scopeColumn) {
existing := s.colSetWithExtraCols()
for i := range cols {
if !existing.Contains(cols[i].id) {
s.extraCols = append(s.extraCols, cols[i])
}
}
}
// addColumn adds a column to scope with the given alias and typed expression.
// It returns a pointer to the new column. The column ID and group are left
// empty so they can be filled in later.
func (s *scope) addColumn(alias string, expr tree.TypedExpr) *scopeColumn {
name := tree.Name(alias)
s.cols = append(s.cols, scopeColumn{
name: name,
typ: expr.ResolvedType(),
expr: expr,
})
return &s.cols[len(s.cols)-1]
}
// setOrdering sets the ordering in the physical properties and adds any new
// columns as extra columns.
func (s *scope) setOrdering(cols []scopeColumn, ord opt.Ordering) {
s.addExtraColumns(cols)
s.ordering = ord
}
// copyOrdering copies the ordering and the ORDER BY columns from the src scope.
// The groups in the new columns are reset to 0.
func (s *scope) copyOrdering(src *scope) {
s.ordering = src.ordering
if src.ordering.Empty() {
return
}
// Copy any columns that the scope doesn't already have.
existing := s.colSetWithExtraCols()
for _, ordCol := range src.ordering {
if !existing.Contains(ordCol.ID()) {
col := *src.getColumn(ordCol.ID())
// We want to reset the group, as this becomes a pass-through column in
// the new scope.
col.scalar = nil
s.extraCols = append(s.extraCols, col)
}
}
}
// getColumn returns the scopeColumn with the given id (either in cols or
// extraCols).
func (s *scope) getColumn(col opt.ColumnID) *scopeColumn {
for i := range s.cols {
if s.cols[i].id == col {
return &s.cols[i]
}
}
for i := range s.extraCols {
if s.extraCols[i].id == col {
return &s.extraCols[i]
}
}
return nil
}
// getColumnForTableOrdinal returns the column with a specific tableOrdinal
// value, or nil if it doesn't exist.
func (s *scope) getColumnForTableOrdinal(tabOrd int) *scopeColumn {
for i := range s.cols {
if s.cols[i].tableOrdinal == tabOrd {
return &s.cols[i]
}
}
return nil
}
func (s *scope) makeColumnTypes() []*types.T {
res := make([]*types.T, len(s.cols))
for i := range res {
res[i] = s.cols[i].typ
}
return res
}
// makeOrderingChoice returns an OrderingChoice that corresponds to s.ordering.
func (s *scope) makeOrderingChoice() physical.OrderingChoice {
var oc physical.OrderingChoice
oc.FromOrdering(s.ordering)
return oc
}
// makePhysicalProps constructs physical properties using the columns in the
// scope for presentation and s.ordering for required ordering.
func (s *scope) makePhysicalProps() *physical.Required {
p := &physical.Required{
Presentation: s.makePresentation(),
}
p.Ordering.FromOrdering(s.ordering)
return p
}
func (s *scope) makePresentation() physical.Presentation {
if len(s.cols) == 0 {
return nil
}
presentation := make(physical.Presentation, 0, len(s.cols))
for i := range s.cols {
col := &s.cols[i]
if col.visibility == cat.Visible {
presentation = append(presentation, opt.AliasedColumn{
Alias: string(col.name),
ID: col.id,
})
}
}
return presentation
}
// makePresentationWithHiddenCols is only used when constructing the
// presentation for a [ ... ]-style data source.
func (s *scope) makePresentationWithHiddenCols() physical.Presentation {
if len(s.cols) == 0 {
return nil
}
presentation := make(physical.Presentation, 0, len(s.cols))
for i := range s.cols {
col := &s.cols[i]
presentation = append(presentation, opt.AliasedColumn{
Alias: string(col.name),
ID: col.id,
})
}
return presentation
}
// walkExprTree walks the given expression and performs name resolution,
// replaces unresolved column names with columnProps, and replaces subqueries
// with typed subquery structs.
func (s *scope) walkExprTree(expr tree.Expr) tree.Expr {
// TODO(peter): The caller should specify the desired number of columns. This
// is needed when a subquery is used by an UPDATE statement.
// TODO(andy): shouldn't this be part of the desired type rather than yet
// another parameter?
s.columns = 1
expr, _ = tree.WalkExpr(s, expr)
s.builder.semaCtx.IVarContainer = s
return expr
}
// resolveCTE looks up a CTE name in this and the parent scopes, returning nil
// if it's not found.
func (s *scope) resolveCTE(name *tree.TableName) *cteSource {
var nameStr string
seenCTEs := false
for s != nil {
if s.ctes != nil {
// Only compute the stringified name if we see any CTEs.
if !seenCTEs {
nameStr = name.String()
seenCTEs = true
}
if cte, ok := s.ctes[nameStr]; ok {
if cte.onRef != nil {
cte.onRef()
}
return cte
}
}
s = s.parent
}
return nil
}
// resolveType converts the given expr to a tree.TypedExpr. As part of the
// conversion, it performs name resolution, replaces unresolved column names
// with columnProps, and replaces subqueries with typed subquery structs.
//
// The desired type is a suggestion, but resolveType does not throw an error if
// the resolved type turns out to be different from desired (in contrast to
// resolveAndRequireType, which throws an error). If the result type is
// types.Unknown, then resolveType will wrap the expression in a type cast in
// order to produce the desired type.
func (s *scope) resolveType(expr tree.Expr, desired *types.T) tree.TypedExpr {
expr = s.walkExprTree(expr)
texpr, err := tree.TypeCheck(s.builder.ctx, expr, s.builder.semaCtx, desired)
if err != nil {
panic(err)
}
return s.ensureNullType(texpr, desired)
}
// resolveAndRequireType converts the given expr to a tree.TypedExpr. As part
// of the conversion, it performs name resolution, replaces unresolved
// column names with columnProps, and replaces subqueries with typed subquery
// structs.
//
// If the resolved type does not match the desired type, resolveAndRequireType
// throws an error (in contrast to resolveType, which returns the typed
// expression with no error). If the result type is types.Unknown, then
// resolveType will wrap the expression in a type cast in order to produce the
// desired type.
func (s *scope) resolveAndRequireType(expr tree.Expr, desired *types.T) tree.TypedExpr {
expr = s.walkExprTree(expr)
texpr, err := tree.TypeCheckAndRequire(s.builder.ctx, expr, s.builder.semaCtx, desired, s.context.String())
if err != nil {
panic(err)
}
return s.ensureNullType(texpr, desired)
}
// ensureNullType tests the type of the given expression. If types.Unknown, then
// ensureNullType wraps the expression in a CAST to the desired type (assuming
// it is not types.Any). types.Unknown is a special type used for null values,
// and can be cast to any other type.
func (s *scope) ensureNullType(texpr tree.TypedExpr, desired *types.T) tree.TypedExpr {
if desired.Family() != types.AnyFamily && texpr.ResolvedType().Family() == types.UnknownFamily {
texpr = tree.NewTypedCastExpr(texpr, desired)
}
return texpr
}
// isOuterColumn returns true if the given column is not present in the current
// scope (it may or may not be present in an ancestor scope).
func (s *scope) isOuterColumn(id opt.ColumnID) bool {
for i := range s.cols {
col := &s.cols[i]
if col.id == id {
return false
}
}
for i := range s.windows {
w := &s.windows[i]
if w.id == id {
return false
}
}
return true
}
// colSet returns a ColSet of all the columns in this scope,
// excluding orderByCols.
func (s *scope) colSet() opt.ColSet {
var colSet opt.ColSet
for i := range s.cols {
colSet.Add(s.cols[i].id)
}
return colSet
}
// colSetWithExtraCols returns a ColSet of all the columns in this scope,
// including extraCols.
func (s *scope) colSetWithExtraCols() opt.ColSet {
colSet := s.colSet()
for i := range s.extraCols {
colSet.Add(s.extraCols[i].id)
}
return colSet
}
// hasSameColumns returns true if this scope has the same columns
// as the other scope.
//
// NOTE: This function is currently only called by
// Builder.constructProjectForScope, which uses it to determine whether or not
// to construct a projection. Since the projection includes the extra columns,
// this check is sufficient to determine whether or not the projection is
// necessary. Be careful if using this function for another purpose.
func (s *scope) hasSameColumns(other *scope) bool {
return s.colSetWithExtraCols().Equals(other.colSetWithExtraCols())
}
// removeHiddenCols removes hidden columns from the scope (and moves them to
// extraCols, in case they are referenced by ORDER BY or DISTINCT ON).
func (s *scope) removeHiddenCols() {
n := 0
for i := range s.cols {
if s.cols[i].visibility != cat.Visible {
s.extraCols = append(s.extraCols, s.cols[i])
} else {
if n != i {
s.cols[n] = s.cols[i]
}
n++
}
}
s.cols = s.cols[:n]
}
// isAnonymousTable returns true if the table name of the first column
// in this scope is empty.
func (s *scope) isAnonymousTable() bool {
return len(s.cols) > 0 && s.cols[0].table.ObjectName == ""
}
// setTableAlias qualifies the names of all columns in this scope with the
// given alias name, as if they were part of a table with that name. If the
// alias is the empty string, then setTableAlias removes any existing column
// qualifications, as if the columns were part of an "anonymous" table.
func (s *scope) setTableAlias(alias tree.Name) {
tn := tree.MakeUnqualifiedTableName(alias)
for i := range s.cols {
s.cols[i].table = tn
}
}
// See (*scope).findExistingCol.
func findExistingColInList(
expr tree.TypedExpr, cols []scopeColumn, allowSideEffects bool,
) *scopeColumn {
exprStr := symbolicExprStr(expr)
for i := range cols {
col := &cols[i]
if expr == col {
return col
}
if exprStr == col.getExprStr() {
if allowSideEffects || col.scalar == nil {
return col
}
var p props.Shared
memo.BuildSharedProps(col.scalar, &p)
if !p.VolatilitySet.HasVolatile() {
return col
}
}
}
return nil
}
// findExistingCol finds the given expression among the bound variables in this
// scope. Returns nil if the expression is not found (or an expression is found
// but it has side-effects and allowSideEffects is false).
// If a column is found and we are tracking view dependencies, we add the column
// to the view dependencies since it means this column is being referenced.
func (s *scope) findExistingCol(expr tree.TypedExpr, allowSideEffects bool) *scopeColumn {
col := findExistingColInList(expr, s.cols, allowSideEffects)
if col != nil {
s.builder.trackReferencedColumnForViews(col)
}
return col
}
// startAggFunc is called when the builder starts building an aggregate
// function. It is used to disallow nested aggregates and ensure that a
// grouping error is not called on the aggregate arguments. For example:
// SELECT max(v) FROM kv GROUP BY k
// should not throw an error, even though v is not a grouping column.
// Non-grouping columns are allowed inside aggregate functions.
//
// startAggFunc returns a temporary scope for building the aggregate arguments.
// It is not possible to know the correct scope until the arguments are fully
// built. At that point, endAggFunc can be used to find the correct scope.
// If endAggFunc returns a different scope than startAggFunc, the columns
// will be transferred to the correct scope by buildAggregateFunction.
func (s *scope) startAggFunc() *scope {
if s.inAgg {
panic(sqlerrors.NewAggInAggError())
}
s.inAgg = true
if s.groupby == nil {
return s.builder.allocScope()
}
return s.groupby.aggInScope
}
// endAggFunc is called when the builder finishes building an aggregate
// function. It is used in combination with startAggFunc to disallow nested
// aggregates and prevent grouping errors while building aggregate arguments.
//
// In addition, endAggFunc finds the correct groupby structure, given
// that the aggregate references the columns in cols. The reference scope
// is the one closest to the current scope which contains at least one of the
// variables referenced by the aggregate (or the current scope if the aggregate
// references no variables). endAggFunc also ensures that aggregate functions
// are only used in a groupings scope.
func (s *scope) endAggFunc(cols opt.ColSet) (g *groupby) {
if !s.inAgg {
panic(errors.AssertionFailedf("mismatched calls to start/end aggFunc"))
}
s.inAgg = false
for curr := s; curr != nil; curr = curr.parent {
if cols.Len() == 0 || cols.Intersects(curr.colSet()) {
curr.verifyAggregateContext()
if curr.groupby == nil {
curr.initGrouping()
}
return curr.groupby
}
}
panic(errors.AssertionFailedf("aggregate function is not allowed in this context"))
}
// verifyAggregateContext checks that the current scope is allowed to contain
// aggregate functions.
func (s *scope) verifyAggregateContext() {
if s.inAgg {
panic(sqlerrors.NewAggInAggError())
}
switch s.context {
case exprKindLateralJoin:
panic(pgerror.Newf(pgcode.Grouping,
"aggregate functions are not allowed in FROM clause of their own query level",
))
case exprKindOn:
panic(pgerror.Newf(pgcode.Grouping,
"aggregate functions are not allowed in JOIN conditions",
))
case exprKindWhere:
panic(tree.NewInvalidFunctionUsageError(tree.AggregateClass, s.context.String()))
}
}
// scope implements the tree.Visitor interface so that it can walk through
// a tree.Expr tree, perform name resolution, and replace unresolved column
// names with a scopeColumn. The info stored in scopeColumn is necessary for
// Builder.buildScalar to construct a "variable" memo expression.
var _ tree.Visitor = &scope{}
// ColumnSourceMeta implements the tree.ColumnSourceMeta interface.
func (*scope) ColumnSourceMeta() {}
// ColumnSourceMeta implements the tree.ColumnSourceMeta interface.
func (*scopeColumn) ColumnSourceMeta() {}
// ColumnResolutionResult implements the tree.ColumnResolutionResult interface.
func (*scopeColumn) ColumnResolutionResult() {}
// FindSourceProvidingColumn is part of the tree.ColumnItemResolver interface.
func (s *scope) FindSourceProvidingColumn(
_ context.Context, colName tree.Name,
) (prefix *tree.TableName, srcMeta tree.ColumnSourceMeta, colHint int, err error) {
var candidateFromAnonSource *scopeColumn
var candidateWithPrefix *scopeColumn
var hiddenCandidate *scopeColumn
var moreThanOneCandidateFromAnonSource bool
var moreThanOneCandidateWithPrefix bool
var moreThanOneHiddenCandidate bool
// We only allow hidden columns in the current scope. Hidden columns
// in parent scopes are not accessible.
allowHidden := true
// If multiple columns match c in the same scope, we return an error
// due to ambiguity. If no columns match in the current scope, we
// search the parent scope. If the column is not found in any of the
// ancestor scopes, we return an error.
reportBackfillError := false
for ; s != nil; s, allowHidden = s.parent, false {
for i := range s.cols {
col := &s.cols[i]
if col.name != colName {
continue
}
switch col.visibility {
case cat.Inaccessible:
// Act as if this column is not present so that matches in higher scopes
// can be found. However, if no match is found in higher scopes and this
// is a mutation column, report a backfill error rather than a "not
// found" error.
if col.mutation {
reportBackfillError = true
}
case cat.Visible:
if col.table.ObjectName == "" {
if candidateFromAnonSource != nil {
moreThanOneCandidateFromAnonSource = true
}
candidateFromAnonSource = col
} else {
if candidateWithPrefix != nil {
moreThanOneCandidateWithPrefix = true
}
candidateWithPrefix = col
}
case cat.Hidden:
if allowHidden {
if hiddenCandidate != nil {
moreThanOneHiddenCandidate = true
}
hiddenCandidate = col
}
}
}
// The table name was unqualified, so if a single anonymous source exists
// with a matching non-hidden column, use that.
if moreThanOneCandidateFromAnonSource {
return nil, nil, -1, s.newAmbiguousColumnError(
colName, allowHidden, moreThanOneCandidateFromAnonSource, moreThanOneCandidateWithPrefix, moreThanOneHiddenCandidate,
)
}
if candidateFromAnonSource != nil {
return &candidateFromAnonSource.table, candidateFromAnonSource, int(candidateFromAnonSource.id), nil
}
// Else if a single named source exists with a matching non-hidden column,
// use that.
if candidateWithPrefix != nil && !moreThanOneCandidateWithPrefix {
return &candidateWithPrefix.table, candidateWithPrefix, int(candidateWithPrefix.id), nil
}
if moreThanOneCandidateWithPrefix || moreThanOneHiddenCandidate {
return nil, nil, -1, s.newAmbiguousColumnError(
colName, allowHidden, moreThanOneCandidateFromAnonSource, moreThanOneCandidateWithPrefix, moreThanOneHiddenCandidate,
)
}
// One last option: if a single source exists with a matching hidden
// column, use that.
if hiddenCandidate != nil {
return &hiddenCandidate.table, hiddenCandidate, int(hiddenCandidate.id), nil
}
}
// Make a copy of colName so that passing a reference to tree.ErrString does
// not cause colName to be allocated on the heap in the happy (no error) path
// above.
tmpName := colName
if reportBackfillError {
return nil, nil, -1, makeBackfillError(tmpName)
}
return nil, nil, -1, colinfo.NewUndefinedColumnError(tree.ErrString(&tmpName))
}
// FindSourceMatchingName is part of the tree.ColumnItemResolver interface.
func (s *scope) FindSourceMatchingName(
_ context.Context, tn tree.TableName,
) (
res tree.NumResolutionResults,
prefix *tree.TableName,
srcMeta tree.ColumnSourceMeta,
err error,
) {
// If multiple sources match tn in the same scope, we return an error
// due to ambiguity. If no sources match in the current scope, we
// search the parent scope. If the source is not found in any of the
// ancestor scopes, we return an error.
var source tree.TableName
for ; s != nil; s = s.parent {
sources := make(map[tree.TableName]struct{})
for i := range s.cols {
sources[s.cols[i].table] = struct{}{}
}
found := false
for src := range sources {
if !sourceNameMatches(src, tn) {
continue
}
if found {
return tree.MoreThanOne, nil, s, newAmbiguousSourceError(&tn)
}
found = true
source = src
}
if found {
return tree.ExactlyOne, &source, s, nil
}
}
return tree.NoResults, nil, s, nil
}
// sourceNameMatches checks whether a request for table name toFind
// can be satisfied by the FROM source name srcName.
//
// For example:
// - a request for "kv" is matched by a source named "db1.public.kv"
// - a request for "public.kv" is not matched by a source named just "kv"
func sourceNameMatches(srcName tree.TableName, toFind tree.TableName) bool {
if srcName.ObjectName != toFind.ObjectName {
return false
}
if toFind.ExplicitSchema {
if srcName.SchemaName != toFind.SchemaName {
return false
}
if toFind.ExplicitCatalog {
if srcName.CatalogName != toFind.CatalogName {
return false
}
}
}
return true
}
// Resolve is part of the tree.ColumnItemResolver interface.
func (s *scope) Resolve(
_ context.Context,
prefix *tree.TableName,
srcMeta tree.ColumnSourceMeta,
colHint int,
colName tree.Name,
) (tree.ColumnResolutionResult, error) {
if colHint >= 0 {
// Column was found by FindSourceProvidingColumn above.
return srcMeta.(*scopeColumn), nil
}
// Otherwise, a table is known but not the column yet.
inScope := srcMeta.(*scope)
for i := range inScope.cols {
col := &inScope.cols[i]
if col.name == colName && sourceNameMatches(*prefix, col.table) {
return col, nil
}
}
return nil, colinfo.NewUndefinedColumnError(tree.ErrString(tree.NewColumnItem(prefix, colName)))
}
func makeUntypedTuple(labels []string, texprs []tree.TypedExpr) *tree.Tuple {
exprs := make(tree.Exprs, len(texprs))
for i, e := range texprs {
exprs[i] = e
}
return &tree.Tuple{Exprs: exprs, Labels: labels}
}
// VisitPre is part of the Visitor interface.
//
// NB: This code is adapted from sql/select_name_resolution.go and
// sql/subquery.go.
func (s *scope) VisitPre(expr tree.Expr) (recurse bool, newExpr tree.Expr) {
switch t := expr.(type) {
case *tree.AllColumnsSelector, *tree.TupleStar:
// AllColumnsSelectors and TupleStars at the top level of a SELECT clause
// are replaced when the select's renders are prepared. If we
// encounter one here during expression analysis, it's being used
// as an argument to an inner expression/function. In that case,
// treat it as a tuple of the expanded columns.
//
// Hence:
// SELECT kv.* FROM kv -> SELECT k, v FROM kv
// SELECT (kv.*) FROM kv -> SELECT (k, v) FROM kv
// SELECT COUNT(DISTINCT kv.*) FROM kv -> SELECT COUNT(DISTINCT (k, v)) FROM kv
//
labels, exprs := s.builder.expandStar(expr, s)
// We return an untyped tuple because name resolution occurs
// before type checking, and type checking will resolve the
// tuple's type. However we need to preserve the labels in
// case of e.g. `SELECT (kv.*).v`.
return false, makeUntypedTuple(labels, exprs)
case *tree.UnresolvedName:
vn, err := t.NormalizeVarName()
if err != nil {
panic(err)
}
return s.VisitPre(vn)
case *tree.ColumnItem:
colI, err := t.Resolve(s.builder.ctx, s)
if err != nil {
panic(err)
}
return false, colI.(*scopeColumn)
case *tree.FuncExpr:
def, err := t.Func.Resolve(s.builder.semaCtx.SearchPath)
if err != nil {
panic(err)
}
if isGenerator(def) && s.replaceSRFs {
expr = s.replaceSRF(t, def)
break
}
if isAggregate(def) && t.WindowDef == nil {
expr = s.replaceAggregate(t, def)
break
}
if t.WindowDef != nil {
expr = s.replaceWindowFn(t, def)
break
}
if isSQLFn(def) {
expr = s.replaceSQLFn(t, def)
break
}
case *tree.ArrayFlatten:
if sub, ok := t.Subquery.(*tree.Subquery); ok {
// Copy the ArrayFlatten expression so that the tree isn't mutated.
copy := *t
copy.Subquery = s.replaceSubquery(
sub, false /* wrapInTuple */, 1 /* desiredNumColumns */, extraColsAllowed,
)
expr = ©
}
case *tree.ComparisonExpr:
switch t.Operator {
case tree.In, tree.NotIn, tree.Any, tree.Some, tree.All:
if sub, ok := t.Right.(*tree.Subquery); ok {
// Copy the Comparison expression so that the tree isn't mutated.
copy := *t
copy.Right = s.replaceSubquery(
sub, true /* wrapInTuple */, -1 /* desiredNumColumns */, noExtraColsAllowed,
)
expr = ©
}
}
case *tree.Subquery:
if t.Exists {
expr = s.replaceSubquery(
t, true /* wrapInTuple */, -1 /* desiredNumColumns */, noExtraColsAllowed,
)
} else {
expr = s.replaceSubquery(
t, false /* wrapInTuple */, s.columns /* desiredNumColumns */, noExtraColsAllowed,
)
}
}
// Reset the desired number of columns since if the subquery is a child of
// any other expression, type checking will verify the number of columns.
s.columns = -1