-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
expr.go
1299 lines (1129 loc) · 35.6 KB
/
expr.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: Peter Mattis ([email protected])
package parser
import (
"bytes"
"fmt"
)
// Expr represents an expression.
type Expr interface {
fmt.Stringer
NodeFormatter
// Walk recursively walks all children using WalkExpr. If any children are changed, it returns a
// copy of this node updated to point to the new children. Otherwise the receiver is returned.
// For childless (leaf) Exprs, its implementation is empty.
Walk(Visitor) Expr
// TypeCheck transforms the Expr into a well-typed TypedExpr, which further permits
// evaluation and type introspection, or an error if the expression cannot be well-typed.
// When type checking is complete, if no error was reported, the expression and all
// sub-expressions will be guaranteed to be well-typed, meaning that the method effectively
// maps the Expr tree into a TypedExpr tree.
//
// The ctx parameter defines the context in which to perform type checking.
// The desired parameter hints the desired type that the method's caller wants from
// the resulting TypedExpr.
TypeCheck(ctx *SemaContext, desired Datum) (TypedExpr, error)
}
// TypedExpr represents a well-typed expression.
type TypedExpr interface {
Expr
// Eval evaluates an SQL expression. Expression evaluation is a mostly
// straightforward walk over the parse tree. The only significant complexity is
// the handling of types and implicit conversions. See binOps and cmpOps for
// more details. Note that expression evaluation returns an error if certain
// node types are encountered: Placeholder, QualifiedName or Subquery. These nodes
// should be replaced prior to expression evaluation by an appropriate
// WalkExpr. For example, Placeholder should be replace by the argument passed from
// the client.
Eval(*EvalContext) (Datum, error)
// ReturnType provides the type of the TypedExpr, which is the type of Datum that
// the TypedExpr will return when evaluated.
ReturnType() Datum
}
// VariableExpr is an Expr that may change per row. It is used to
// signal the evaluation/simplification machinery that the underlying
// Expr is not constant.
type VariableExpr interface {
Expr
Variable()
}
// operatorExpr is used to identify expression types that involve operators;
// used by exprStrWithParen.
type operatorExpr interface {
Expr
operatorExpr()
}
var _ operatorExpr = &AndExpr{}
var _ operatorExpr = &OrExpr{}
var _ operatorExpr = &NotExpr{}
var _ operatorExpr = &BinaryExpr{}
var _ operatorExpr = &UnaryExpr{}
var _ operatorExpr = &ComparisonExpr{}
var _ operatorExpr = &RangeCond{}
var _ operatorExpr = &IsOfTypeExpr{}
// exprFmtWithParen is a variant of Format() which adds a set of outer parens
// if the expression involves an operator. It is used internally when the
// expression is part of another expression and we know it is preceded or
// followed by an operator.
func exprFmtWithParen(buf *bytes.Buffer, f FmtFlags, e Expr) {
if _, ok := e.(operatorExpr); ok {
buf.WriteByte('(')
FormatNode(buf, f, e)
buf.WriteByte(')')
} else {
FormatNode(buf, f, e)
}
}
// typeAnnotation is an embeddable struct to provide a TypedExpr with a dynamic
// type annotation.
type typeAnnotation struct {
typ Datum
}
func (ta typeAnnotation) ReturnType() Datum {
ta.assertTyped()
return ta.typ
}
func (ta typeAnnotation) assertTyped() {
if ta.typ == nil {
panic("ReturnType called on TypedExpr with empty typeAnnotation. " +
"Was the underlying Expr type-checked before asserting a type of TypedExpr?")
}
}
// AndExpr represents an AND expression.
type AndExpr struct {
Left, Right Expr
typeAnnotation
}
func (*AndExpr) operatorExpr() {}
func binExprFmtWithParen(buf *bytes.Buffer, f FmtFlags, e1 Expr, op string, e2 Expr) {
exprFmtWithParen(buf, f, e1)
buf.WriteByte(' ')
buf.WriteString(op)
buf.WriteByte(' ')
exprFmtWithParen(buf, f, e2)
}
// Format implements the NodeFormatter interface.
func (node *AndExpr) Format(buf *bytes.Buffer, f FmtFlags) {
binExprFmtWithParen(buf, f, node.Left, "AND", node.Right)
}
// NewTypedAndExpr returns a new AndExpr that is verified to be well-typed.
func NewTypedAndExpr(left, right TypedExpr) *AndExpr {
node := &AndExpr{Left: left, Right: right}
node.typ = TypeBool
return node
}
// TypedLeft returns the AndExpr's left expression as a TypedExpr.
func (node *AndExpr) TypedLeft() TypedExpr {
return node.Left.(TypedExpr)
}
// TypedRight returns the AndExpr's right expression as a TypedExpr.
func (node *AndExpr) TypedRight() TypedExpr {
return node.Right.(TypedExpr)
}
// OrExpr represents an OR expression.
type OrExpr struct {
Left, Right Expr
typeAnnotation
}
func (*OrExpr) operatorExpr() {}
// Format implements the NodeFormatter interface.
func (node *OrExpr) Format(buf *bytes.Buffer, f FmtFlags) {
binExprFmtWithParen(buf, f, node.Left, "OR", node.Right)
}
// NewTypedOrExpr returns a new OrExpr that is verified to be well-typed.
func NewTypedOrExpr(left, right TypedExpr) *OrExpr {
node := &OrExpr{Left: left, Right: right}
node.typ = TypeBool
return node
}
// TypedLeft returns the OrExpr's left expression as a TypedExpr.
func (node *OrExpr) TypedLeft() TypedExpr {
return node.Left.(TypedExpr)
}
// TypedRight returns the OrExpr's right expression as a TypedExpr.
func (node *OrExpr) TypedRight() TypedExpr {
return node.Right.(TypedExpr)
}
// NotExpr represents a NOT expression.
type NotExpr struct {
Expr Expr
typeAnnotation
}
func (*NotExpr) operatorExpr() {}
// Format implements the NodeFormatter interface.
func (node *NotExpr) Format(buf *bytes.Buffer, f FmtFlags) {
buf.WriteString("NOT ")
exprFmtWithParen(buf, f, node.Expr)
}
// NewTypedNotExpr returns a new NotExpr that is verified to be well-typed.
func NewTypedNotExpr(expr TypedExpr) *NotExpr {
node := &NotExpr{Expr: expr}
node.typ = TypeBool
return node
}
// TypedInnerExpr returns the NotExpr's inner expression as a TypedExpr.
func (node *NotExpr) TypedInnerExpr() TypedExpr {
return node.Expr.(TypedExpr)
}
// ParenExpr represents a parenthesized expression.
type ParenExpr struct {
Expr Expr
typeAnnotation
}
// Format implements the NodeFormatter interface.
func (node *ParenExpr) Format(buf *bytes.Buffer, f FmtFlags) {
buf.WriteByte('(')
FormatNode(buf, f, node.Expr)
buf.WriteByte(')')
}
// TypedInnerExpr returns the ParenExpr's inner expression as a TypedExpr.
func (node *ParenExpr) TypedInnerExpr() TypedExpr {
return node.Expr.(TypedExpr)
}
// StripParens strips any parentheses surrounding an expression and
// returns the inner expression. For instance:
// 1 -> 1
// (1) -> 1
// ((1)) -> 1
func StripParens(expr Expr) Expr {
if p, ok := expr.(*ParenExpr); ok {
return StripParens(p.Expr)
}
return expr
}
// ComparisonOperator represents a binary operator.
type ComparisonOperator int
// ComparisonExpr.Operator
const (
EQ ComparisonOperator = iota
LT
GT
LE
GE
NE
In
NotIn
Like
NotLike
ILike
NotILike
SimilarTo
NotSimilarTo
IsDistinctFrom
IsNotDistinctFrom
Is
IsNot
)
var comparisonOpName = [...]string{
EQ: "=",
LT: "<",
GT: ">",
LE: "<=",
GE: ">=",
NE: "!=",
In: "IN",
NotIn: "NOT IN",
Like: "LIKE",
NotLike: "NOT LIKE",
ILike: "ILIKE",
NotILike: "NOT ILIKE",
SimilarTo: "SIMILAR TO",
NotSimilarTo: "NOT SIMILAR TO",
IsDistinctFrom: "IS DISTINCT FROM",
IsNotDistinctFrom: "IS NOT DISTINCT FROM",
Is: "IS",
IsNot: "IS NOT",
}
func (i ComparisonOperator) String() string {
if i < 0 || i > ComparisonOperator(len(comparisonOpName)-1) {
return fmt.Sprintf("ComparisonOp(%d)", i)
}
return comparisonOpName[i]
}
// ComparisonExpr represents a two-value comparison expression.
type ComparisonExpr struct {
Operator ComparisonOperator
Left, Right Expr
typeAnnotation
fn CmpOp
}
func (*ComparisonExpr) operatorExpr() {}
// Format implements the NodeFormatter interface.
func (node *ComparisonExpr) Format(buf *bytes.Buffer, f FmtFlags) {
binExprFmtWithParen(buf, f, node.Left, node.Operator.String(), node.Right)
}
// NewTypedComparisonExpr returns a new ComparisonExpr that is verified to be well-typed.
func NewTypedComparisonExpr(op ComparisonOperator, left, right TypedExpr) *ComparisonExpr {
node := &ComparisonExpr{Operator: op, Left: left, Right: right}
node.typ = TypeBool
node.memoizeFn()
return node
}
func (node *ComparisonExpr) memoizeFn() {
switch node.Operator {
case Is, IsNot, IsDistinctFrom, IsNotDistinctFrom:
return
}
fOp, fLeft, fRight, _, _ := foldComparisonExpr(node.Operator, node.Left, node.Right)
leftRet, rightRet := fLeft.(TypedExpr).ReturnType(), fRight.(TypedExpr).ReturnType()
fn, ok := CmpOps[fOp].lookupImpl(leftRet, rightRet)
if !ok {
panic(fmt.Sprintf("lookup for ComparisonExpr %s's CmpOp failed",
AsStringWithFlags(node, FmtShowTypes)))
}
node.fn = fn
}
// TypedLeft returns the ComparisonExpr's left expression as a TypedExpr.
func (node *ComparisonExpr) TypedLeft() TypedExpr {
return node.Left.(TypedExpr)
}
// TypedRight returns the ComparisonExpr's right expression as a TypedExpr.
func (node *ComparisonExpr) TypedRight() TypedExpr {
return node.Right.(TypedExpr)
}
// IsMixedTypeComparison returns true when the two sides of
// a comparison operator have different types.
func (node *ComparisonExpr) IsMixedTypeComparison() bool {
switch node.Operator {
case In, NotIn:
tuple := *node.Right.(*DTuple)
for _, expr := range tuple {
if !sameTypeExprs(node.TypedLeft(), expr.(TypedExpr)) {
return true
}
}
return false
default:
return !sameTypeExprs(node.TypedLeft(), node.TypedRight())
}
}
func sameTypeExprs(left, right TypedExpr) bool {
leftType := left.ReturnType()
if leftType == DNull {
return true
}
rightType := right.ReturnType()
if rightType == DNull {
return true
}
return leftType.TypeEqual(rightType)
}
// RangeCond represents a BETWEEN or a NOT BETWEEN expression.
type RangeCond struct {
Not bool
Left Expr
From, To Expr
typeAnnotation
}
func (*RangeCond) operatorExpr() {}
// Format implements the NodeFormatter interface.
func (node *RangeCond) Format(buf *bytes.Buffer, f FmtFlags) {
notStr := " BETWEEN "
if node.Not {
notStr = " NOT BETWEEN "
}
exprFmtWithParen(buf, f, node.Left)
buf.WriteString(notStr)
binExprFmtWithParen(buf, f, node.From, "AND", node.To)
}
// TypedLeft returns the RangeCond's left expression as a TypedExpr.
func (node *RangeCond) TypedLeft() TypedExpr {
return node.Left.(TypedExpr)
}
// TypedFrom returns the RangeCond's from expression as a TypedExpr.
func (node *RangeCond) TypedFrom() TypedExpr {
return node.From.(TypedExpr)
}
// TypedTo returns the RangeCond's to expression as a TypedExpr.
func (node *RangeCond) TypedTo() TypedExpr {
return node.To.(TypedExpr)
}
// IsOfTypeExpr represents an IS {,NOT} OF (type_list) expression.
type IsOfTypeExpr struct {
Not bool
Expr Expr
Types []ColumnType
typeAnnotation
}
func (*IsOfTypeExpr) operatorExpr() {}
// Format implements the NodeFormatter interface.
func (node *IsOfTypeExpr) Format(buf *bytes.Buffer, f FmtFlags) {
FormatNode(buf, f, node.Expr)
buf.WriteString(" IS")
if node.Not {
buf.WriteString(" NOT")
}
buf.WriteString(" OF (")
for i, t := range node.Types {
if i > 0 {
buf.WriteString(", ")
}
FormatNode(buf, f, t)
}
buf.WriteByte(')')
}
// ExistsExpr represents an EXISTS expression.
type ExistsExpr struct {
Subquery Expr
typeAnnotation
}
// Format implements the NodeFormatter interface.
func (node *ExistsExpr) Format(buf *bytes.Buffer, f FmtFlags) {
buf.WriteString("EXISTS ")
exprFmtWithParen(buf, f, node.Subquery)
}
// IfExpr represents an IF expression.
type IfExpr struct {
Cond Expr
True Expr
Else Expr
typeAnnotation
}
// TypedTrueExpr returns the IfExpr's True expression as a TypedExpr.
func (node *IfExpr) TypedTrueExpr() TypedExpr {
return node.True.(TypedExpr)
}
// TypedCondExpr returns the IfExpr's Cond expression as a TypedExpr.
func (node *IfExpr) TypedCondExpr() TypedExpr {
return node.Cond.(TypedExpr)
}
// TypedElseExpr returns the IfExpr's Else expression as a TypedExpr.
func (node *IfExpr) TypedElseExpr() TypedExpr {
return node.Else.(TypedExpr)
}
// Format implements the NodeFormatter interface.
func (node *IfExpr) Format(buf *bytes.Buffer, f FmtFlags) {
buf.WriteString("IF(")
FormatNode(buf, f, node.Cond)
buf.WriteString(", ")
FormatNode(buf, f, node.True)
buf.WriteString(", ")
FormatNode(buf, f, node.Else)
buf.WriteByte(')')
}
// NullIfExpr represents a NULLIF expression.
type NullIfExpr struct {
Expr1 Expr
Expr2 Expr
typeAnnotation
}
// Format implements the NodeFormatter interface.
func (node *NullIfExpr) Format(buf *bytes.Buffer, f FmtFlags) {
buf.WriteString("NULLIF(")
FormatNode(buf, f, node.Expr1)
buf.WriteString(", ")
FormatNode(buf, f, node.Expr2)
buf.WriteByte(')')
}
// CoalesceExpr represents a COALESCE or IFNULL expression.
type CoalesceExpr struct {
Name string
Exprs Exprs
typeAnnotation
}
// TypedExprAt returns the expression at the specified index as a TypedExpr.
func (node *CoalesceExpr) TypedExprAt(idx int) TypedExpr {
return node.Exprs[idx].(TypedExpr)
}
// Format implements the NodeFormatter interface.
func (node *CoalesceExpr) Format(buf *bytes.Buffer, f FmtFlags) {
buf.WriteString(node.Name)
buf.WriteByte('(')
FormatNode(buf, f, node.Exprs)
buf.WriteByte(')')
}
// DefaultVal represents the DEFAULT expression.
type DefaultVal struct{}
// Format implements the NodeFormatter interface.
func (node DefaultVal) Format(buf *bytes.Buffer, f FmtFlags) {
buf.WriteString("DEFAULT")
}
// ReturnType implements the TypedExpr interface.
func (DefaultVal) ReturnType() Datum { return nil }
var _ VariableExpr = Placeholder{}
// Placeholder represents a named placeholder.
type Placeholder struct {
Name string
}
// Variable implements the VariableExpr interface.
func (Placeholder) Variable() {}
// Format implements the NodeFormatter interface.
func (node Placeholder) Format(buf *bytes.Buffer, f FmtFlags) {
buf.WriteByte('$')
buf.WriteString(node.Name)
}
type nameType int
const (
_ nameType = iota
tableName
columnName
)
var _ VariableExpr = &QualifiedName{}
// QualifiedName is a base name and an optional indirection expression.
type QualifiedName struct {
Base Name
Indirect Indirection
normalized nameType
// We preserve the "original" string representation (before normalization).
origString string
}
// ReturnType implements the TypedExpr interface.
func (node *QualifiedName) ReturnType() Datum {
if qualifiedNameTypes == nil {
return nil
}
return qualifiedNameTypes[node.String()]
}
// Variable implements the VariableExpr interface.
func (*QualifiedName) Variable() {}
// StarExpr is a convenience function that represents an unqualified "*".
func StarExpr() *QualifiedName {
return &QualifiedName{Indirect: Indirection{unqualifiedStar}}
}
// NormalizeTableName normalizes the qualified name to contain a database name
// as prefix, returning an error if unable to do so or if the name is not a
// valid table name (e.g. it contains an array indirection). The incoming
// qualified name should have one of the following forms:
//
// table
// database.table
// table@index
// database.table@index
//
// On successful normalization, the qualified name will have the form:
//
// database.table@index
func (node *QualifiedName) NormalizeTableName(database string) error {
if node == nil || node.Base == "" {
return fmt.Errorf("empty table name: %s", node)
}
if node.normalized == columnName {
return fmt.Errorf("already normalized as a column name: %s", node)
}
if err := node.QualifyWithDatabase(database); err != nil {
return err
}
if len(node.Indirect) > 1 {
return fmt.Errorf("invalid table name: %s", node)
}
node.normalized = tableName
return nil
}
// QualifyWithDatabase adds an indirection for the database, if it's missing.
// It transforms:
// table -> database.table
// table@index -> database.table@index
// * -> database.*
func (node *QualifiedName) QualifyWithDatabase(database string) error {
node.setString()
if len(node.Indirect) == 0 {
if database == "" {
return fmt.Errorf("no database specified: %s", node)
}
// table -> database.table
if database == "" {
return fmt.Errorf("no database specified: %s", node)
}
node.Indirect = append(node.Indirect, NameIndirection(node.Base))
node.Base = Name(database)
node.normalized = tableName
return nil
}
switch node.Indirect[0].(type) {
case NameIndirection:
// Nothing to do.
case StarIndirection:
// * -> database.*
if node.Base != "" {
// nothing to do
return nil
}
if node.Base != "" {
node.Indirect = append(Indirection{NameIndirection(node.Base)}, node.Indirect...)
}
if database == "" {
return fmt.Errorf("no database specified: %s", node)
}
node.Base = Name(database)
}
return nil
}
// NormalizeColumnName normalizes the qualified name to contain a table name as
// prefix, returning an error if unable to do so or if the name is not a valid
// column name (e.g. it contains too many indirections). If normalization
// occurred, the modified qualified name will have n.Base == "" to indicate no
// explicit table was specified. The incoming qualified name should have one of
// the following forms:
//
// *
// table.*
// column
// column[array-indirection]
// table.column
// table.column[array-indirection]
//
// Note that "table" may be the empty string. On successful normalization the
// qualified name will have one of the forms:
//
// table.*
// table.column
// table.column[array-indirection]
func (node *QualifiedName) NormalizeColumnName() error {
if node == nil {
return fmt.Errorf("empty column name: %s", node)
}
if node.normalized == tableName {
return fmt.Errorf("already normalized as a table name: %s", node)
}
node.setString()
if len(node.Indirect) == 0 {
// column -> table.column
if node.Base == "" {
return fmt.Errorf("empty column name: %s", node)
}
node.Indirect = append(node.Indirect, NameIndirection(node.Base))
node.Base = ""
node.normalized = columnName
return nil
}
if len(node.Indirect) > 2 {
return fmt.Errorf("invalid column name: %s", node)
}
// Either table.column, table.*, column[array-indirection] or
// table.column[array-indirection].
switch node.Indirect[0].(type) {
case NameIndirection:
// Nothing to do.
case StarIndirection:
node.Indirect[0] = qualifiedStar
case *ArrayIndirection:
// column[array-indirection] -> "".column[array-indirection]
//
// Accomplished by prepending node.Base to the existing indirection and then
// clearing node.Base.
node.Indirect = append(Indirection{NameIndirection(node.Base)}, node.Indirect...)
node.Base = ""
default:
return fmt.Errorf("invalid column name: %s", node)
}
if len(node.Indirect) == 2 {
if _, ok := node.Indirect[1].(*ArrayIndirection); !ok {
return fmt.Errorf("invalid column name: %s", node)
}
}
node.normalized = columnName
return nil
}
// Database returns the database portion of the name. Note that the returned
// string is not quoted even if the name is a keyword.
func (node *QualifiedName) Database() string {
if node.normalized != tableName {
panic(fmt.Sprintf("%s is not a table name", node))
}
// The database portion of the name is n.Base.
return string(node.Base)
}
// Table returns the table portion of the name. Note that the returned string
// is not quoted even if the name is a keyword.
func (node *QualifiedName) Table() string {
if node.normalized != tableName && node.normalized != columnName {
panic(fmt.Sprintf("%s is not a table or column name", node))
}
if node.normalized == tableName {
return string(node.Indirect[0].(NameIndirection))
}
return string(node.Base)
}
// Column returns the column portion of the name. Note that the returned string
// is not quoted even if the name is a keyword.
func (node *QualifiedName) Column() string {
if node.normalized != columnName {
panic(fmt.Sprintf("%s is not a column name", node))
}
return string(node.Indirect[0].(NameIndirection))
}
// IsStar returns true iff the qualified name contains matches "".* or table.*.
func (node *QualifiedName) IsStar() bool {
if node.normalized != columnName {
panic(fmt.Sprintf("%s is not a column name", node))
}
if len(node.Indirect) != 1 {
return false
}
if _, ok := node.Indirect[0].(StarIndirection); !ok {
return false
}
return true
}
// ClearString causes String to return the current (possibly normalized) name instead of the
// original name (used for testing).
func (node *QualifiedName) ClearString() {
node.origString = ""
}
func (node *QualifiedName) setString() {
// We preserve the representation pre-normalization.
if node.origString != "" {
return
}
var buf bytes.Buffer
if node.Base == "" && len(node.Indirect) == 1 && node.Indirect[0] == unqualifiedStar {
FormatNode(&buf, FmtSimple, node.Indirect[0])
} else {
FormatNode(&buf, FmtSimple, node.Base)
FormatNode(&buf, FmtSimple, node.Indirect)
}
node.origString = buf.String()
}
// Format implements the NodeFormatter interface.
func (node *QualifiedName) Format(buf *bytes.Buffer, f FmtFlags) {
node.setString()
buf.WriteString(node.origString)
}
// QualifiedNames represents a command separated list (see the String method)
// of qualified names.
type QualifiedNames []*QualifiedName
// Format implements the NodeFormatter interface.
func (n QualifiedNames) Format(buf *bytes.Buffer, f FmtFlags) {
for i, e := range n {
if i > 0 {
buf.WriteString(", ")
}
FormatNode(buf, f, e)
}
}
// TableNameWithIndex represents a "table@index", used in statements that
// specifically refer to an index.
type TableNameWithIndex struct {
Table *QualifiedName
Index Name
}
// Format implements the NodeFormatter interface.
func (n *TableNameWithIndex) Format(buf *bytes.Buffer, f FmtFlags) {
FormatNode(buf, f, n.Table)
buf.WriteByte('@')
FormatNode(buf, f, n.Index)
}
// TableNameWithIndexList is a list of indexes.
type TableNameWithIndexList []*TableNameWithIndex
// Format implements the NodeFormatter interface.
func (n TableNameWithIndexList) Format(buf *bytes.Buffer, f FmtFlags) {
for i, e := range n {
if i > 0 {
buf.WriteString(", ")
}
FormatNode(buf, f, e)
}
}
// Tuple represents a parenthesized list of expressions.
type Tuple struct {
Exprs Exprs
row bool // indicates whether or not the tuple should be textually represented as a row.
types DTuple
}
// Format implements the NodeFormatter interface.
func (node *Tuple) Format(buf *bytes.Buffer, f FmtFlags) {
if node.row {
buf.WriteString("ROW")
}
buf.WriteByte('(')
FormatNode(buf, f, node.Exprs)
buf.WriteByte(')')
}
// ReturnType implements the TypedExpr interface.
func (node *Tuple) ReturnType() Datum {
return &node.types
}
// Array represents an array constructor.
type Array struct {
Exprs Exprs
}
// Format implements the NodeFormatter interface.
func (node *Array) Format(buf *bytes.Buffer, f FmtFlags) {
buf.WriteString("ARRAY[")
FormatNode(buf, f, node.Exprs)
buf.WriteByte(']')
}
// Exprs represents a list of value expressions. It's not a valid expression
// because it's not parenthesized.
type Exprs []Expr
// Format implements the NodeFormatter interface.
func (node Exprs) Format(buf *bytes.Buffer, f FmtFlags) {
for i, n := range node {
if i > 0 {
buf.WriteString(", ")
}
FormatNode(buf, f, n)
}
}
// TypedExprs represents a list of well-typed value expressions. It's not a valid expression
// because it's not parenthesized.
type TypedExprs []TypedExpr
func (node TypedExprs) String() string {
var prefix string
var buf bytes.Buffer
for _, n := range node {
fmt.Fprintf(&buf, "%s%s", prefix, n)
prefix = ", "
}
return buf.String()
}
// Subquery represents a subquery.
type Subquery struct {
Select SelectStatement
}
// Variable implements the VariableExpr interface.
func (*Subquery) Variable() {}
// Format implements the NodeFormatter interface.
func (node *Subquery) Format(buf *bytes.Buffer, f FmtFlags) {
FormatNode(buf, f, node.Select)
}
// ReturnType implements the TypedExpr interface.
func (node *Subquery) ReturnType() Datum {
return DNull
}
// BinaryOperator represents a binary operator.
type BinaryOperator int
// BinaryExpr.Operator
const (
Bitand BinaryOperator = iota
Bitor
Bitxor
Plus
Minus
Mult
Div
FloorDiv
Mod
Concat
LShift
RShift
)
var binaryOpName = [...]string{
Bitand: "&",
Bitor: "|",
Bitxor: "^",
Plus: "+",
Minus: "-",
Mult: "*",
Div: "/",
FloorDiv: "//",
Mod: "%",
Concat: "||",
LShift: "<<",
RShift: ">>",
}
func (i BinaryOperator) String() string {
if i < 0 || i > BinaryOperator(len(binaryOpName)-1) {
return fmt.Sprintf("BinaryOp(%d)", i)
}
return binaryOpName[i]
}
// BinaryExpr represents a binary value expression.
type BinaryExpr struct {
Operator BinaryOperator
Left, Right Expr
typeAnnotation
fn BinOp
}
// TypedLeft returns the BinaryExpr's left expression as a TypedExpr.
func (node *BinaryExpr) TypedLeft() TypedExpr {
return node.Left.(TypedExpr)
}
// TypedRight returns the BinaryExpr's right expression as a TypedExpr.
func (node *BinaryExpr) TypedRight() TypedExpr {
return node.Right.(TypedExpr)
}
func (*BinaryExpr) operatorExpr() {}
func (node *BinaryExpr) memoizeFn() {
leftRet, rightRet := node.Left.(TypedExpr).ReturnType(), node.Right.(TypedExpr).ReturnType()
fn, ok := BinOps[node.Operator].lookupImpl(leftRet, rightRet)
if !ok {
panic(fmt.Sprintf("lookup for BinaryExpr %s's BinOp failed",
AsStringWithFlags(node, FmtShowTypes)))
}
node.fn = fn
}
// newBinExprIfValidOverloads constructs a new BinaryExpr if and only
// if the pair of arguments have a valid implementation.
func newBinExprIfValidOverload(op BinaryOperator, left TypedExpr, right TypedExpr) *BinaryExpr {
leftRet, rightRet := left.ReturnType(), right.ReturnType()
fn, ok := BinOps[op].lookupImpl(leftRet, rightRet)
if ok {
expr := &BinaryExpr{