forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathast.go
More file actions
8365 lines (7331 loc) · 204 KB
/
ast.go
File metadata and controls
8365 lines (7331 loc) · 204 KB
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
//go:generate goyacc -o sql.go sql.y
import (
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"runtime/trace"
"sort"
"strconv"
"strings"
"sync"
"unicode"
"github.com/dolthub/vitess/go/sqltypes"
"github.com/dolthub/vitess/go/vt/vterrors"
querypb "github.com/dolthub/vitess/go/vt/proto/query"
vtrpcpb "github.com/dolthub/vitess/go/vt/proto/vtrpc"
)
// parserPool is a pool for parser objects.
var parserPool = sync.Pool{}
// zeroParser is a zero-initialized parser to help reinitialize the parser for pooling.
var zeroParser = *(yyNewParser().(*yyParserImpl))
// yyParsePooled is a wrapper around yyParse that pools the parser objects. There isn't a
// particularly good reason to use yyParse directly, since it immediately discards its parser. What
// would be ideal down the line is to actually pool the stacks themselves rather than the parser
// objects, as per https://github.com/cznic/goyacc/blob/master/main.go. However, absent an upstream
// change to goyacc, this is the next best option.
//
// N.B: Parser pooling means that you CANNOT take references directly to parse stack variables (e.g.
// $$ = &$4) in sql.y rules. You must instead add an intermediate reference like so:
//
// showCollationFilterOpt := $4
// $$ = &Show{Type: string($2), ShowCollationFilterOpt: &showCollationFilterOpt}
func yyParsePooled(yylex yyLexer) (ret int) {
// Being very particular about using the base type and not an interface type b/c we depend on
// the implementation to know how to reinitialize the parser.
var parser *yyParserImpl
i := parserPool.Get()
if i != nil {
parser = i.(*yyParserImpl)
} else {
parser = yyNewParser().(*yyParserImpl)
}
defer func() {
*parser = zeroParser
parserPool.Put(parser)
}()
defer func() {
if recoveredPanic := recover(); recoveredPanic != nil {
yylex.Error(fmt.Sprintf("handler caught panic: %v", recoveredPanic))
ret = 1
}
}()
return parser.Parse(yylex)
}
// Instructions for creating new types: If a type
// needs to satisfy an interface, declare that function
// along with that interface. This will help users
// identify the list of types to which they can assert
// those interfaces.
// If the member of a type has a string with a predefined
// list of values, declare those values as const following
// the type.
// For interfaces that define dummy functions to consolidate
// a set of types, define the function as iTypeName.
// This will help avoid name collisions.
// ParserOptions defines options that customize how statements are parsed.
type ParserOptions struct {
// AnsiQuotes controls whether " characters are treated as the identifier character, as
// defined in the SQL92 standard, or as a string quote character. By default, AnsiQuotes
// mode is disabled, and " chars are treated as string literal quoting characters.
// When AnsiQuotes is set to true, " characters are treated as identifier quotes and are
// NOT valid as string literal quotes. Note that the ` character may always
// be used to quote identifiers, regardless of whether AnsiQuotes is enabled or not. For
// more info, see: https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html#sqlmode_ansi_quotes
AnsiQuotes bool
// PipesAsConcat turns double pipes into a CONCAT token. Otherwise, double pipes are synonymous with OR.
// PipesAsConcat mode is disabled by default.
PipesAsConcat bool
}
// Parse parses the SQL in full and returns a Statement, which
// is the AST representation of the query. If a DDL statement
// is partially parsed but still contains a syntax error, the
// error is ignored and the DDL is returned anyway.
func Parse(sql string) (Statement, error) {
return ParseWithOptions(context.Background(), sql, ParserOptions{})
}
// ParseWithOptions fully parses the SQL in |sql|, using any custom options specified
// in |options|, and returns a Statement, which is the AST representation of the query.
// If a DDL statement is partially parsed but contains a syntax error, the
// error is ignored and the DDL is returned anyway.
func ParseWithOptions(ctx context.Context, sql string, options ParserOptions) (Statement, error) {
defer trace.StartRegion(ctx, "ParseWithOptions").End()
tokenizer := NewStringTokenizer(sql)
if options.AnsiQuotes {
tokenizer = NewStringTokenizerForAnsiQuotes(sql)
}
tokenizer.PipesAsConcat = options.PipesAsConcat
return parseTokenizer(sql, tokenizer)
}
// ParseOne parses the first SQL statement in the given string and returns the
// index of the start of the next statement in |sql|. If there was only one
// statement in |sql|, the value of the returned index will be |len(sql)|.
func ParseOne(ctx context.Context, sql string) (Statement, int, error) {
return ParseOneWithOptions(ctx, sql, ParserOptions{})
}
// ParseOneWithOptions parses the first SQL statement in |sql|, using any parsing
// options specified in |options|, and returns the parsed Statement, along with
// the index of the start of the next statement in |sql|. If there was only one
// statement in |sql|, the value of the returned index will be |len(sql)|.
func ParseOneWithOptions(ctx context.Context, sql string, options ParserOptions) (Statement, int, error) {
defer trace.StartRegion(ctx, "ParseOneWithOptions").End()
tokenizer := NewStringTokenizer(sql)
if options.AnsiQuotes {
tokenizer = NewStringTokenizerForAnsiQuotes(sql)
}
tokenizer.PipesAsConcat = options.PipesAsConcat
tokenizer.stopAfterFirstStmt = true
tree, err := parseTokenizer(sql, tokenizer)
if err != nil {
if err == ErrEmpty {
return nil, tokenizer.Position, err
} else {
return nil, 0, err
}
}
return tree, tokenizer.Position - 1, nil
}
func parseTokenizer(sql string, tokenizer *Tokenizer) (Statement, error) {
if yyParsePooled(tokenizer) != 0 {
if se, ok := tokenizer.LastError.(vterrors.SyntaxError); ok {
return nil, vterrors.NewWithCause(vtrpcpb.Code_INVALID_ARGUMENT, tokenizer.LastError.Error(), se)
} else {
return nil, vterrors.New(vtrpcpb.Code_INVALID_ARGUMENT, tokenizer.LastError.Error())
}
}
if tokenizer.ParseTree == nil {
return nil, ErrEmpty
}
captureSelectExpressions(sql, tokenizer)
adjustSubstatementPositions(sql, tokenizer)
return tokenizer.ParseTree, nil
}
// For select statements, capture the verbatim select expressions from the original query text.
// It searches select expressions in walkable nodes.
func captureSelectExpressions(sql string, tokenizer *Tokenizer) {
if s, isSelect := tokenizer.ParseTree.(SelectStatement); isSelect {
walkSelectExpressions(s, sql)
} else if w, ok := tokenizer.ParseTree.(WalkableSQLNode); ok {
w.walkSubtree(func(node SQLNode) (bool, error) {
if s, isSelect = node.(SelectStatement); isSelect {
walkSelectExpressions(s, sql)
}
return true, nil
})
}
}
// walkSelectExpressions fills in `InputExpression` of `AliasedExpr` if it's not a column name.
// This is used to display the result as defined original query text. This function gets called
// by captureSelectExpressions.
func walkSelectExpressions(s SelectStatement, sql string) {
s.walkSubtree(func(node SQLNode) (bool, error) {
if node, ok := node.(*AliasedExpr); ok && node.EndParsePos > node.StartParsePos {
_, ok := node.Expr.(*ColName)
if ok {
// column names don't need any special handling to capture the input expression
return false, nil
} else {
node.InputExpression = trimQuotes(strings.Trim(sql[node.StartParsePos:node.EndParsePos], " \n\t"))
}
}
return true, nil
})
}
// For DDL statements that capture the position of a sub-statement (create view and others), we need to adjust these
// indexes if they occurred inside a MySQL special comment (/*! */) because we sometimes inappropriately capture the
// comment ending characters in such cases.
func adjustSubstatementPositions(sql string, tokenizer *Tokenizer) {
if ddl, ok := tokenizer.ParseTree.(*DDL); ok {
if ddl.SpecialCommentMode && ddl.SubStatementPositionStart > 0 &&
ddl.SubStatementPositionEnd > ddl.SubStatementPositionStart {
sub := sql[ddl.SubStatementPositionStart:ddl.SubStatementPositionEnd]
// We don't actually capture the end of the comment in all cases, sometimes it's just *
endCommentIdx := strings.LastIndex(sub, "*/") - 1
if endCommentIdx < 0 {
if sub[len(sub)-1] == '*' {
endCommentIdx = len(sub) - 2
} else {
endCommentIdx = len(sub) - 1
}
}
// Backtrack until we find a non-space character. That's the actual end of the substatement.
for endCommentIdx > 0 && unicode.IsSpace(rune(sub[endCommentIdx])) {
endCommentIdx--
}
if !unicode.IsSpace(rune(sub[endCommentIdx])) {
endCommentIdx++
}
ddl.SubStatementPositionEnd = ddl.SubStatementPositionStart + endCommentIdx
}
}
}
func trimQuotes(s string) string {
firstChar := s[0]
lastChar := s[len(s)-1]
if firstChar == lastChar {
if firstChar == '`' || firstChar == '"' || firstChar == '\'' {
// Some edge cases here: we have to be careful to not strip expressions like `"1" + "2"`
if stringIsUnbrokenQuote(s, firstChar) {
return s[1 : len(s)-1]
}
}
}
return s
}
func stringIsUnbrokenQuote(s string, quoteChar byte) bool {
numConsecutiveQuotes := 0
numConsecutiveEscapes := 0
for _, c := range ([]byte)(s[1 : len(s)-1]) {
if c == quoteChar && numConsecutiveEscapes%2 == 0 {
numConsecutiveQuotes++
} else {
if numConsecutiveQuotes%2 != 0 {
return false
}
numConsecutiveQuotes = 0
}
if c == '\\' {
numConsecutiveEscapes++
} else {
numConsecutiveEscapes = 0
}
}
return true
}
// ParseNext parses a single SQL statement from the tokenizer
// returning a Statement which is the AST representation of the query.
// The tokenizer will always read up to the end of the statement, allowing for
// the next call to ParseNext to parse any subsequent SQL statements. When
// there are no more statements to parse, a error of io.EOF is returned.
func ParseNext(tokenizer *Tokenizer) (Statement, error) {
if tokenizer.lastChar == ';' {
tokenizer.next()
tokenizer.skipBlank()
}
if tokenizer.lastChar == eofChar {
return nil, io.EOF
}
tokenizer.reset()
tokenizer.multi = true
if yyParsePooled(tokenizer) != 0 {
return nil, tokenizer.LastError
}
if tokenizer.ParseTree == nil {
return ParseNext(tokenizer)
}
captureSelectExpressions((string)(tokenizer.queryBuf), tokenizer)
return tokenizer.ParseTree, nil
}
// ErrEmpty is a sentinel error returned when parsing empty statements.
var ErrEmpty = errors.New("empty statement")
// SplitStatement returns the first sql statement up to either a ; or EOF
// and the remainder from the given buffer
func SplitStatement(blob string) (string, string, error) {
tokenizer := NewStringTokenizer(blob)
tkn := 0
for {
tkn, _ = tokenizer.Scan()
if tkn == 0 || tkn == ';' || tkn == eofChar {
break
}
}
if tokenizer.LastError != nil {
return "", "", tokenizer.LastError
}
if tkn == ';' {
return blob[:tokenizer.Position-2], blob[tokenizer.Position-1:], nil
}
return blob, "", nil
}
// SplitStatementToPieces split raw sql statement that may have multi sql pieces to sql pieces
// returns the sql pieces blob contains; or error if sql cannot be parsed
func SplitStatementToPieces(blob string) (pieces []string, err error) {
pieces = make([]string, 0, 16)
tokenizer := NewStringTokenizer(blob)
tkn := 0
var stmt string
stmtBegin := 0
for {
tkn, _ = tokenizer.Scan()
if tkn == ';' {
stmt = blob[stmtBegin : tokenizer.Position-2]
pieces = append(pieces, stmt)
stmtBegin = tokenizer.Position - 1
} else if tkn == 0 || tkn == eofChar {
blobTail := tokenizer.Position - 2
if stmtBegin < blobTail {
stmt = blob[stmtBegin : blobTail+1]
if strings.TrimSpace(stmt) != "" {
pieces = append(pieces, stmt)
}
}
break
}
}
err = tokenizer.LastError
return
}
// SQLNode defines the interface for all nodes
// generated by the parser.
type SQLNode interface {
Format(buf *TrackedBuffer)
}
// WalkableSQLNode represents an interface for nodes
// that have subnodes that may need to be traversed over.
type WalkableSQLNode interface {
SQLNode
// walkSubtree calls visit on all underlying nodes
// of the subtree, but not the current one. Walking
// must be interrupted if visit returns an error.
walkSubtree(visit Visit) error
}
// Visit defines the signature of a function that
// can be used to visit all nodes of a parse tree.
type Visit func(node SQLNode) (kontinue bool, err error)
// Walk calls visit on every node.
// If visit 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 {
if node == nil {
continue
}
kontinue, err := visit(node)
if err != nil {
return err
}
if kontinue {
if node, ok := node.(WalkableSQLNode); ok {
err = node.walkSubtree(visit)
if err != nil {
return err
}
}
}
}
return nil
}
// String returns a string representation of an SQLNode.
func String(node SQLNode) string {
if node == nil {
return "<nil>"
}
buf := NewTrackedBuffer(nil)
buf.Myprintf("%v", node)
return buf.String()
}
// Append appends the SQLNode to the buffer.
func Append(buf *strings.Builder, node SQLNode) {
tbuf := &TrackedBuffer{
Builder: buf,
}
node.Format(tbuf)
}
// Statement represents a statement.
type Statement interface {
iStatement()
SQLNode
}
type Statements []Statement
func (*SetOp) iStatement() {}
func (*Select) iStatement() {}
func (*Stream) iStatement() {}
func (*Insert) iStatement() {}
func (*Update) iStatement() {}
func (*Delete) iStatement() {}
func (*Set) iStatement() {}
func (*DBDDL) iStatement() {}
func (*DDL) iStatement() {}
func (*AlterTable) iStatement() {}
func (*Explain) iStatement() {}
func (*Show) iStatement() {}
func (*Use) iStatement() {}
func (*Begin) iStatement() {}
func (*Commit) iStatement() {}
func (*Rollback) iStatement() {}
func (*Flush) iStatement() {}
func (*OtherRead) iStatement() {}
func (*OtherAdmin) iStatement() {}
func (*PurgeBinaryLogs) iStatement() {}
func (*BeginEndBlock) iStatement() {}
func (*CaseStatement) iStatement() {}
func (*IfStatement) iStatement() {}
func (*Signal) iStatement() {}
func (*Resignal) iStatement() {}
func (*Declare) iStatement() {}
func (*OpenCursor) iStatement() {}
func (*CloseCursor) iStatement() {}
func (*FetchCursor) iStatement() {}
func (*Loop) iStatement() {}
func (*Repeat) iStatement() {}
func (*While) iStatement() {}
func (*Leave) iStatement() {}
func (*Return) iStatement() {}
func (*Iterate) iStatement() {}
func (*Call) iStatement() {}
func (*Load) iStatement() {}
func (*Savepoint) iStatement() {}
func (*RollbackSavepoint) iStatement() {}
func (*ReleaseSavepoint) iStatement() {}
func (*LockTables) iStatement() {}
func (*UnlockTables) iStatement() {}
func (*Binlog) iStatement() {}
// ParenSelect can actually not be a top level statement,
// but we have to allow it because it's a requirement
// of SelectStatement.
func (*ParenSelect) iStatement() {}
// SelectStatement any SELECT statement.
type SelectStatement interface {
iSelectStatement()
iStatement()
iInsertRows()
AddOrder(*Order)
SetLimit(*Limit)
SetLock(interface{})
SetOrderBy(OrderBy)
SetWith(*With)
SetInto(*Into) error
GetInto() *Into
WalkableSQLNode
}
func (*Select) iSelectStatement() {}
func (*SetOp) iSelectStatement() {}
func (*ParenSelect) iSelectStatement() {}
func (*ValuesStatement) iSelectStatement() {}
type QueryOpts struct {
All bool
Distinct bool
StraightJoinHint bool
SQLCalcFoundRows bool
SQLCache bool
SQLNoCache bool
}
func (q *QueryOpts) merge(other QueryOpts) error {
q.All = q.All || other.All
q.Distinct = q.Distinct || other.Distinct
q.StraightJoinHint = q.StraightJoinHint || other.StraightJoinHint
q.SQLCalcFoundRows = q.SQLCalcFoundRows || other.SQLCalcFoundRows
q.SQLCache = q.SQLCache || other.SQLCache
q.SQLNoCache = q.SQLNoCache || other.SQLNoCache
if q.Distinct && q.All {
return errors.New("incorrect usage of DISTINCT and ALL")
}
if q.SQLCache && q.SQLNoCache {
return errors.New("incorrect usage of SQL_CACHE and SQL_NO_CACHE")
}
return nil
}
func (q *QueryOpts) Format(buf *TrackedBuffer) {
if q == nil {
return
}
if q.All {
buf.Myprintf("%s", AllStr)
}
if q.Distinct {
buf.Myprintf("%s", DistinctStr)
}
if q.StraightJoinHint {
buf.Myprintf("%s", StraightJoinHintStr)
}
if q.SQLCalcFoundRows {
buf.Myprintf("%s", SQLCalcFoundRowsStr)
}
if q.SQLCache {
buf.Myprintf("%s", SQLCacheStr)
}
if q.SQLNoCache {
buf.Myprintf("%s", SQLNoCacheStr)
}
}
// Lock represents a lock clause
type Lock struct {
Type string // The lock type string (e.g., " for update", " for update of t1, t2 skip locked")
Tables TableNames // Table names for FOR UPDATE OF clause (empty for regular FOR UPDATE)
}
// Select represents a SELECT statement.
type Select struct {
Into *Into
With *With
Limit *Limit
Having *Where
Where *Where
Lock *Lock
GroupBy GroupBy
Comments Comments
Window Window
OrderBy OrderBy
SelectExprs SelectExprs
From TableExprs
QueryOpts QueryOpts
}
// Select.QueryOpts
const (
DistinctStr = "distinct "
AllStr = "all "
StraightJoinHintStr = "straight_join "
SQLCalcFoundRowsStr = "sql_calc_found_rows "
SQLCacheStr = "sql_cache "
SQLNoCacheStr = "sql_no_cache "
)
// Select.Lock
const (
ForUpdateStr = " for update"
ShareModeStr = " lock in share mode"
ForUpdateSkipLockedStr = " for update skip locked"
ForUpdateNowaitStr = " for update nowait"
ForUpdateOfStr = " for update of"
)
// AddOrder adds an order by element
func (node *Select) AddOrder(order *Order) {
node.OrderBy = append(node.OrderBy, order)
}
func (node *Select) SetOrderBy(orderBy OrderBy) {
node.OrderBy = orderBy
}
func (node *Select) SetWith(w *With) {
node.With = w
}
func (node *Select) SetLock(lock interface{}) {
switch v := lock.(type) {
case string:
node.Lock = &Lock{Type: v}
case *Lock:
node.Lock = v
default:
node.Lock = nil
}
}
func (node *Select) SetInto(into *Into) error {
if into == nil {
return nil
}
if into.Variables == nil && into.Dumpfile == "" && into.Outfile == "" {
return nil
}
if node.Into != nil {
return fmt.Errorf("Multiple INTO clauses in one query block")
}
node.Into = into
return nil
}
func (node *Select) GetInto() *Into {
return node.Into
}
// SetLimit sets the limit clause
func (node *Select) SetLimit(limit *Limit) {
node.Limit = limit
}
// Format formats the node.
func (node *Select) Format(buf *TrackedBuffer) {
buf.Myprintf("%vselect %v%v%v",
node.With,
node.Comments, &node.QueryOpts, node.SelectExprs,
)
if node.From != nil {
buf.Myprintf(" from %v", node.From)
}
lockStr := ""
if node.Lock != nil {
lockStr = node.Lock.Type
}
buf.Myprintf("%v%v%v%v%v%v%s%v",
node.Where, node.GroupBy, node.Having, node.Window,
node.OrderBy, node.Limit, lockStr, node.Into)
}
func (node *Select) walkSubtree(visit Visit) error {
if node == nil {
return nil
}
return Walk(
visit,
node.With,
node.Comments,
node.SelectExprs,
node.From,
node.Where,
node.GroupBy,
node.Having,
node.OrderBy,
node.Limit,
node.Into,
)
}
// AddWhere adds the boolean expression to the
// WHERE clause as an AND condition. If the expression
// is an OR clause, it parenthesizes it.
// Both OR and XOR operators are lower precedence than AND.
func (node *Select) AddWhere(expr Expr) {
switch expr.(type) {
case *OrExpr, *XorExpr:
expr = &ParenExpr{Expr: expr}
}
if node.Where == nil {
node.Where = &Where{
Type: WhereStr,
Expr: expr,
}
return
}
node.Where.Expr = &AndExpr{
Left: node.Where.Expr,
Right: expr,
}
}
// AddHaving adds the boolean expression to the
// HAVING clause as an AND condition. If the expression
// is an OR clause, it parenthesizes it.
// Both OR and XOR operators are lower precedence than AND.
func (node *Select) AddHaving(expr Expr) {
switch expr.(type) {
case *OrExpr, *XorExpr:
expr = &ParenExpr{Expr: expr}
}
if node.Having == nil {
node.Having = &Where{
Type: HavingStr,
Expr: expr,
}
return
}
node.Having.Expr = &AndExpr{
Left: node.Having.Expr,
Right: expr,
}
}
// ParenSelect is a parenthesized SELECT statement.
type ParenSelect struct {
Select SelectStatement
}
// AddOrder adds an order by element
func (node *ParenSelect) AddOrder(order *Order) {
panic("unreachable")
}
func (node *ParenSelect) SetOrderBy(orders OrderBy) {
panic("unreachable")
}
func (node *ParenSelect) SetWith(w *With) {
panic("unreachable")
}
func (node *ParenSelect) SetLock(lock interface{}) {
panic("unreachable")
}
// SetLimit sets the limit clause
func (node *ParenSelect) SetLimit(limit *Limit) {
panic("unreachable")
}
func (node *ParenSelect) SetInto(into *Into) error {
panic("unreachable")
}
func (node *ParenSelect) GetInto() *Into {
return node.Select.GetInto()
}
// Format formats the node.
func (node *ParenSelect) Format(buf *TrackedBuffer) {
buf.Myprintf("(%v)", node.Select)
}
func (node *ParenSelect) walkSubtree(visit Visit) error {
if node == nil {
return nil
}
return Walk(
visit,
node.Select,
)
}
// ValuesStatement is a VALUES ROW('1', '2'), ROW(3, 4) expression, which can be a table factor or a stand-alone
// statement
type ValuesStatement struct {
Rows Values
Columns Columns
}
func (s *ValuesStatement) Format(buf *TrackedBuffer) {
buf.Myprintf("values ")
for i, row := range s.Rows {
if i > 0 {
buf.Myprintf(", ")
}
buf.Myprintf("row%v", row)
}
}
func (s *ValuesStatement) walkSubtree(visit Visit) error {
return Walk(visit, s.Rows)
}
// SetOp represents a UNION, INTERSECT, and EXCEPT statement.
type SetOp struct {
Left SelectStatement
Right SelectStatement
With *With
Limit *Limit
Into *Into
Type string
Lock *Lock
OrderBy OrderBy
}
// SetOp.Type
const (
UnionStr = "union"
UnionAllStr = "union all"
UnionDistinctStr = "union distinct"
IntersectStr = "intersect"
IntersectAllStr = "intersect all"
IntersectDistinctStr = "intersect distinct"
ExceptStr = "except"
ExceptAllStr = "except all"
ExceptDistinctStr = "except distinct"
)
// AddOrder adds an order by element
func (node *SetOp) AddOrder(order *Order) {
node.OrderBy = append(node.OrderBy, order)
}
func (node *SetOp) SetOrderBy(orderBy OrderBy) {
node.OrderBy = orderBy
}
func (node *SetOp) SetWith(w *With) {
node.With = w
}
// SetLimit sets the limit clause
func (node *SetOp) SetLimit(limit *Limit) {
node.Limit = limit
}
func (node *SetOp) SetLock(lock interface{}) {
switch v := lock.(type) {
case string:
node.Lock = &Lock{Type: v}
case *Lock:
node.Lock = v
default:
node.Lock = nil
}
}
func (node *SetOp) SetInto(into *Into) error {
if into == nil {
if r, ok := node.Right.(*Select); ok {
node.Into = r.Into
r.Into = nil
}
return nil
}
if node.Into != nil {
return fmt.Errorf("Multiple INTO clauses in one query block")
}
node.Into = into
return nil
}
func (node *SetOp) GetInto() *Into {
return node.Into
}
// Format formats the node.
func (node *SetOp) Format(buf *TrackedBuffer) {
lockStr := ""
if node.Lock != nil {
lockStr = node.Lock.Type
}
buf.Myprintf("%v%v %s %v%v%v%s%v", node.With, node.Left, node.Type, node.Right,
node.OrderBy, node.Limit, lockStr, node.Into)
}
func (node *SetOp) walkSubtree(visit Visit) error {
if node == nil {
return nil
}
return Walk(
visit,
node.Left,
node.Right,
)
}
// LoadStatement any LOAD statement.
type LoadStatement interface {
iLoadStatement()
iStatement()
SQLNode
}
// Load represents a LOAD statement
type Load struct {
Auth AuthInformation
*Fields
*Lines
IgnoreNum *SQLVal
Table TableName
Infile string
Charset string
IgnoreOrReplace string
Partition Partitions
Columns
SetExprs AssignmentExprs
Local BoolVal
}
var _ AuthNode = (*Load)(nil)
func (*Load) iLoadStatement() {}
func (node *Load) Format(buf *TrackedBuffer) {
local := ""
if node.Local {
local = "local "
}
charset := ""
if node.Charset != "" {
charset = " character set " + node.Charset
}
ignoreNum := ""
if node.IgnoreNum != nil {
ignoreNum = fmt.Sprintf(" ignore %v lines", node.IgnoreNum)
}
if node.IgnoreNum == nil && node.Columns != nil {
ignoreNum = " "
} else if node.IgnoreNum != nil && node.Columns != nil {
ignoreNum += " "
}
ignoreOrReplace := node.IgnoreOrReplace
if ignoreOrReplace == ReplaceStr {
ignoreOrReplace += " "
}
buf.Myprintf("load data %sinfile '%s' %sinto table %s", local, node.Infile, ignoreOrReplace, node.Table.String())
if len(node.Partition) > 0 {
buf.Myprintf(" partition (%v)", node.Partition)
}
buf.Myprintf("%s%v%v%s%v", charset, node.Fields, node.Lines, ignoreNum, node.Columns)
if node.SetExprs != nil {
buf.Myprintf(" set %v", node.SetExprs)
}
}
// GetAuthInformation implements the AuthNode interface.
func (node *Load) GetAuthInformation() AuthInformation {
return node.Auth
}
// SetAuthType implements the AuthNode interface.
func (node *Load) SetAuthType(authType string) {
node.Auth.AuthType = authType
}
// SetAuthTargetType implements the AuthNode interface.
func (node *Load) SetAuthTargetType(targetType string) {
node.Auth.TargetType = targetType
}
// SetAuthTargetNames implements the AuthNode interface.
func (node *Load) SetAuthTargetNames(targetNames []string) {
node.Auth.TargetNames = targetNames
}
// SetExtra implements the AuthNode interface.
func (node *Load) SetExtra(extra any) {
node.Auth.Extra = extra
}
func (node *Load) walkSubtree(visit Visit) error {
if node == nil {
return nil
}
return Walk(
visit,
node.Local,
node.Table,
node.Partition,
node.Fields,
node.Lines,
node.IgnoreNum,
node.Columns,