-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
ast_funcs.go
2364 lines (2135 loc) · 54.4 KB
/
ast_funcs.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 2019 The Vitess 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 sqlparser
import (
"encoding/hex"
"encoding/json"
"fmt"
"io"
"strconv"
"strings"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
"vitess.io/vitess/go/vt/vterrors"
"vitess.io/vitess/go/vt/log"
"vitess.io/vitess/go/sqltypes"
querypb "vitess.io/vitess/go/vt/proto/query"
)
// Walk calls postVisit on every node.
// If postVisit returns true, the underlying nodes
// are also visited. If it returns an error, walking
// is interrupted, and the error is returned.
func Walk(visit Visit, nodes ...SQLNode) error {
for _, node := range nodes {
err := VisitSQLNode(node, visit)
if err != nil {
return err
}
}
return nil
}
// Visit defines the signature of a function that
// can be used to postVisit all nodes of a parse tree.
// returning false on kontinue means that children will not be visited
// returning an error will abort the visitation and return the error
type Visit func(node SQLNode) (kontinue bool, err error)
// Append appends the SQLNode to the buffer.
func Append(buf *strings.Builder, node SQLNode) {
tbuf := &TrackedBuffer{
Builder: buf,
fast: true,
}
node.formatFast(tbuf)
}
// IndexColumn describes a column or expression in an index definition with optional length (for column)
type IndexColumn struct {
// Only one of Column or Expression can be specified
// Length is an optional field which is only applicable when Column is used
Column IdentifierCI
Length *Literal
Expression Expr
Direction OrderDirection
}
// LengthScaleOption is used for types that have an optional length
// and scale
type LengthScaleOption struct {
Length *Literal
Scale *Literal
}
// IndexOption is used for trailing options for indexes: COMMENT, KEY_BLOCK_SIZE, USING, WITH PARSER
type IndexOption struct {
Name string
Value *Literal
String string
}
// TableOption is used for create table options like AUTO_INCREMENT, INSERT_METHOD, etc
type TableOption struct {
Name string
Value *Literal
String string
Tables TableNames
CaseSensitive bool
}
// ColumnKeyOption indicates whether or not the given column is defined as an
// index element and contains the type of the option
type ColumnKeyOption int
const (
ColKeyNone ColumnKeyOption = iota
ColKeyPrimary
ColKeySpatialKey
ColKeyFulltextKey
ColKeyUnique
ColKeyUniqueKey
ColKey
)
// ReferenceAction indicates the action takes by a referential constraint e.g.
// the `CASCADE` in a `FOREIGN KEY .. ON DELETE CASCADE` table definition.
type ReferenceAction int
// These map to the SQL-defined reference actions.
// See https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html#foreign-keys-referential-actions
const (
// DefaultAction indicates no action was explicitly specified.
DefaultAction ReferenceAction = iota
Restrict
Cascade
NoAction
SetNull
SetDefault
)
// MatchAction indicates the type of match for a referential constraint, so
// a `MATCH FULL`, `MATCH SIMPLE` or `MATCH PARTIAL`.
type MatchAction int
const (
// DefaultAction indicates no action was explicitly specified.
DefaultMatch MatchAction = iota
Full
Partial
Simple
)
// ShowTablesOpt is show tables option
type ShowTablesOpt struct {
Full string
DbName string
Filter *ShowFilter
}
// ValType specifies the type for Literal.
type ValType int
// These are the possible Valtype values.
// HexNum represents a 0x... value. It cannot
// be treated as a simple value because it can
// be interpreted differently depending on the
// context.
const (
StrVal = ValType(iota)
IntVal
DecimalVal
FloatVal
HexNum
HexVal
BitVal
DateVal
TimeVal
TimestampVal
)
// queryOptimizerPrefix is the prefix of an optimizer hint comment.
const queryOptimizerPrefix = "/*+"
// AddColumn appends the given column to the list in the spec
func (ts *TableSpec) AddColumn(cd *ColumnDefinition) {
ts.Columns = append(ts.Columns, cd)
}
// AddIndex appends the given index to the list in the spec
func (ts *TableSpec) AddIndex(id *IndexDefinition) {
ts.Indexes = append(ts.Indexes, id)
}
// AddConstraint appends the given index to the list in the spec
func (ts *TableSpec) AddConstraint(cd *ConstraintDefinition) {
ts.Constraints = append(ts.Constraints, cd)
}
// DescribeType returns the abbreviated type information as required for
// describe table
func (ct *ColumnType) DescribeType() string {
buf := NewTrackedBuffer(nil)
buf.Myprintf("%s", ct.Type)
if ct.Length != nil && ct.Scale != nil {
buf.Myprintf("(%v,%v)", ct.Length, ct.Scale)
} else if ct.Length != nil {
buf.Myprintf("(%v)", ct.Length)
}
opts := make([]string, 0, 16)
if ct.Unsigned {
opts = append(opts, keywordStrings[UNSIGNED])
}
if ct.Zerofill {
opts = append(opts, keywordStrings[ZEROFILL])
}
if len(opts) != 0 {
buf.Myprintf(" %s", strings.Join(opts, " "))
}
return buf.String()
}
// SQLType returns the sqltypes type code for the given column
func (ct *ColumnType) SQLType() querypb.Type {
return SQLTypeToQueryType(ct.Type, ct.Unsigned)
}
func SQLTypeToQueryType(typeName string, unsigned bool) querypb.Type {
switch keywordVals[strings.ToLower(typeName)] {
case TINYINT:
if unsigned {
return sqltypes.Uint8
}
return sqltypes.Int8
case SMALLINT:
if unsigned {
return sqltypes.Uint16
}
return sqltypes.Int16
case MEDIUMINT:
if unsigned {
return sqltypes.Uint24
}
return sqltypes.Int24
case INT, INTEGER:
if unsigned {
return sqltypes.Uint32
}
return sqltypes.Int32
case BIGINT:
if unsigned {
return sqltypes.Uint64
}
return sqltypes.Int64
case BOOL, BOOLEAN:
return sqltypes.Uint8
case TEXT:
return sqltypes.Text
case TINYTEXT:
return sqltypes.Text
case MEDIUMTEXT:
return sqltypes.Text
case LONGTEXT:
return sqltypes.Text
case BLOB:
return sqltypes.Blob
case TINYBLOB:
return sqltypes.Blob
case MEDIUMBLOB:
return sqltypes.Blob
case LONGBLOB:
return sqltypes.Blob
case CHAR:
return sqltypes.Char
case VARCHAR:
return sqltypes.VarChar
case BINARY:
return sqltypes.Binary
case VARBINARY:
return sqltypes.VarBinary
case DATE:
return sqltypes.Date
case TIME:
return sqltypes.Time
case DATETIME:
return sqltypes.Datetime
case TIMESTAMP:
return sqltypes.Timestamp
case YEAR:
return sqltypes.Year
case FLOAT_TYPE, FLOAT4_TYPE:
return sqltypes.Float32
case DOUBLE, FLOAT8_TYPE:
return sqltypes.Float64
case DECIMAL, DECIMAL_TYPE:
return sqltypes.Decimal
case BIT:
return sqltypes.Bit
case ENUM:
return sqltypes.Enum
case SET:
return sqltypes.Set
case JSON:
return sqltypes.TypeJSON
case GEOMETRY:
return sqltypes.Geometry
case POINT:
return sqltypes.Geometry
case LINESTRING:
return sqltypes.Geometry
case POLYGON:
return sqltypes.Geometry
case GEOMETRYCOLLECTION:
return sqltypes.Geometry
case MULTIPOINT:
return sqltypes.Geometry
case MULTILINESTRING:
return sqltypes.Geometry
case MULTIPOLYGON:
return sqltypes.Geometry
}
return sqltypes.Null
}
// AddQueryHint adds the given string to list of comment.
// If the list is empty, one will be created containing the query hint.
// If the list already contains a query hint, the given string will be merged with the existing one.
// This is done because only one query hint is allowed per query.
func (node *ParsedComments) AddQueryHint(queryHint string) (Comments, error) {
if queryHint == "" {
if node == nil {
return nil, nil
}
return node.comments, nil
}
var newComments Comments
var hasQueryHint bool
if node != nil {
for _, comment := range node.comments {
if strings.HasPrefix(comment, queryOptimizerPrefix) {
if hasQueryHint {
return nil, vterrors.New(vtrpcpb.Code_INTERNAL, "Must have only one query hint")
}
hasQueryHint = true
idx := strings.Index(comment, "*/")
if idx == -1 {
return nil, vterrors.New(vtrpcpb.Code_INTERNAL, "Query hint comment is malformed")
}
if strings.Contains(comment, queryHint) {
newComments = append(Comments{comment}, newComments...)
continue
}
newComment := fmt.Sprintf("%s %s */", strings.TrimSpace(comment[:idx]), queryHint)
newComments = append(Comments{newComment}, newComments...)
continue
}
newComments = append(newComments, comment)
}
}
if !hasQueryHint {
queryHintCommentStr := fmt.Sprintf("%s %s */", queryOptimizerPrefix, queryHint)
newComments = append(Comments{queryHintCommentStr}, newComments...)
}
return newComments, nil
}
// ParseParams parses the vindex parameter list, pulling out the special-case
// "owner" parameter
func (node *VindexSpec) ParseParams() (string, map[string]string) {
var owner string
params := map[string]string{}
for _, p := range node.Params {
if p.Key.Lowered() == VindexOwnerStr {
owner = p.Val
} else {
params[p.Key.String()] = p.Val
}
}
return owner, params
}
var _ ConstraintInfo = &ForeignKeyDefinition{}
func (f *ForeignKeyDefinition) iConstraintInfo() {}
var _ ConstraintInfo = &CheckConstraintDefinition{}
func (c *CheckConstraintDefinition) iConstraintInfo() {}
// FindColumn finds a column in the column list, returning
// the index if it exists or -1 otherwise
func (node Columns) FindColumn(col IdentifierCI) int {
for i, colName := range node {
if colName.Equal(col) {
return i
}
}
return -1
}
// RemoveHints returns a new AliasedTableExpr with the hints removed.
func (node *AliasedTableExpr) RemoveHints() *AliasedTableExpr {
noHints := *node
noHints.Hints = nil
return &noHints
}
// TableName returns a TableName pointing to this table expr
func (node *AliasedTableExpr) TableName() (TableName, error) {
if !node.As.IsEmpty() {
return TableName{Name: node.As}, nil
}
tableName, ok := node.Expr.(TableName)
if !ok {
return TableName{}, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "BUG: the AST has changed. This should not be possible")
}
return tableName, nil
}
// IsEmpty returns true if TableName is nil or empty.
func (node TableName) IsEmpty() bool {
// If Name is empty, Qualifier is also empty.
return node.Name.IsEmpty()
}
// NewWhere creates a WHERE or HAVING clause out
// of a Expr. If the expression is nil, it returns nil.
func NewWhere(typ WhereType, expr Expr) *Where {
if expr == nil {
return nil
}
return &Where{Type: typ, Expr: expr}
}
// ReplaceExpr finds the from expression from root
// and replaces it with to. If from matches root,
// then to is returned.
func ReplaceExpr(root, from, to Expr) Expr {
tmp := SafeRewrite(root, stopWalking, replaceExpr(from, to))
expr, success := tmp.(Expr)
if !success {
log.Errorf("Failed to rewrite expression. Rewriter returned a non-expression: %s", String(tmp))
return from
}
return expr
}
func stopWalking(e SQLNode, _ SQLNode) bool {
switch e.(type) {
case *ExistsExpr, *Literal, *Subquery, *ValuesFuncExpr, *Default:
return false
default:
return true
}
}
func replaceExpr(from, to Expr) func(cursor *Cursor) bool {
return func(cursor *Cursor) bool {
if cursor.Node() == from {
cursor.Replace(to)
}
return true
}
}
// IsImpossible returns true if the comparison in the expression can never evaluate to true.
// Note that this is not currently exhaustive to ALL impossible comparisons.
func (node *ComparisonExpr) IsImpossible() bool {
var left, right *Literal
var ok bool
if left, ok = node.Left.(*Literal); !ok {
return false
}
if right, ok = node.Right.(*Literal); !ok {
return false
}
if node.Operator == NotEqualOp && left.Type == right.Type {
if len(left.Val) != len(right.Val) {
return false
}
for i := range left.Val {
if left.Val[i] != right.Val[i] {
return false
}
}
return true
}
return false
}
// NewStrLiteral builds a new StrVal.
func NewStrLiteral(in string) *Literal {
return &Literal{Type: StrVal, Val: in}
}
// NewIntLiteral builds a new IntVal.
func NewIntLiteral(in string) *Literal {
return &Literal{Type: IntVal, Val: in}
}
func NewDecimalLiteral(in string) *Literal {
return &Literal{Type: DecimalVal, Val: in}
}
// NewFloatLiteral builds a new FloatVal.
func NewFloatLiteral(in string) *Literal {
return &Literal{Type: FloatVal, Val: in}
}
// NewHexNumLiteral builds a new HexNum.
func NewHexNumLiteral(in string) *Literal {
return &Literal{Type: HexNum, Val: in}
}
// NewHexLiteral builds a new HexVal.
func NewHexLiteral(in string) *Literal {
return &Literal{Type: HexVal, Val: in}
}
// NewBitLiteral builds a new BitVal containing a bit literal.
func NewBitLiteral(in string) *Literal {
return &Literal{Type: BitVal, Val: in}
}
// NewDateLiteral builds a new Date.
func NewDateLiteral(in string) *Literal {
return &Literal{Type: DateVal, Val: in}
}
// NewTimeLiteral builds a new Date.
func NewTimeLiteral(in string) *Literal {
return &Literal{Type: TimeVal, Val: in}
}
// NewTimestampLiteral builds a new Date.
func NewTimestampLiteral(in string) *Literal {
return &Literal{Type: TimestampVal, Val: in}
}
// NewArgument builds a new ValArg.
func NewArgument(in string) *Argument {
return &Argument{Name: in, Type: sqltypes.Unknown}
}
func parseBindVariable(yylex yyLexer, bvar string) *Argument {
markBindVariable(yylex, bvar)
return NewArgument(bvar)
}
func NewTypedArgument(in string, t sqltypes.Type) *Argument {
return &Argument{Name: in, Type: t}
}
// NewListArg builds a new ListArg.
func NewListArg(in string) ListArg {
return ListArg(in)
}
// String returns ListArg as a string.
func (node ListArg) String() string {
return string(node)
}
// Bytes return the []byte
func (node *Literal) Bytes() []byte {
return []byte(node.Val)
}
// HexDecode decodes the hexval into bytes.
func (node *Literal) HexDecode() ([]byte, error) {
return hex.DecodeString(node.Val)
}
func (node *Literal) SQLType() sqltypes.Type {
switch node.Type {
case StrVal:
return sqltypes.VarChar
case IntVal:
return sqltypes.Int64
case FloatVal:
return sqltypes.Float64
case DecimalVal:
return sqltypes.Decimal
case HexNum:
return sqltypes.HexNum
case HexVal:
return sqltypes.HexVal
case BitVal:
return sqltypes.HexNum
case DateVal:
return sqltypes.Date
case TimeVal:
return sqltypes.Time
case TimestampVal:
return sqltypes.Datetime
default:
return -1
}
}
// Equal returns true if the column names match.
func (node *ColName) Equal(c *ColName) bool {
// Failsafe: ColName should not be empty.
if node == nil || c == nil {
return false
}
return node.Name.Equal(c.Name) && node.Qualifier == c.Qualifier
}
// Aggregates is a map of all aggregate functions.
var Aggregates = map[string]bool{
"avg": true,
"bit_and": true,
"bit_or": true,
"bit_xor": true,
"count": true,
"group_concat": true,
"max": true,
"min": true,
"std": true,
"stddev_pop": true,
"stddev_samp": true,
"stddev": true,
"sum": true,
"var_pop": true,
"var_samp": true,
"variance": true,
}
// IsAggregate returns true if the function is an aggregate.
func (node *FuncExpr) IsAggregate() bool {
return Aggregates[node.Name.Lowered()]
}
// NewIdentifierCI makes a new IdentifierCI.
func NewIdentifierCI(str string) IdentifierCI {
return IdentifierCI{
val: str,
}
}
// NewColName makes a new ColName
func NewColName(str string) *ColName {
return &ColName{
Name: NewIdentifierCI(str),
}
}
// NewColNameWithQualifier makes a new ColName pointing to a specific table
func NewColNameWithQualifier(identifier string, table TableName) *ColName {
return &ColName{
Name: NewIdentifierCI(identifier),
Qualifier: TableName{
Name: NewIdentifierCS(table.Name.String()),
Qualifier: NewIdentifierCS(table.Qualifier.String()),
},
}
}
// NewSelect is used to create a select statement
func NewSelect(comments Comments, exprs SelectExprs, selectOptions []string, into *SelectInto, from TableExprs, where *Where, groupBy GroupBy, having *Where, windows NamedWindows) *Select {
var cache *bool
var distinct, straightJoinHint, sqlFoundRows bool
for _, option := range selectOptions {
switch strings.ToLower(option) {
case DistinctStr:
distinct = true
case SQLCacheStr:
truth := true
cache = &truth
case SQLNoCacheStr:
truth := false
cache = &truth
case StraightJoinHint:
straightJoinHint = true
case SQLCalcFoundRowsStr:
sqlFoundRows = true
}
}
return &Select{
Cache: cache,
Comments: comments.Parsed(),
Distinct: distinct,
StraightJoinHint: straightJoinHint,
SQLCalcFoundRows: sqlFoundRows,
SelectExprs: exprs,
Into: into,
From: from,
Where: where,
GroupBy: groupBy,
Having: having,
Windows: windows,
}
}
// UpdateSetExprsScope updates the scope of the variables in SetExprs.
func UpdateSetExprsScope(setExprs SetExprs, scope Scope) SetExprs {
for _, setExpr := range setExprs {
setExpr.Var.Scope = scope
}
return setExprs
}
// NewSetVariable returns a variable that can be used with SET.
func NewSetVariable(str string, scope Scope) *Variable {
return &Variable{Name: createIdentifierCI(str), Scope: scope}
}
// NewSetStatement returns a Set struct
func NewSetStatement(comments *ParsedComments, exprs SetExprs) *Set {
return &Set{Exprs: exprs, Comments: comments}
}
// NewVariableExpression returns an expression the evaluates to a variable at runtime.
// The AtCount and the prefix of the name of the variable will decide how it's evaluated
func NewVariableExpression(str string, at AtCount) *Variable {
l := strings.ToLower(str)
v := &Variable{
Name: createIdentifierCI(str),
}
switch at {
case DoubleAt:
switch {
case strings.HasPrefix(l, "local."):
v.Name = createIdentifierCI(str[6:])
v.Scope = SessionScope
case strings.HasPrefix(l, "session."):
v.Name = createIdentifierCI(str[8:])
v.Scope = SessionScope
case strings.HasPrefix(l, "global."):
v.Name = createIdentifierCI(str[7:])
v.Scope = GlobalScope
case strings.HasPrefix(l, "vitess_metadata."):
v.Name = createIdentifierCI(str[16:])
v.Scope = VitessMetadataScope
case strings.HasSuffix(l, TransactionIsolationStr) || strings.HasSuffix(l, TransactionReadOnlyStr):
v.Scope = NextTxScope
default:
v.Scope = SessionScope
}
case SingleAt:
v.Scope = VariableScope
case NoAt:
panic("we should never see NoAt here")
}
return v
}
func createIdentifierCI(str string) IdentifierCI {
size := len(str)
if str[0] == '`' && str[size-1] == '`' {
str = str[1 : size-1]
}
return NewIdentifierCI(str)
}
// NewOffset creates an offset and returns it
func NewOffset(v int, original Expr) *Offset {
return &Offset{V: v, Original: original}
}
// IsEmpty returns true if the name is empty.
func (node IdentifierCI) IsEmpty() bool {
return node.val == ""
}
// String returns the unescaped column name. It must
// not be used for SQL generation. Use sqlparser.String
// instead. The Stringer conformance is for usage
// in templates.
func (node IdentifierCI) String() string {
return node.val
}
// CompliantName returns a compliant id name
// that can be used for a bind var.
func (node IdentifierCI) CompliantName() string {
return compliantName(node.val)
}
// Lowered returns a lower-cased column name.
// This function should generally be used only for optimizing
// comparisons.
func (node IdentifierCI) Lowered() string {
if node.val == "" {
return ""
}
if node.lowered == "" {
node.lowered = strings.ToLower(node.val)
}
return node.lowered
}
// Equal performs a case-insensitive compare.
func (node IdentifierCI) Equal(in IdentifierCI) bool {
return node.Lowered() == in.Lowered()
}
// EqualString performs a case-insensitive compare with str.
func (node IdentifierCI) EqualString(str string) bool {
return node.Lowered() == strings.ToLower(str)
}
// MarshalJSON marshals into JSON.
func (node IdentifierCI) MarshalJSON() ([]byte, error) {
return json.Marshal(node.val)
}
// UnmarshalJSON unmarshals from JSON.
func (node *IdentifierCI) UnmarshalJSON(b []byte) error {
var result string
err := json.Unmarshal(b, &result)
if err != nil {
return err
}
node.val = result
return nil
}
// NewIdentifierCS creates a new IdentifierCS.
func NewIdentifierCS(str string) IdentifierCS {
// Use StringClone on the table name to ensure it is not pinned to the
// underlying query string that has been generated by the parser. This
// could lead to a significant increase in memory usage when the table
// name comes from a large query.
return IdentifierCS{v: strings.Clone(str)}
}
// IsEmpty returns true if TabIdent is empty.
func (node IdentifierCS) IsEmpty() bool {
return node.v == ""
}
// String returns the unescaped table name. It must
// not be used for SQL generation. Use sqlparser.String
// instead. The Stringer conformance is for usage
// in templates.
func (node IdentifierCS) String() string {
return node.v
}
// CompliantName returns a compliant id name
// that can be used for a bind var.
func (node IdentifierCS) CompliantName() string {
return compliantName(node.v)
}
// MarshalJSON marshals into JSON.
func (node IdentifierCS) MarshalJSON() ([]byte, error) {
return json.Marshal(node.v)
}
// UnmarshalJSON unmarshals from JSON.
func (node *IdentifierCS) UnmarshalJSON(b []byte) error {
var result string
err := json.Unmarshal(b, &result)
if err != nil {
return err
}
node.v = result
return nil
}
func containEscapableChars(s string, at AtCount) bool {
isDbSystemVariable := at != NoAt
for i := range s {
c := uint16(s[i])
letter := isLetter(c)
systemVarChar := isDbSystemVariable && isCarat(c)
if !(letter || systemVarChar) {
if i == 0 || !isDigit(c) {
return true
}
}
}
return false
}
func formatID(buf *TrackedBuffer, original string, at AtCount) {
if buf.escape == escapeNoIdentifiers {
buf.WriteString(original)
return
}
_, isKeyword := keywordLookupTable.LookupString(original)
if buf.escape == escapeAllIdentifiers || isKeyword || containEscapableChars(original, at) {
writeEscapedString(buf, original)
} else {
buf.WriteString(original)
}
}
func writeEscapedString(buf *TrackedBuffer, original string) {
buf.WriteByte('`')
for _, c := range original {
buf.WriteRune(c)
if c == '`' {
buf.WriteByte('`')
}
}
buf.WriteByte('`')
}
func CompliantString(in SQLNode) string {
s := String(in)
return compliantName(s)
}
func compliantName(in string) string {
var buf strings.Builder
for i, c := range in {
if !isLetter(uint16(c)) {
if i == 0 || !isDigit(uint16(c)) {
buf.WriteByte('_')
continue
}
}
buf.WriteRune(c)
}
return buf.String()
}
// AddOrder adds an order by element
func (node *Select) AddOrder(order *Order) {
node.OrderBy = append(node.OrderBy, order)
}
// SetOrderBy sets the order by clause
func (node *Select) SetOrderBy(orderBy OrderBy) {
node.OrderBy = orderBy
}
// GetOrderBy gets the order by clause
func (node *Select) GetOrderBy() OrderBy {
return node.OrderBy
}
// SetLimit sets the limit clause
func (node *Select) SetLimit(limit *Limit) {
node.Limit = limit
}
// GetLimit gets the limit
func (node *Select) GetLimit() *Limit {
return node.Limit
}
// SetLock sets the lock clause
func (node *Select) SetLock(lock Lock) {
node.Lock = lock
}
// SetInto sets the into clause
func (node *Select) SetInto(into *SelectInto) {
node.Into = into
}
// SetWith sets the with clause to a select statement
func (node *Select) SetWith(with *With) {
node.With = with
}
// MakeDistinct makes the statement distinct
func (node *Select) MakeDistinct() {
node.Distinct = true
}
// GetColumnCount return SelectExprs count.
func (node *Select) GetColumnCount() int {
return len(node.SelectExprs)
}
// GetColumns gets the columns
func (node *Select) GetColumns() SelectExprs {
return node.SelectExprs
}
// SetComments implements the Commented interface
func (node *Select) SetComments(comments Comments) {
node.Comments = comments.Parsed()
}
// GetParsedComments implements the Commented interface
func (node *Select) GetParsedComments() *ParsedComments {
return node.Comments
}
// AddWhere adds the boolean expression to the
// WHERE clause as an AND condition.
func (node *Select) AddWhere(expr Expr) {
node.Where = addPredicate(node.Where, expr)
}
// AddHaving adds the boolean expression to the
// HAVING clause as an AND condition.
func (node *Select) AddHaving(expr Expr) {
node.Having = addPredicate(node.Having, expr)
node.Having.Type = HavingClause
}
// AddGroupBy adds a grouping expression, unless it's already present
func (node *Select) AddGroupBy(expr Expr) {