-
Notifications
You must be signed in to change notification settings - Fork 0
/
type_check.go
1552 lines (1386 loc) · 51.1 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.
package parser
import (
"fmt"
"strings"
"time"
"golang.org/x/text/language"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"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 errors.Wrapf(err, format, a...)
}
// 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]
typedSubExprs, fns, err := typeCheckOverloadedExprs(ctx, desired, ops, true, expr.Left, expr.Right)
if err != nil {
return nil, err
}
leftTyped, rightTyped := typedSubExprs[0], typedSubExprs[1]
leftReturn := leftTyped.ResolvedType()
rightReturn := rightTyped.ResolvedType()
// Return NULL if at least one overload is possible, NULL is an argument,
// and none of the overloads accept NULL.
if leftReturn == TypeNull || rightReturn == TypeNull {
if len(fns) > 0 {
noneAcceptNull := true
for _, e := range fns {
if e.(BinOp).nullableArgs {
noneAcceptNull = false
break
}
}
if noneAcceptNull {
return DNull, nil
}
}
}
// Throw a typing error if overload resolution found either no compatible candidates
// or if it found an ambiguity.
if len(fns) != 1 {
var desStr string
if desired != TypeAny {
desStr = fmt.Sprintf(" (desired <%s>)", desired)
}
sig := fmt.Sprintf("<%s> %s <%s>%s", leftReturn, expr.Operator, rightReturn, desStr)
if len(fns) == 0 {
return nil,
pgerror.NewErrorf(pgerror.CodeInvalidParameterValueError, unsupportedBinaryOpErrFmt, sig)
}
fnsStr := formatCandidates(expr.Operator.String(), fns)
return nil,
pgerror.NewErrorf(pgerror.CodeAmbiguousFunctionError,
ambiguousBinaryOpErrFmt, sig).SetHintf(candidatesHintFmt, fnsStr)
}
binOp := fns[0].(BinOp)
expr.Left, expr.Right = leftTyped, rightTyped
expr.fn = binOp
expr.typ = binOp.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, pgerror.NewErrorf(pgerror.CodeCannotCoerceError, "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, pgerror.UnimplementedWithIssueErrorf(2115, "ARRAY slicing in %s", expr)
}
if i > 0 {
return nil, pgerror.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, pgerror.NewErrorf(pgerror.CodeDatatypeMismatchError, "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, pgerror.NewErrorf(pgerror.CodeDatatypeMismatchError, "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
}
switch expr.Operator {
case Is, IsNot, IsDistinctFrom, IsNotDistinctFrom:
// These operators handle NULL arguments, so they do not result in an
// evaluation directly to NULL in the presence of any NULL arguments.
//
// TODO(pmattis): For IS {UNKNOWN,TRUE,FALSE} we should be requiring that
// TypeLeft.TypeEquals(TypeBool). We currently can't distinguish NULL from
// UNKNOWN. Is it important to do so?
default:
// Return NULL if at least one overload is possible and NULL is an argument.
if leftTyped.ResolvedType() == TypeNull || rightTyped.ResolvedType() == TypeNull {
return DNull, nil
}
}
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
}
typedSubExprs, fns, err := typeCheckOverloadedExprs(ctx, desired, def.Definition, false, expr.Exprs...)
if err != nil {
return nil, errors.Wrapf(err, "%s()", def.Name)
}
// Return NULL if at least one overload is possible and NULL is an argument.
if len(fns) > 0 {
// However, if any of the possible candidate functions can handle NULL
// arguments, we don't want to take the NULL argument fast-path.
handledNull := false
for _, fn := range fns {
if fn.(Builtin).nullableArgs {
handledNull = true
break
}
}
if !handledNull {
for _, expr := range typedSubExprs {
if expr.ResolvedType() == TypeNull {
return DNull, nil
}
}
}
}
// Throw a typing error if overload resolution found either no compatible candidates
// or if it found an ambiguity.
// TODO(nvanbenschoten): now that we can distinguish these, we can improve the
// error message the two report (e.g. "add casts please")
if len(fns) != 1 {
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)
}
sig := fmt.Sprintf("%s(%s)%s", expr.Func, strings.Join(typeNames, ", "), desStr)
if len(fns) == 0 {
return nil, pgerror.NewErrorf(pgerror.CodeUndefinedFunctionError, "unknown signature: %s", sig)
}
fnsStr := formatCandidates(expr.Func.String(), fns)
return nil, pgerror.NewErrorf(pgerror.CodeAmbiguousFunctionError, "ambiguous call: %s, candidates are:\n%s", sig, fnsStr)
}
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 {
if orderBy.OrderType != OrderByColumn {
return nil, errors.New("ORDER BY INDEX in window definition is not supported")
}
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 := fns[0].(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, pgerror.NewErrorf(pgerror.CodeWrongObjectTypeError, "OVER specified, but %s() is neither a window function nor an "+
"aggregate function", expr.Func)
}
if expr.Filter != nil {
return nil, pgerror.NewErrorf(pgerror.CodeFeatureNotSupportedError, "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, pgerror.NewErrorf(pgerror.CodeWrongObjectTypeError, "window function %s() requires an OVER clause", expr.Func)
}
}
if expr.Filter != nil {
if builtin.class != AggregateClass {
// Same error message as Postgres.
return nil, pgerror.NewErrorf(pgerror.CodeWrongObjectTypeError, "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, pgerror.NewErrorf(pgerror.CodeInternalError, "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, pgerror.NewErrorf(pgerror.CodeSyntaxError, "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]
typedSubExprs, fns, err := typeCheckOverloadedExprs(ctx, desired, ops, false, expr.Expr)
if err != nil {
return nil, err
}
exprTyped := typedSubExprs[0]
exprReturn := exprTyped.ResolvedType()
// Return NULL if at least one overload is possible and NULL is an argument.
if len(fns) > 0 {
if exprReturn == TypeNull {
return DNull, nil
}
}
// Throw a typing error if overload resolution found either no compatible candidates
// or if it found an ambiguity.
if len(fns) != 1 {
var desStr string
if desired != TypeAny {
desStr = fmt.Sprintf(" (desired <%s>)", desired)
}
sig := fmt.Sprintf("%s <%s>%s", expr.Operator, exprReturn, desStr)
if len(fns) == 0 {
return nil,
pgerror.NewErrorf(pgerror.CodeInvalidParameterValueError, unsupportedUnaryOpErrFmt, sig)
}
fnsStr := formatCandidates(expr.Operator.String(), fns)
return nil, pgerror.NewErrorf(pgerror.CodeAmbiguousFunctionError,
ambiguousUnaryOpErrFmt, sig).SetHintf(candidatesHintFmt, fnsStr)
}
unaryOp := fns[0].(UnaryOp)
expr.Expr = exprTyped
expr.fn = unaryOp
expr.typ = unaryOp.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")
// 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 = pgerror.NewErrorf(pgerror.CodeIndeterminateDatatypeError, "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
expr.typ = TArray{subqueryTyped.ResolvedType()}
return expr, nil
}
// TypeCheck implements the Expr interface.
func (expr *Placeholder) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
// Perform placeholder typing. This function is only called during Prepare,
// when there are no available values for the placeholders yet, because
// during Execute all placeholders are replaced from the AST before type
// checking.
if typ, ok := ctx.Placeholders.Type(expr.Name, true); ok {
if !desired.Equivalent(typ) {
// This indicates there's a conflict between what the type system thinks
// the type for this position should be, and the actual type of the
// placeholder. This actual placeholder type could be either a type hint
// (from pgwire or from a SQL PREPARE), or the actual value type.
//
// To resolve this situation, we *override* the placeholder type with what
// the type system expects. Then, when the value is actually sent to us
// later, we cast the input value (whose type is the expected type) to the
// desired type here.
typ = desired
}
// We call SetType regardless of the above condition to inform the
// placeholder struct that this placeholder is locked to its type and cannot
// be overridden again.
if err := ctx.Placeholders.SetType(expr.Name, typ); err != nil {
return nil, err
}
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 *DUuid) 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, pgerror.NewErrorf(pgerror.CodeDatatypeMismatchError, "incompatible %s type: %s", op, typ)
}
return typedExpr, nil
}
const (
compSignatureFmt = "<%s> %s <%s>"
compSignatureWithSubOpFmt = "<%s> %s %s <%s>"
compExprsFmt = "%s %s %s: %v"
compExprsWithSubOpFmt = "%s %s %s %s: %v"
unsupportedCompErrFmt = "unsupported comparison operator: %s"
unsupportedUnaryOpErrFmt = "unsupported unary operator: %s"
unsupportedBinaryOpErrFmt = "unsupported binary operator: %s"
ambiguousCompErrFmt = "ambiguous comparison operator: %s"
ambiguousUnaryOpErrFmt = "ambiguous unary operator: %s"
ambiguousBinaryOpErrFmt = "ambiguous binary operator: %s"
candidatesHintFmt = "candidates are:\n%s"
)
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 {
sigWithErr := fmt.Sprintf(compExprsWithSubOpFmt, left, op, subOp, right, err)
return nil, nil, CmpOp{},
pgerror.NewErrorf(pgerror.CodeInvalidParameterValueError, unsupportedCompErrFmt, sigWithErr)
}
// 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 {