forked from cockroachdb/cockroach
/
type_check.go
1445 lines (1288 loc) · 45.6 KB
/
type_check.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 2015 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// Author: Tamir Duberstein (tamird@gmail.com)
package parser
import (
"fmt"
"strings"
"time"
"golang.org/x/text/language"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/pkg/errors"
)
// SemaContext defines the context in which to perform semantic analysis on an
// expression syntax tree.
type SemaContext struct {
// Placeholders relates placeholder names to their type and, later, value.
Placeholders PlaceholderInfo
// Location references the *Location on the current Session.
Location **time.Location
// SearchPath indicates where to search for unqualified function
// names. The path elements must be normalized via Name.Normalize()
// already.
SearchPath []string
// privileged, if true, enables "unsafe" builtins, e.g. those
// from the crdb_internal namespace. Must be set only for
// the root user.
// TODO(knz): this attribute can be moved to EvalContext pending #15363.
privileged bool
}
// MakeSemaContext initializes a simple SemaContext suitable
// for "lightweight" type checking such as the one performed for default
// expressions.
func MakeSemaContext(privileged bool) SemaContext {
return SemaContext{
Placeholders: MakePlaceholderInfo(),
privileged: privileged,
}
}
// isUnresolvedPlaceholder provides a nil-safe method to determine whether expr is an
// unresolved placeholder.
func (sc *SemaContext) isUnresolvedPlaceholder(expr Expr) bool {
if sc == nil {
return false
}
return sc.Placeholders.IsUnresolvedPlaceholder(expr)
}
// GetLocation returns the session timezone.
func (sc *SemaContext) getLocation() *time.Location {
if sc == nil || sc.Location == nil || *sc.Location == nil {
return time.UTC
}
return *sc.Location
}
type placeholderTypeAmbiguityError struct {
v *Placeholder
}
func (err placeholderTypeAmbiguityError) Error() string {
return fmt.Sprintf("could not determine data type of placeholder %s", err.v)
}
type unexpectedTypeError struct {
expr Expr
want, got Type
}
func (err unexpectedTypeError) Error() string {
return fmt.Sprintf("expected %s to be of type %s, found type %s", err.expr, err.want, err.got)
}
func decorateTypeCheckError(err error, format string, a ...interface{}) error {
if _, ok := err.(placeholderTypeAmbiguityError); ok {
return err
}
return fmt.Errorf(format+": %v", append(a, err)...)
}
// TypeCheck implements the Expr interface.
func (expr *AndExpr) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
leftTyped, err := typeCheckAndRequireBoolean(ctx, expr.Left, "AND argument")
if err != nil {
return nil, err
}
rightTyped, err := typeCheckAndRequireBoolean(ctx, expr.Right, "AND argument")
if err != nil {
return nil, err
}
expr.Left, expr.Right = leftTyped, rightTyped
expr.typ = TypeBool
return expr, nil
}
// TypeCheck implements the Expr interface.
func (expr *BinaryExpr) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
ops := BinOps[expr.Operator]
overloads := make([]overloadImpl, len(ops))
for i := range ops {
overloads[i] = ops[i]
}
typedSubExprs, fn, err := typeCheckOverloadedExprs(ctx, desired, overloads, expr.Left, expr.Right)
if err != nil {
return nil, err
}
leftTyped, rightTyped := typedSubExprs[0], typedSubExprs[1]
leftReturn := leftTyped.ResolvedType()
rightReturn := rightTyped.ResolvedType()
if leftReturn == TypeNull || rightReturn == TypeNull {
return DNull, nil
}
if fn == nil {
var desStr string
if desired != TypeAny {
desStr = fmt.Sprintf(" (desired <%s>)", desired)
}
return nil, fmt.Errorf("unsupported binary operator: <%s> %s <%s>%s",
leftReturn, expr.Operator, rightReturn, desStr)
}
expr.Left, expr.Right = leftTyped, rightTyped
expr.fn = fn.(BinOp)
expr.typ = fn.returnType()(typedSubExprs)
return expr, nil
}
// TypeCheck implements the Expr interface.
func (expr *CaseExpr) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
var err error
tmpExprs := make([]Expr, 0, len(expr.Whens)+1)
if expr.Expr != nil {
tmpExprs = tmpExprs[:0]
tmpExprs = append(tmpExprs, expr.Expr)
for _, when := range expr.Whens {
tmpExprs = append(tmpExprs, when.Cond)
}
typedSubExprs, _, err := typeCheckSameTypedExprs(ctx, TypeAny, tmpExprs...)
if err != nil {
return nil, decorateTypeCheckError(err, "incompatible condition type")
}
expr.Expr = typedSubExprs[0]
for i, whenCond := range typedSubExprs[1:] {
expr.Whens[i].Cond = whenCond
}
} else {
// If expr.Expr is nil, the WHEN clauses contain boolean expressions.
for i, when := range expr.Whens {
typedCond, err := typeCheckAndRequireBoolean(ctx, when.Cond, "condition")
if err != nil {
return nil, err
}
expr.Whens[i].Cond = typedCond
}
}
tmpExprs = tmpExprs[:0]
for _, when := range expr.Whens {
tmpExprs = append(tmpExprs, when.Val)
}
if expr.Else != nil {
tmpExprs = append(tmpExprs, expr.Else)
}
typedSubExprs, retType, err := typeCheckSameTypedExprs(ctx, desired, tmpExprs...)
if err != nil {
return nil, decorateTypeCheckError(err, "incompatible value type")
}
if expr.Else != nil {
expr.Else = typedSubExprs[len(typedSubExprs)-1]
typedSubExprs = typedSubExprs[:len(typedSubExprs)-1]
}
for i, whenVal := range typedSubExprs {
expr.Whens[i].Val = whenVal
}
expr.typ = retType
return expr, nil
}
// TypeCheck implements the Expr interface.
func (expr *CastExpr) TypeCheck(ctx *SemaContext, _ Type) (TypedExpr, error) {
returnType := expr.castType()
// The desired type provided to a CastExpr is ignored. Instead,
// TypeAny is passed to the child of the cast. There are two
// exceptions, described below.
desired := TypeAny
switch {
case isConstant(expr.Expr):
if canConstantBecome(expr.Expr.(Constant), returnType) {
// If a Constant is subject to a cast which it can naturally become (which
// is in its resolvable type set), we desire the cast's type for the Constant,
// which will result in the CastExpr becoming an identity cast.
desired = returnType
// If the type doesn't have any possible parameters (like length,
// precision), the CastExpr becomes a no-op and can be elided.
switch expr.Type.(type) {
case *BoolColType, *DateColType, *TimestampColType, *TimestampTZColType,
*IntervalColType, *BytesColType:
return expr.Expr.TypeCheck(ctx, returnType)
}
}
case ctx.isUnresolvedPlaceholder(expr.Expr):
// This case will be triggered if ProcessPlaceholderAnnotations found
// the same placeholder in another location where it was either not
// the child of a cast, or was the child of a cast to a different type.
// In this case, we default to inferring a STRING for the placeholder.
desired = TypeString
}
typedSubExpr, err := expr.Expr.TypeCheck(ctx, desired)
if err != nil {
return nil, err
}
castFrom := typedSubExpr.ResolvedType()
for _, t := range validCastTypes(returnType) {
if castFrom.FamilyEqual(t) {
expr.Expr = typedSubExpr
expr.typ = returnType
return expr, nil
}
}
return nil, fmt.Errorf("invalid cast: %s -> %s", castFrom, expr.Type)
}
// TypeCheck implements the Expr interface.
func (expr *IndirectionExpr) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
for i, t := range expr.Indirection {
if t.Slice {
return nil, util.UnimplementedWithIssueErrorf(2115, "ARRAY slicing in %s", expr)
}
if i > 0 {
return nil, util.UnimplementedWithIssueErrorf(2115, "multidimensional ARRAY %s", expr)
}
beginExpr, err := typeCheckAndRequire(ctx, t.Begin, TypeInt, "ARRAY subscript")
if err != nil {
return nil, err
}
t.Begin = beginExpr
}
subExpr, err := expr.Expr.TypeCheck(ctx, TArray{desired})
if err != nil {
return nil, err
}
typ := UnwrapType(subExpr.ResolvedType())
arrType, ok := typ.(TArray)
if !ok {
return nil, errors.Errorf("cannot subscript type %s because it is not an array", typ)
}
expr.Expr = subExpr
expr.typ = arrType.Typ
return expr, nil
}
// TypeCheck implements the Expr interface.
func (expr *AnnotateTypeExpr) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
annotType := expr.annotationType()
subExpr, err := typeCheckAndRequire(ctx, expr.Expr, annotType,
fmt.Sprintf("type annotation for %v as %s, found", expr.Expr, annotType))
if err != nil {
return nil, err
}
return subExpr, nil
}
// TypeCheck implements the Expr interface.
func (expr *CollateExpr) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
_, err := language.Parse(expr.Locale)
if err != nil {
return nil, errors.Wrapf(err, "invalid locale %s", expr.Locale)
}
subExpr, err := expr.Expr.TypeCheck(ctx, TypeString)
if err != nil {
return nil, err
}
switch t := subExpr.ResolvedType().(type) {
case tString, TCollatedString:
expr.Expr = subExpr
expr.typ = TCollatedString{expr.Locale}
return expr, nil
default:
return nil, fmt.Errorf("incompatible type for COLLATE: %s", t)
}
}
// TypeCheck implements the Expr interface.
func (expr *CoalesceExpr) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
typedSubExprs, retType, err := typeCheckSameTypedExprs(ctx, desired, expr.Exprs...)
if err != nil {
return nil, decorateTypeCheckError(err, fmt.Sprintf("incompatible %s expressions", expr.Name))
}
for i, subExpr := range typedSubExprs {
expr.Exprs[i] = subExpr
}
expr.typ = retType
return expr, nil
}
// TypeCheck implements the Expr interface.
func (expr *ComparisonExpr) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
var leftTyped, rightTyped TypedExpr
var fn CmpOp
var err error
if expr.Operator.hasSubOperator() {
leftTyped, rightTyped, fn, err = typeCheckComparisonOpWithSubOperator(ctx,
expr.Operator,
expr.SubOperator,
expr.Left,
expr.Right,
)
} else {
leftTyped, rightTyped, fn, err = typeCheckComparisonOp(ctx,
expr.Operator,
expr.Left,
expr.Right,
)
}
if err != nil {
return nil, err
}
expr.Left, expr.Right = leftTyped, rightTyped
expr.fn = fn
expr.typ = TypeBool
return expr, err
}
// TypeCheck implements the Expr interface.
func (expr *ExistsExpr) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
subqueryTyped, err := expr.Subquery.TypeCheck(ctx, TypeAny)
if err != nil {
return nil, err
}
expr.Subquery = subqueryTyped
expr.typ = TypeBool
return expr, nil
}
// TypeCheck implements the Expr interface.
func (expr *FuncExpr) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
var searchPath SearchPath
if ctx != nil {
searchPath = ctx.SearchPath
}
def, err := expr.Func.Resolve(searchPath)
if err != nil {
return nil, err
}
overloads := make([]overloadImpl, len(def.Definition))
for i, d := range def.Definition {
overloads[i] = d
}
typedSubExprs, fn, err := typeCheckOverloadedExprs(ctx, desired, overloads, expr.Exprs...)
if err != nil {
return nil, fmt.Errorf("%s(): %v", def.Name, err)
} else if fn == nil {
typeNames := make([]string, 0, len(expr.Exprs))
for _, expr := range typedSubExprs {
typeNames = append(typeNames, expr.ResolvedType().String())
}
var desStr string
if desired != TypeAny {
desStr = fmt.Sprintf(" (desired <%s>)", desired)
}
return nil, fmt.Errorf("unknown signature: %s(%s)%s",
expr.Func, strings.Join(typeNames, ", "), desStr)
}
if expr.WindowDef != nil {
for i, partition := range expr.WindowDef.Partitions {
typedPartition, err := partition.TypeCheck(ctx, TypeAny)
if err != nil {
return nil, err
}
expr.WindowDef.Partitions[i] = typedPartition
}
for i, orderBy := range expr.WindowDef.OrderBy {
typedOrderBy, err := orderBy.Expr.TypeCheck(ctx, TypeAny)
if err != nil {
return nil, err
}
expr.WindowDef.OrderBy[i].Expr = typedOrderBy
}
}
if expr.Filter != nil {
typedFilter, err := typeCheckAndRequireBoolean(ctx, expr.Filter, "FILTER expression")
if err != nil {
return nil, err
}
expr.Filter = typedFilter
}
builtin := fn.(Builtin)
if expr.IsWindowFunctionApplication() {
// Make sure the window function application is of either a built-in window
// function or of a builtin aggregate function.
switch builtin.class {
case AggregateClass:
case WindowClass:
default:
return nil, fmt.Errorf("OVER specified, but %s() is neither a window function nor an "+
"aggregate function", expr.Func)
}
if expr.Filter != nil {
return nil, fmt.Errorf("FILTER within a window function call is not yet supported")
}
} else {
// Make sure the window function builtins are used as window function applications.
switch builtin.class {
case WindowClass:
return nil, fmt.Errorf("window function %s() requires an OVER clause", expr.Func)
}
}
if expr.Filter != nil {
if builtin.class != AggregateClass {
// Same error message as Postgres.
return nil, fmt.Errorf("FILTER specified but %s() is not an aggregate function", expr.Func)
}
}
// Check that the built-in is allowed for the current user.
// TODO(knz): this check can be moved to evaluation time pending #15363.
if builtin.privileged && !ctx.privileged {
return nil, pgerror.NewErrorf(pgerror.CodeInsufficientPrivilegeError,
"insufficient privilege to use %s", expr.Func)
}
for i, subExpr := range typedSubExprs {
expr.Exprs[i] = subExpr
}
expr.fn = builtin
expr.typ = builtin.returnType()(typedSubExprs)
return expr, nil
}
// TypeCheck implements the Expr interface.
func (expr *IfExpr) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
typedCond, err := typeCheckAndRequireBoolean(ctx, expr.Cond, "IF condition")
if err != nil {
return nil, err
}
typedSubExprs, retType, err := typeCheckSameTypedExprs(ctx, desired, expr.True, expr.Else)
if err != nil {
return nil, decorateTypeCheckError(err, "incompatible IF expressions")
}
expr.Cond = typedCond
expr.True, expr.Else = typedSubExprs[0], typedSubExprs[1]
expr.typ = retType
return expr, nil
}
// TypeCheck implements the Expr interface.
func (expr *IsOfTypeExpr) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
exprTyped, err := expr.Expr.TypeCheck(ctx, TypeAny)
if err != nil {
return nil, err
}
expr.Expr = exprTyped
expr.typ = TypeBool
return expr, nil
}
// TypeCheck implements the Expr interface.
func (expr *NotExpr) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
exprTyped, err := typeCheckAndRequireBoolean(ctx, expr.Expr, "NOT argument")
if err != nil {
return nil, err
}
expr.Expr = exprTyped
expr.typ = TypeBool
return expr, nil
}
// TypeCheck implements the Expr interface.
func (expr *NullIfExpr) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
typedSubExprs, retType, err := typeCheckSameTypedExprs(ctx, desired, expr.Expr1, expr.Expr2)
if err != nil {
return nil, decorateTypeCheckError(err, "incompatible NULLIF expressions")
}
expr.Expr1, expr.Expr2 = typedSubExprs[0], typedSubExprs[1]
expr.typ = retType
return expr, nil
}
// TypeCheck implements the Expr interface.
func (expr *OrExpr) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
leftTyped, err := typeCheckAndRequireBoolean(ctx, expr.Left, "OR argument")
if err != nil {
return nil, err
}
rightTyped, err := typeCheckAndRequireBoolean(ctx, expr.Right, "OR argument")
if err != nil {
return nil, err
}
expr.Left, expr.Right = leftTyped, rightTyped
expr.typ = TypeBool
return expr, nil
}
// TypeCheck implements the Expr interface.
func (expr *ParenExpr) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
exprTyped, err := expr.Expr.TypeCheck(ctx, desired)
if err != nil {
return nil, err
}
expr.Expr = exprTyped
expr.typ = exprTyped.ResolvedType()
return expr, nil
}
// presetTypesForTesting is a mapping of qualified names to types that can be mocked out
// for tests to allow the qualified names to be type checked without throwing an error.
var presetTypesForTesting map[string]Type
func mockNameTypes(types map[string]Type) func() {
presetTypesForTesting = types
return func() {
presetTypesForTesting = nil
}
}
// TypeCheck implements the Expr interface. This function has a valid
// implementation only for testing within this package. During query
// execution, ColumnItems are replaced to IndexedVars prior to type
// checking.
func (expr *ColumnItem) TypeCheck(_ *SemaContext, desired Type) (TypedExpr, error) {
name := expr.String()
if _, ok := presetTypesForTesting[name]; ok {
return expr, nil
}
return nil, fmt.Errorf("name \"%s\" is not defined", name)
}
// TypeCheck implements the Expr interface.
func (expr UnqualifiedStar) TypeCheck(_ *SemaContext, desired Type) (TypedExpr, error) {
return nil, errors.New("cannot use \"*\" in this context")
}
// TypeCheck implements the Expr interface.
func (expr UnresolvedName) TypeCheck(s *SemaContext, desired Type) (TypedExpr, error) {
v, err := expr.NormalizeVarName()
if err != nil {
return nil, err
}
return v.TypeCheck(s, desired)
}
// TypeCheck implements the Expr interface.
func (expr *AllColumnsSelector) TypeCheck(_ *SemaContext, desired Type) (TypedExpr, error) {
return nil, fmt.Errorf("cannot use %q in this context", expr)
}
// TypeCheck implements the Expr interface.
func (expr *RangeCond) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
leftTyped, fromTyped, _, err := typeCheckComparisonOp(ctx, GT, expr.Left, expr.From)
if err != nil {
return nil, err
}
_, toTyped, _, err := typeCheckComparisonOp(ctx, LT, expr.Left, expr.To)
if err != nil {
return nil, err
}
expr.Left, expr.From, expr.To = leftTyped, fromTyped, toTyped
expr.typ = TypeBool
return expr, nil
}
// TypeCheck implements the Expr interface.
func (expr *Subquery) TypeCheck(_ *SemaContext, desired Type) (TypedExpr, error) {
panic("subquery nodes must be replaced before type checking")
}
// TypeCheck implements the Expr interface.
func (expr *UnaryExpr) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
ops := UnaryOps[expr.Operator]
overloads := make([]overloadImpl, len(ops))
for i := range ops {
overloads[i] = ops[i]
}
typedSubExprs, fn, err := typeCheckOverloadedExprs(ctx, desired, overloads, expr.Expr)
if err != nil {
return nil, err
}
exprTyped := typedSubExprs[0]
exprReturn := exprTyped.ResolvedType()
if exprReturn == TypeNull {
return DNull, nil
}
if fn == nil {
var desStr string
if desired != TypeAny {
desStr = fmt.Sprintf(" (desired <%s>)", desired)
}
return nil, fmt.Errorf("unsupported unary operator: %s <%s>%s",
expr.Operator, exprReturn, desStr)
}
expr.Expr = exprTyped
expr.fn = fn.(UnaryOp)
expr.typ = fn.returnType()(typedSubExprs)
return expr, nil
}
var errInvalidDefaultUsage = errors.New("DEFAULT can only appear in a VALUES list within INSERT or on the right side of a SET within UPDATE")
// TypeCheck implements the Expr interface.
func (expr DefaultVal) TypeCheck(_ *SemaContext, desired Type) (TypedExpr, error) {
return nil, errInvalidDefaultUsage
}
// TypeCheck implements the Expr interface.
func (expr *NumVal) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
return typeCheckConstant(expr, ctx, desired)
}
// TypeCheck implements the Expr interface.
func (expr *StrVal) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
return typeCheckConstant(expr, ctx, desired)
}
// TypeCheck implements the Expr interface.
func (expr *Tuple) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
expr.types = make(TTuple, len(expr.Exprs))
for i, subExpr := range expr.Exprs {
desiredElem := TypeAny
if t, ok := desired.(TTuple); ok && len(t) > i {
desiredElem = t[i]
}
typedExpr, err := subExpr.TypeCheck(ctx, desiredElem)
if err != nil {
return nil, err
}
expr.Exprs[i] = typedExpr
expr.types[i] = typedExpr.ResolvedType()
}
return expr, nil
}
var errAmbiguousArrayType = errors.Errorf("cannot determine type of empty array. " +
"Consider annotating with the desired type, for example ARRAY[]:::int[]")
// TypeCheck implements the Expr interface.
func (expr *Array) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
desiredParam := TypeAny
if arr, ok := desired.(TArray); ok {
desiredParam = arr.Typ
}
if len(expr.Exprs) == 0 {
if desiredParam == TypeAny {
return nil, errAmbiguousArrayType
}
expr.typ = TArray{desiredParam}
return expr, nil
}
typedSubExprs, typ, err := typeCheckSameTypedExprs(ctx, desiredParam, expr.Exprs...)
if err != nil {
return nil, err
}
expr.typ = TArray{typ}
for i := range typedSubExprs {
expr.Exprs[i] = typedSubExprs[i]
}
return expr, nil
}
// TypeCheck implements the Expr interface.
func (expr *ArrayFlatten) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
desiredParam := TypeAny
if arr, ok := desired.(TArray); ok {
desiredParam = arr.Typ
}
subqueryTyped, err := expr.Subquery.TypeCheck(ctx, desiredParam)
if err != nil {
return nil, err
}
expr.Subquery = subqueryTyped
subqueryType := subqueryTyped.ResolvedType()
switch subqueryType {
case TypeInt:
expr.typ = TypeIntArray
case TypeString:
expr.typ = TypeStringArray
default:
return nil, errors.Errorf("unhandled parameterized array type %T", subqueryType)
}
return expr, nil
}
// TypeCheck implements the Expr interface.
func (expr *Placeholder) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
// If there is a value known already, immediately substitute with it.
if v, ok := ctx.Placeholders.Value(expr.Name); ok {
return v, nil
}
// Otherwise, perform placeholder typing.
if typ, ok := ctx.Placeholders.Type(expr.Name); ok {
expr.typ = typ
return expr, nil
}
if desired.IsAmbiguous() {
return nil, placeholderTypeAmbiguityError{expr}
}
if err := ctx.Placeholders.SetType(expr.Name, desired); err != nil {
return nil, err
}
expr.typ = desired
return expr, nil
}
// TypeCheck implements the Expr interface. It is implemented as an idempotent
// identity function for Datum.
func (d *DBool) TypeCheck(_ *SemaContext, _ Type) (TypedExpr, error) { return d, nil }
// TypeCheck implements the Expr interface. It is implemented as an idempotent
// identity function for Datum.
func (d *DInt) TypeCheck(_ *SemaContext, _ Type) (TypedExpr, error) { return d, nil }
// TypeCheck implements the Expr interface. It is implemented as an idempotent
// identity function for Datum.
func (d *DFloat) TypeCheck(_ *SemaContext, _ Type) (TypedExpr, error) { return d, nil }
// TypeCheck implements the Expr interface. It is implemented as an idempotent
// identity function for Datum.
func (d *DDecimal) TypeCheck(_ *SemaContext, _ Type) (TypedExpr, error) { return d, nil }
// TypeCheck implements the Expr interface. It is implemented as an idempotent
// identity function for Datum.
func (d *DString) TypeCheck(_ *SemaContext, _ Type) (TypedExpr, error) { return d, nil }
// TypeCheck implements the Expr interface. It is implemented as an idempotent
// identity function for Datum.
func (d *DCollatedString) TypeCheck(_ *SemaContext, _ Type) (TypedExpr, error) { return d, nil }
// TypeCheck implements the Expr interface. It is implemented as an idempotent
// identity function for Datum.
func (d *DBytes) TypeCheck(_ *SemaContext, _ Type) (TypedExpr, error) { return d, nil }
// TypeCheck implements the Expr interface. It is implemented as an idempotent
// identity function for Datum.
func (d *DDate) TypeCheck(_ *SemaContext, _ Type) (TypedExpr, error) { return d, nil }
// TypeCheck implements the Expr interface. It is implemented as an idempotent
// identity function for Datum.
func (d *DTimestamp) TypeCheck(_ *SemaContext, _ Type) (TypedExpr, error) { return d, nil }
// TypeCheck implements the Expr interface. It is implemented as an idempotent
// identity function for Datum.
func (d *DTimestampTZ) TypeCheck(_ *SemaContext, _ Type) (TypedExpr, error) { return d, nil }
// TypeCheck implements the Expr interface. It is implemented as an idempotent
// identity function for Datum.
func (d *DInterval) TypeCheck(_ *SemaContext, _ Type) (TypedExpr, error) { return d, nil }
// TypeCheck implements the Expr interface. It is implemented as an idempotent
// identity function for Datum.
func (d *DTuple) TypeCheck(_ *SemaContext, _ Type) (TypedExpr, error) { return d, nil }
// TypeCheck implements the Expr interface. It is implemented as an idempotent
// identity function for Datum.
func (d *DArray) TypeCheck(_ *SemaContext, _ Type) (TypedExpr, error) { return d, nil }
// TypeCheck implements the Expr interface. It is implemented as an idempotent
// identity function for Datum.
func (d *DTable) TypeCheck(_ *SemaContext, _ Type) (TypedExpr, error) { return d, nil }
// TypeCheck implements the Expr interface. It is implemented as an idempotent
// identity function for Datum.
func (d *DOid) TypeCheck(_ *SemaContext, _ Type) (TypedExpr, error) { return d, nil }
// TypeCheck implements the Expr interface. It is implemented as an idempotent
// identity function for Datum.
func (d *DOidWrapper) TypeCheck(_ *SemaContext, _ Type) (TypedExpr, error) { return d, nil }
// TypeCheck implements the Expr interface. It is implemented as an idempotent
// identity function for Datum.
func (d dNull) TypeCheck(_ *SemaContext, desired Type) (TypedExpr, error) { return d, nil }
func typeCheckAndRequireBoolean(ctx *SemaContext, expr Expr, op string) (TypedExpr, error) {
return typeCheckAndRequire(ctx, expr, TypeBool, op)
}
func typeCheckAndRequire(ctx *SemaContext, expr Expr, required Type, op string) (TypedExpr, error) {
typedExpr, err := expr.TypeCheck(ctx, required)
if err != nil {
return nil, err
}
if typ := typedExpr.ResolvedType(); !(typ == TypeNull || typ.Equivalent(required)) {
return nil, fmt.Errorf("incompatible %s type: %s", op, typ)
}
return typedExpr, nil
}
const (
unsupportedCompErrFmtWithTypes = "unsupported comparison operator: <%s> %s <%s>"
unsupportedCompErrFmtWithTypesAndSubOp = "unsupported comparison operator: <%s> %s %s <%s>"
unsupportedCompErrFmtWithExprs = "unsupported comparison operator: %s %s %s: %v"
unsupportedCompErrFmtWithExprsAndSubOp = "unsupported comparison operator: %s %s %s %s: %v"
)
func typeCheckComparisonOpWithSubOperator(
ctx *SemaContext, op, subOp ComparisonOperator, left, right Expr,
) (TypedExpr, TypedExpr, CmpOp, error) {
// Determine the set of comparisons are possible for the sub-operation,
// which will be memoized.
foldedOp, _, _, _, _ := foldComparisonExpr(subOp, nil, nil)
ops := CmpOps[foldedOp]
var cmpTypeLeft, cmpTypeRight Type
var leftTyped, rightTyped TypedExpr
if array, isConstructor := StripParens(right).(*Array); isConstructor {
// If the right expression is an (optionally nested) array constructor, we
// perform type inference on the array elements and the left expression.
sameTypeExprs := make([]Expr, len(array.Exprs)+1)
sameTypeExprs[0] = left
copy(sameTypeExprs[1:], array.Exprs)
typedSubExprs, retType, err := typeCheckSameTypedExprs(ctx, TypeAny, sameTypeExprs...)
if err != nil {
return nil, nil, CmpOp{}, fmt.Errorf(unsupportedCompErrFmtWithExprsAndSubOp,
left, op, subOp, right, err)
}
// Determine TypedExpr and comparison type for left operand.
leftTyped = typedSubExprs[0]
cmpTypeLeft = retType
// Determine TypedExpr and comparison type for right operand, making sure
// all ParenExprs on the right are properly type checked.
for i, typedExpr := range typedSubExprs[1:] {
array.Exprs[i] = typedExpr
}
array.typ = TArray{retType}
rightParen := right
for {
if p, ok := rightParen.(*ParenExpr); ok {
p.typ = array.typ
rightParen = p.Expr
continue
}
break
}
rightTyped = right.(TypedExpr)
cmpTypeRight = retType
// Return early without looking up a CmpOp if the comparison type is TypeNull.
if retType == TypeNull {
return leftTyped, rightTyped, CmpOp{}, nil
}
} else {
// If the right expression is not an array constructor, we type the left
// expression in isolation.
var err error
leftTyped, err = left.TypeCheck(ctx, TypeAny)
if err != nil {
return nil, nil, CmpOp{}, err
}
cmpTypeLeft = leftTyped.ResolvedType()
// We then type the right expression desiring an array of the left's type.
rightTyped, err = right.TypeCheck(ctx, TArray{cmpTypeLeft})
if err != nil {
return nil, nil, CmpOp{}, err
}
rightReturn := rightTyped.ResolvedType()
if cmpTypeLeft == TypeNull || rightReturn == TypeNull {
return leftTyped, rightTyped, CmpOp{}, nil
}
rightArr, ok := UnwrapType(rightReturn).(TArray)
if !ok {
return nil, nil, CmpOp{},
errors.Errorf(unsupportedCompErrFmtWithExprsAndSubOp, left, subOp, op, right,
fmt.Sprintf("op %s array requires array on right side", op))
}
cmpTypeRight = rightArr.Typ
}
fn, ok := ops.lookupImpl(cmpTypeLeft, cmpTypeRight)
if !ok {
return nil, nil, CmpOp{}, fmt.Errorf(unsupportedCompErrFmtWithTypesAndSubOp,
cmpTypeLeft, subOp, op, TArray{cmpTypeRight})
}
return leftTyped, rightTyped, fn, nil
}
func typeCheckComparisonOp(
ctx *SemaContext, op ComparisonOperator, left, right Expr,
) (TypedExpr, TypedExpr, CmpOp, error) {
foldedOp, foldedLeft, foldedRight, switched, _ := foldComparisonExpr(op, left, right)
ops := CmpOps[foldedOp]
_, leftIsTuple := foldedLeft.(*Tuple)
rightTuple, rightIsTuple := foldedRight.(*Tuple)
switch {
case foldedOp == In && rightIsTuple:
sameTypeExprs := make([]Expr, len(rightTuple.Exprs)+1)
sameTypeExprs[0] = foldedLeft
copy(sameTypeExprs[1:], rightTuple.Exprs)
typedSubExprs, retType, err := typeCheckSameTypedExprs(ctx, TypeAny, sameTypeExprs...)
if err != nil {
return nil, nil, CmpOp{}, fmt.Errorf(unsupportedCompErrFmtWithExprs,
left, op, right, err)
}
fn, ok := ops.lookupImpl(retType, TypeTuple)
if !ok {
return nil, nil, CmpOp{}, fmt.Errorf(unsupportedCompErrFmtWithTypes, retType, op, TypeTuple)
}
typedLeft := typedSubExprs[0]
typedSubExprs = typedSubExprs[1:]
rightTuple.types = make(TTuple, len(typedSubExprs))
for i, typedExpr := range typedSubExprs {
rightTuple.Exprs[i] = typedExpr
rightTuple.types[i] = retType
}
if switched {
return rightTuple, typedLeft, fn, nil
}
return typedLeft, rightTuple, fn, nil
case leftIsTuple && rightIsTuple:
fn, ok := ops.lookupImpl(TypeTuple, TypeTuple)
if !ok {
return nil, nil, CmpOp{}, fmt.Errorf(unsupportedCompErrFmtWithTypes, TypeTuple, op, TypeTuple)
}
// Using non-folded left and right to avoid having to swap later.
typedLeft, typedRight, err := typeCheckTupleComparison(ctx, op, left.(*Tuple), right.(*Tuple))
if err != nil {
return nil, nil, CmpOp{}, err
}
return typedLeft, typedRight, fn, nil
}
overloads := make([]overloadImpl, len(ops))
for i := range ops {
overloads[i] = ops[i]
}
typedSubExprs, fn, err := typeCheckOverloadedExprs(ctx, TypeAny, overloads, foldedLeft, foldedRight)
if err != nil {
return nil, nil, CmpOp{}, err
}
leftExpr, rightExpr := typedSubExprs[0], typedSubExprs[1]
if switched {
leftExpr, rightExpr = rightExpr, leftExpr
}
leftReturn := leftExpr.ResolvedType()
rightReturn := rightExpr.ResolvedType()
if leftReturn == TypeNull || rightReturn == TypeNull {
switch op {