Debian Codegraph @

ast.go

raw symbols SCIP
1 /*
2 Copyright 2017 Google Inc.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package sqlparser
18
19 import (
20 "bytes"
21 "encoding/hex"
22 "encoding/json"
23 "fmt"
24 "io"
25 "log"
26 "strings"
27
28 "github.com/xwb1989/sqlparser/dependency/querypb"
29 "github.com/xwb1989/sqlparser/dependency/sqltypes"
30 )
31
32 // Instructions for creating new types: If a type
33 // needs to satisfy an interface, declare that function
34 // along with that interface. This will help users
35 // identify the list of types to which they can assert
36 // those interfaces.
37 // If the member of a type has a string with a predefined
38 // list of values, declare those values as const following
39 // the type.
40 // For interfaces that define dummy functions to consolidate
41 // a set of types, define the function as iTypeName.
42 // This will help avoid name collisions.
43
44 // Parse parses the SQL in full and returns a Statement, which
45 // is the AST representation of the query. If a DDL statement
46 // is partially parsed but still contains a syntax error, the
47 // error is ignored and the DDL is returned anyway.
48 func Parse(sql string) (Statement, error) {
49 tokenizer := NewStringTokenizer(sql)
50 if yyParse(tokenizer) != 0 {
51 if tokenizer.partialDDL != nil {
52 log.Printf("ignoring error parsing DDL '%s': %v", sql, tokenizer.LastError)
53 tokenizer.ParseTree = tokenizer.partialDDL
54 return tokenizer.ParseTree, nil
55 }
56 return nil, tokenizer.LastError
57 }
58 return tokenizer.ParseTree, nil
59 }
60
61 // ParseStrictDDL is the same as Parse except it errors on
62 // partially parsed DDL statements.
63 func ParseStrictDDL(sql string) (Statement, error) {
64 tokenizer := NewStringTokenizer(sql)
65 if yyParse(tokenizer) != 0 {
66 return nil, tokenizer.LastError
67 }
68 return tokenizer.ParseTree, nil
69 }
70
71 // ParseNext parses a single SQL statement from the tokenizer
72 // returning a Statement which is the AST representation of the query.
73 // The tokenizer will always read up to the end of the statement, allowing for
74 // the next call to ParseNext to parse any subsequent SQL statements. When
75 // there are no more statements to parse, a error of io.EOF is returned.
76 func ParseNext(tokenizer *Tokenizer) (Statement, error) {
77 if tokenizer.lastChar == ';' {
78 tokenizer.next()
79 tokenizer.skipBlank()
80 }
81 if tokenizer.lastChar == eofChar {
82 return nil, io.EOF
83 }
84
85 tokenizer.reset()
86 tokenizer.multi = true
87 if yyParse(tokenizer) != 0 {
88 if tokenizer.partialDDL != nil {
89 tokenizer.ParseTree = tokenizer.partialDDL
90 return tokenizer.ParseTree, nil
91 }
92 return nil, tokenizer.LastError
93 }
94 return tokenizer.ParseTree, nil
95 }
96
97 // SplitStatement returns the first sql statement up to either a ; or EOF
98 // and the remainder from the given buffer
99 func SplitStatement(blob string) (string, string, error) {
100 tokenizer := NewStringTokenizer(blob)
101 tkn := 0
102 for {
103 tkn, _ = tokenizer.Scan()
104 if tkn == 0 || tkn == ';' || tkn == eofChar {
105 break
106 }
107 }
108 if tokenizer.LastError != nil {
109 return "", "", tokenizer.LastError
110 }
111 if tkn == ';' {
112 return blob[:tokenizer.Position-2], blob[tokenizer.Position-1:], nil
113 }
114 return blob, "", nil
115 }
116
117 // SplitStatementToPieces split raw sql statement that may have multi sql pieces to sql pieces
118 // returns the sql pieces blob contains; or error if sql cannot be parsed
119 func SplitStatementToPieces(blob string) (pieces []string, err error) {
120 pieces = make([]string, 0, 16)
121 tokenizer := NewStringTokenizer(blob)
122
123 tkn := 0
124 var stmt string
125 stmtBegin := 0
126 for {
127 tkn, _ = tokenizer.Scan()
128 if tkn == ';' {
129 stmt = blob[stmtBegin : tokenizer.Position-2]
130 pieces = append(pieces, stmt)
131 stmtBegin = tokenizer.Position - 1
132
133 } else if tkn == 0 || tkn == eofChar {
134 blobTail := tokenizer.Position - 2
135
136 if stmtBegin < blobTail {
137 stmt = blob[stmtBegin : blobTail+1]
138 pieces = append(pieces, stmt)
139 }
140 break
141 }
142 }
143
144 err = tokenizer.LastError
145 return
146 }
147
148 // SQLNode defines the interface for all nodes
149 // generated by the parser.
150 type SQLNode interface {
151 Format(buf *TrackedBuffer)
152 // walkSubtree calls visit on all underlying nodes
153 // of the subtree, but not the current one. Walking
154 // must be interrupted if visit returns an error.
155 walkSubtree(visit Visit) error
156 }
157
158 // Visit defines the signature of a function that
159 // can be used to visit all nodes of a parse tree.
160 type Visit func(node SQLNode) (kontinue bool, err error)
161
162 // Walk calls visit on every node.
163 // If visit returns true, the underlying nodes
164 // are also visited. If it returns an error, walking
165 // is interrupted, and the error is returned.
166 func Walk(visit Visit, nodes ...SQLNode) error {
167 for _, node := range nodes {
168 if node == nil {
169 continue
170 }
171 kontinue, err := visit(node)
172 if err != nil {
173 return err
174 }
175 if kontinue {
176 err = node.walkSubtree(visit)
177 if err != nil {
178 return err
179 }
180 }
181 }
182 return nil
183 }
184
185 // String returns a string representation of an SQLNode.
186 func String(node SQLNode) string {
187 if node == nil {
188 return "<nil>"
189 }
190
191 buf := NewTrackedBuffer(nil)
192 buf.Myprintf("%v", node)
193 return buf.String()
194 }
195
196 // Append appends the SQLNode to the buffer.
197 func Append(buf *bytes.Buffer, node SQLNode) {
198 tbuf := &TrackedBuffer{
199 Buffer: buf,
200 }
201 node.Format(tbuf)
202 }
203
204 // Statement represents a statement.
205 type Statement interface {
206 iStatement()
207 SQLNode
208 }
209
210 func (*Union) iStatement() {}
211 func (*Select) iStatement() {}
212 func (*Stream) iStatement() {}
213 func (*Insert) iStatement() {}
214 func (*Update) iStatement() {}
215 func (*Delete) iStatement() {}
216 func (*Set) iStatement() {}
217 func (*DBDDL) iStatement() {}
218 func (*DDL) iStatement() {}
219 func (*Show) iStatement() {}
220 func (*Use) iStatement() {}
221 func (*Begin) iStatement() {}
222 func (*Commit) iStatement() {}
223 func (*Rollback) iStatement() {}
224 func (*OtherRead) iStatement() {}
225 func (*OtherAdmin) iStatement() {}
226
227 // ParenSelect can actually not be a top level statement,
228 // but we have to allow it because it's a requirement
229 // of SelectStatement.
230 func (*ParenSelect) iStatement() {}
231
232 // SelectStatement any SELECT statement.
233 type SelectStatement interface {
234 iSelectStatement()
235 iStatement()
236 iInsertRows()
237 AddOrder(*Order)
238 SetLimit(*Limit)
239 SQLNode
240 }
241
242 func (*Select) iSelectStatement() {}
243 func (*Union) iSelectStatement() {}
244 func (*ParenSelect) iSelectStatement() {}
245
246 // Select represents a SELECT statement.
247 type Select struct {
248 Cache string
249 Comments Comments
250 Distinct string
251 Hints string
252 SelectExprs SelectExprs
253 From TableExprs
254 Where *Where
255 GroupBy GroupBy
256 Having *Where
257 OrderBy OrderBy
258 Limit *Limit
259 Lock string
260 }
261
262 // Select.Distinct
263 const (
264 DistinctStr = "distinct "
265 StraightJoinHint = "straight_join "
266 )
267
268 // Select.Lock
269 const (
270 ForUpdateStr = " for update"
271 ShareModeStr = " lock in share mode"
272 )
273
274 // Select.Cache
275 const (
276 SQLCacheStr = "sql_cache "
277 SQLNoCacheStr = "sql_no_cache "
278 )
279
280 // AddOrder adds an order by element
281 func (node *Select) AddOrder(order *Order) {
282 node.OrderBy = append(node.OrderBy, order)
283 }
284
285 // SetLimit sets the limit clause
286 func (node *Select) SetLimit(limit *Limit) {
287 node.Limit = limit
288 }
289
290 // Format formats the node.
291 func (node *Select) Format(buf *TrackedBuffer) {
292 buf.Myprintf("select %v%s%s%s%v from %v%v%v%v%v%v%s",
293 node.Comments, node.Cache, node.Distinct, node.Hints, node.SelectExprs,
294 node.From, node.Where,
295 node.GroupBy, node.Having, node.OrderBy,
296 node.Limit, node.Lock)
297 }
298
299 func (node *Select) walkSubtree(visit Visit) error {
300 if node == nil {
301 return nil
302 }
303 return Walk(
304 visit,
305 node.Comments,
306 node.SelectExprs,
307 node.From,
308 node.Where,
309 node.GroupBy,
310 node.Having,
311 node.OrderBy,
312 node.Limit,
313 )
314 }
315
316 // AddWhere adds the boolean expression to the
317 // WHERE clause as an AND condition. If the expression
318 // is an OR clause, it parenthesizes it. Currently,
319 // the OR operator is the only one that's lower precedence
320 // than AND.
321 func (node *Select) AddWhere(expr Expr) {
322 if _, ok := expr.(*OrExpr); ok {
323 expr = &ParenExpr{Expr: expr}
324 }
325 if node.Where == nil {
326 node.Where = &Where{
327 Type: WhereStr,
328 Expr: expr,
329 }
330 return
331 }
332 node.Where.Expr = &AndExpr{
333 Left: node.Where.Expr,
334 Right: expr,
335 }
336 return
337 }
338
339 // AddHaving adds the boolean expression to the
340 // HAVING clause as an AND condition. If the expression
341 // is an OR clause, it parenthesizes it. Currently,
342 // the OR operator is the only one that's lower precedence
343 // than AND.
344 func (node *Select) AddHaving(expr Expr) {
345 if _, ok := expr.(*OrExpr); ok {
346 expr = &ParenExpr{Expr: expr}
347 }
348 if node.Having == nil {
349 node.Having = &Where{
350 Type: HavingStr,
351 Expr: expr,
352 }
353 return
354 }
355 node.Having.Expr = &AndExpr{
356 Left: node.Having.Expr,
357 Right: expr,
358 }
359 return
360 }
361
362 // ParenSelect is a parenthesized SELECT statement.
363 type ParenSelect struct {
364 Select SelectStatement
365 }
366
367 // AddOrder adds an order by element
368 func (node *ParenSelect) AddOrder(order *Order) {
369 panic("unreachable")
370 }
371
372 // SetLimit sets the limit clause
373 func (node *ParenSelect) SetLimit(limit *Limit) {
374 panic("unreachable")
375 }
376
377 // Format formats the node.
378 func (node *ParenSelect) Format(buf *TrackedBuffer) {
379 buf.Myprintf("(%v)", node.Select)
380 }
381
382 func (node *ParenSelect) walkSubtree(visit Visit) error {
383 if node == nil {
384 return nil
385 }
386 return Walk(
387 visit,
388 node.Select,
389 )
390 }
391
392 // Union represents a UNION statement.
393 type Union struct {
394 Type string
395 Left, Right SelectStatement
396 OrderBy OrderBy
397 Limit *Limit
398 Lock string
399 }
400
401 // Union.Type
402 const (
403 UnionStr = "union"
404 UnionAllStr = "union all"
405 UnionDistinctStr = "union distinct"
406 )
407
408 // AddOrder adds an order by element
409 func (node *Union) AddOrder(order *Order) {
410 node.OrderBy = append(node.OrderBy, order)
411 }
412
413 // SetLimit sets the limit clause
414 func (node *Union) SetLimit(limit *Limit) {
415 node.Limit = limit
416 }
417
418 // Format formats the node.
419 func (node *Union) Format(buf *TrackedBuffer) {
420 buf.Myprintf("%v %s %v%v%v%s", node.Left, node.Type, node.Right,
421 node.OrderBy, node.Limit, node.Lock)
422 }
423
424 func (node *Union) walkSubtree(visit Visit) error {
425 if node == nil {
426 return nil
427 }
428 return Walk(
429 visit,
430 node.Left,
431 node.Right,
432 )
433 }
434
435 // Stream represents a SELECT statement.
436 type Stream struct {
437 Comments Comments
438 SelectExpr SelectExpr
439 Table TableName
440 }
441
442 // Format formats the node.
443 func (node *Stream) Format(buf *TrackedBuffer) {
444 buf.Myprintf("stream %v%v from %v",
445 node.Comments, node.SelectExpr, node.Table)
446 }
447
448 func (node *Stream) walkSubtree(visit Visit) error {
449 if node == nil {
450 return nil
451 }
452 return Walk(
453 visit,
454 node.Comments,
455 node.SelectExpr,
456 node.Table,
457 )
458 }
459
460 // Insert represents an INSERT or REPLACE statement.
461 // Per the MySQL docs, http://dev.mysql.com/doc/refman/5.7/en/replace.html
462 // Replace is the counterpart to `INSERT IGNORE`, and works exactly like a
463 // normal INSERT except if the row exists. In that case it first deletes
464 // the row and re-inserts with new values. For that reason we keep it as an Insert struct.
465 // Replaces are currently disallowed in sharded schemas because
466 // of the implications the deletion part may have on vindexes.
467 // If you add fields here, consider adding them to calls to validateSubquerySamePlan.
468 type Insert struct {
469 Action string
470 Comments Comments
471 Ignore string
472 Table TableName
473 Partitions Partitions
474 Columns Columns
475 Rows InsertRows
476 OnDup OnDup
477 }
478
479 // DDL strings.
480 const (
481 InsertStr = "insert"
482 ReplaceStr = "replace"
483 )
484
485 // Format formats the node.
486 func (node *Insert) Format(buf *TrackedBuffer) {
487 buf.Myprintf("%s %v%sinto %v%v%v %v%v",
488 node.Action,
489 node.Comments, node.Ignore,
490 node.Table, node.Partitions, node.Columns, node.Rows, node.OnDup)
491 }
492
493 func (node *Insert) walkSubtree(visit Visit) error {
494 if node == nil {
495 return nil
496 }
497 return Walk(
498 visit,
499 node.Comments,
500 node.Table,
501 node.Columns,
502 node.Rows,
503 node.OnDup,
504 )
505 }
506
507 // InsertRows represents the rows for an INSERT statement.
508 type InsertRows interface {
509 iInsertRows()
510 SQLNode
511 }
512
513 func (*Select) iInsertRows() {}
514 func (*Union) iInsertRows() {}
515 func (Values) iInsertRows() {}
516 func (*ParenSelect) iInsertRows() {}
517
518 // Update represents an UPDATE statement.
519 // If you add fields here, consider adding them to calls to validateSubquerySamePlan.
520 type Update struct {
521 Comments Comments
522 TableExprs TableExprs
523 Exprs UpdateExprs
524 Where *Where
525 OrderBy OrderBy
526 Limit *Limit
527 }
528
529 // Format formats the node.
530 func (node *Update) Format(buf *TrackedBuffer) {
531 buf.Myprintf("update %v%v set %v%v%v%v",
532 node.Comments, node.TableExprs,
533 node.Exprs, node.Where, node.OrderBy, node.Limit)
534 }
535
536 func (node *Update) walkSubtree(visit Visit) error {
537 if node == nil {
538 return nil
539 }
540 return Walk(
541 visit,
542 node.Comments,
543 node.TableExprs,
544 node.Exprs,
545 node.Where,
546 node.OrderBy,
547 node.Limit,
548 )
549 }
550
551 // Delete represents a DELETE statement.
552 // If you add fields here, consider adding them to calls to validateSubquerySamePlan.
553 type Delete struct {
554 Comments Comments
555 Targets TableNames
556 TableExprs TableExprs
557 Partitions Partitions
558 Where *Where
559 OrderBy OrderBy
560 Limit *Limit
561 }
562
563 // Format formats the node.
564 func (node *Delete) Format(buf *TrackedBuffer) {
565 buf.Myprintf("delete %v", node.Comments)
566 if node.Targets != nil {
567 buf.Myprintf("%v ", node.Targets)
568 }
569 buf.Myprintf("from %v%v%v%v%v", node.TableExprs, node.Partitions, node.Where, node.OrderBy, node.Limit)
570 }
571
572 func (node *Delete) walkSubtree(visit Visit) error {
573 if node == nil {
574 return nil
575 }
576 return Walk(
577 visit,
578 node.Comments,
579 node.Targets,
580 node.TableExprs,
581 node.Where,
582 node.OrderBy,
583 node.Limit,
584 )
585 }
586
587 // Set represents a SET statement.
588 type Set struct {
589 Comments Comments
590 Exprs SetExprs
591 Scope string
592 }
593
594 // Set.Scope or Show.Scope
595 const (
596 SessionStr = "session"
597 GlobalStr = "global"
598 )
599
600 // Format formats the node.
601 func (node *Set) Format(buf *TrackedBuffer) {
602 if node.Scope == "" {
603 buf.Myprintf("set %v%v", node.Comments, node.Exprs)
604 } else {
605 buf.Myprintf("set %v%s %v", node.Comments, node.Scope, node.Exprs)
606 }
607 }
608
609 func (node *Set) walkSubtree(visit Visit) error {
610 if node == nil {
611 return nil
612 }
613 return Walk(
614 visit,
615 node.Comments,
616 node.Exprs,
617 )
618 }
619
620 // DBDDL represents a CREATE, DROP database statement.
621 type DBDDL struct {
622 Action string
623 DBName string
624 IfExists bool
625 Collate string
626 Charset string
627 }
628
629 // Format formats the node.
630 func (node *DBDDL) Format(buf *TrackedBuffer) {
631 switch node.Action {
632 case CreateStr:
633 buf.WriteString(fmt.Sprintf("%s database %s", node.Action, node.DBName))
634 case DropStr:
635 exists := ""
636 if node.IfExists {
637 exists = " if exists"
638 }
639 buf.WriteString(fmt.Sprintf("%s database%s %v", node.Action, exists, node.DBName))
640 }
641 }
642
643 // walkSubtree walks the nodes of the subtree.
644 func (node *DBDDL) walkSubtree(visit Visit) error {
645 return nil
646 }
647
648 // DDL represents a CREATE, ALTER, DROP, RENAME or TRUNCATE statement.
649 // Table is set for AlterStr, DropStr, RenameStr, TruncateStr
650 // NewName is set for AlterStr, CreateStr, RenameStr.
651 // VindexSpec is set for CreateVindexStr, DropVindexStr, AddColVindexStr, DropColVindexStr
652 // VindexCols is set for AddColVindexStr
653 type DDL struct {
654 Action string
655 Table TableName
656 NewName TableName
657 IfExists bool
658 TableSpec *TableSpec
659 PartitionSpec *PartitionSpec
660 VindexSpec *VindexSpec
661 VindexCols []ColIdent
662 }
663
664 // DDL strings.
665 const (
666 CreateStr = "create"
667 AlterStr = "alter"
668 DropStr = "drop"
669 RenameStr = "rename"
670 TruncateStr = "truncate"
671 CreateVindexStr = "create vindex"
672 AddColVindexStr = "add vindex"
673 DropColVindexStr = "drop vindex"
674
675 // Vindex DDL param to specify the owner of a vindex
676 VindexOwnerStr = "owner"
677 )
678
679 // Format formats the node.
680 func (node *DDL) Format(buf *TrackedBuffer) {
681 switch node.Action {
682 case CreateStr:
683 if node.TableSpec == nil {
684 buf.Myprintf("%s table %v", node.Action, node.NewName)
685 } else {
686 buf.Myprintf("%s table %v %v", node.Action, node.NewName, node.TableSpec)
687 }
688 case DropStr:
689 exists := ""
690 if node.IfExists {
691 exists = " if exists"
692 }
693 buf.Myprintf("%s table%s %v", node.Action, exists, node.Table)
694 case RenameStr:
695 buf.Myprintf("%s table %v to %v", node.Action, node.Table, node.NewName)
696 case AlterStr:
697 if node.PartitionSpec != nil {
698 buf.Myprintf("%s table %v %v", node.Action, node.Table, node.PartitionSpec)
699 } else {
700 buf.Myprintf("%s table %v", node.Action, node.Table)
701 }
702 case CreateVindexStr:
703 buf.Myprintf("%s %v %v", node.Action, node.VindexSpec.Name, node.VindexSpec)
704 case AddColVindexStr:
705 buf.Myprintf("alter table %v %s %v (", node.Table, node.Action, node.VindexSpec.Name)
706 for i, col := range node.VindexCols {
707 if i != 0 {
708 buf.Myprintf(", %v", col)
709 } else {
710 buf.Myprintf("%v", col)
711 }
712 }
713 buf.Myprintf(")")
714 if node.VindexSpec.Type.String() != "" {
715 buf.Myprintf(" %v", node.VindexSpec)
716 }
717 case DropColVindexStr:
718 buf.Myprintf("alter table %v %s %v", node.Table, node.Action, node.VindexSpec.Name)
719 default:
720 buf.Myprintf("%s table %v", node.Action, node.Table)
721 }
722 }
723
724 func (node *DDL) walkSubtree(visit Visit) error {
725 if node == nil {
726 return nil
727 }
728 return Walk(
729 visit,
730 node.Table,
731 node.NewName,
732 )
733 }
734
735 // Partition strings
736 const (
737 ReorganizeStr = "reorganize partition"
738 )
739
740 // PartitionSpec describe partition actions (for alter and create)
741 type PartitionSpec struct {
742 Action string
743 Name ColIdent
744 Definitions []*PartitionDefinition
745 }
746
747 // Format formats the node.
748 func (node *PartitionSpec) Format(buf *TrackedBuffer) {
749 switch node.Action {
750 case ReorganizeStr:
751 buf.Myprintf("%s %v into (", node.Action, node.Name)
752 var prefix string
753 for _, pd := range node.Definitions {
754 buf.Myprintf("%s%v", prefix, pd)
755 prefix = ", "
756 }
757 buf.Myprintf(")")
758 default:
759 panic("unimplemented")
760 }
761 }
762
763 func (node *PartitionSpec) walkSubtree(visit Visit) error {
764 if node == nil {
765 return nil
766 }
767 if err := Walk(visit, node.Name); err != nil {
768 return err
769 }
770 for _, def := range node.Definitions {
771 if err := Walk(visit, def); err != nil {
772 return err
773 }
774 }
775 return nil
776 }
777
778 // PartitionDefinition describes a very minimal partition definition
779 type PartitionDefinition struct {
780 Name ColIdent
781 Limit Expr
782 Maxvalue bool
783 }
784
785 // Format formats the node
786 func (node *PartitionDefinition) Format(buf *TrackedBuffer) {
787 if !node.Maxvalue {
788 buf.Myprintf("partition %v values less than (%v)", node.Name, node.Limit)
789 } else {
790 buf.Myprintf("partition %v values less than (maxvalue)", node.Name)
791 }
792 }
793
794 func (node *PartitionDefinition) walkSubtree(visit Visit) error {
795 if node == nil {
796 return nil
797 }
798 return Walk(
799 visit,
800 node.Name,
801 node.Limit,
802 )
803 }
804
805 // TableSpec describes the structure of a table from a CREATE TABLE statement
806 type TableSpec struct {
807 Columns []*ColumnDefinition
808 Indexes []*IndexDefinition
809 Options string
810 }
811
812 // Format formats the node.
813 func (ts *TableSpec) Format(buf *TrackedBuffer) {
814 buf.Myprintf("(\n")
815 for i, col := range ts.Columns {
816 if i == 0 {
817 buf.Myprintf("\t%v", col)
818 } else {
819 buf.Myprintf(",\n\t%v", col)
820 }
821 }
822 for _, idx := range ts.Indexes {
823 buf.Myprintf(",\n\t%v", idx)
824 }
825
826 buf.Myprintf("\n)%s", strings.Replace(ts.Options, ", ", ",\n ", -1))
827 }
828
829 // AddColumn appends the given column to the list in the spec
830 func (ts *TableSpec) AddColumn(cd *ColumnDefinition) {
831 ts.Columns = append(ts.Columns, cd)
832 }
833
834 // AddIndex appends the given index to the list in the spec
835 func (ts *TableSpec) AddIndex(id *IndexDefinition) {
836 ts.Indexes = append(ts.Indexes, id)
837 }
838
839 func (ts *TableSpec) walkSubtree(visit Visit) error {
840 if ts == nil {
841 return nil
842 }
843
844 for _, n := range ts.Columns {
845 if err := Walk(visit, n); err != nil {
846 return err
847 }
848 }
849
850 for _, n := range ts.Indexes {
851 if err := Walk(visit, n); err != nil {
852 return err
853 }
854 }
855
856 return nil
857 }
858
859 // ColumnDefinition describes a column in a CREATE TABLE statement
860 type ColumnDefinition struct {
861 Name ColIdent
862 Type ColumnType
863 }
864
865 // Format formats the node.
866 func (col *ColumnDefinition) Format(buf *TrackedBuffer) {
867 buf.Myprintf("%v %v", col.Name, &col.Type)
868 }
869
870 func (col *ColumnDefinition) walkSubtree(visit Visit) error {
871 if col == nil {
872 return nil
873 }
874 return Walk(
875 visit,
876 col.Name,
877 &col.Type,
878 )
879 }
880
881 // ColumnType represents a sql type in a CREATE TABLE statement
882 // All optional fields are nil if not specified
883 type ColumnType struct {
884 // The base type string
885 Type string
886
887 // Generic field options.
888 NotNull BoolVal
889 Autoincrement BoolVal
890 Default *SQLVal
891 OnUpdate *SQLVal
892 Comment *SQLVal
893
894 // Numeric field options
895 Length *SQLVal
896 Unsigned BoolVal
897 Zerofill BoolVal
898 Scale *SQLVal
899
900 // Text field options
901 Charset string
902 Collate string
903
904 // Enum values
905 EnumValues []string
906
907 // Key specification
908 KeyOpt ColumnKeyOption
909 }
910
911 // Format returns a canonical string representation of the type and all relevant options
912 func (ct *ColumnType) Format(buf *TrackedBuffer) {
913 buf.Myprintf("%s", ct.Type)
914
915 if ct.Length != nil && ct.Scale != nil {
916 buf.Myprintf("(%v,%v)", ct.Length, ct.Scale)
917
918 } else if ct.Length != nil {
919 buf.Myprintf("(%v)", ct.Length)
920 }
921
922 if ct.EnumValues != nil {
923 buf.Myprintf("(%s)", strings.Join(ct.EnumValues, ", "))
924 }
925
926 opts := make([]string, 0, 16)
927 if ct.Unsigned {
928 opts = append(opts, keywordStrings[UNSIGNED])
929 }
930 if ct.Zerofill {
931 opts = append(opts, keywordStrings[ZEROFILL])
932 }
933 if ct.Charset != "" {
934 opts = append(opts, keywordStrings[CHARACTER], keywordStrings[SET], ct.Charset)
935 }
936 if ct.Collate != "" {
937 opts = append(opts, keywordStrings[COLLATE], ct.Collate)
938 }
939 if ct.NotNull {
940 opts = append(opts, keywordStrings[NOT], keywordStrings[NULL])
941 }
942 if ct.Default != nil {
943 opts = append(opts, keywordStrings[DEFAULT], String(ct.Default))
944 }
945 if ct.OnUpdate != nil {
946 opts = append(opts, keywordStrings[ON], keywordStrings[UPDATE], String(ct.OnUpdate))
947 }
948 if ct.Autoincrement {
949 opts = append(opts, keywordStrings[AUTO_INCREMENT])
950 }
951 if ct.Comment != nil {
952 opts = append(opts, keywordStrings[COMMENT_KEYWORD], String(ct.Comment))
953 }
954 if ct.KeyOpt == colKeyPrimary {
955 opts = append(opts, keywordStrings[PRIMARY], keywordStrings[KEY])
956 }
957 if ct.KeyOpt == colKeyUnique {
958 opts = append(opts, keywordStrings[UNIQUE])
959 }
960 if ct.KeyOpt == colKeyUniqueKey {
961 opts = append(opts, keywordStrings[UNIQUE], keywordStrings[KEY])
962 }
963 if ct.KeyOpt == colKeySpatialKey {
964 opts = append(opts, keywordStrings[SPATIAL], keywordStrings[KEY])
965 }
966 if ct.KeyOpt == colKey {
967 opts = append(opts, keywordStrings[KEY])
968 }
969
970 if len(opts) != 0 {
971 buf.Myprintf(" %s", strings.Join(opts, " "))
972 }
973 }
974
975 // DescribeType returns the abbreviated type information as required for
976 // describe table
977 func (ct *ColumnType) DescribeType() string {
978 buf := NewTrackedBuffer(nil)
979 buf.Myprintf("%s", ct.Type)
980 if ct.Length != nil && ct.Scale != nil {
981 buf.Myprintf("(%v,%v)", ct.Length, ct.Scale)
982 } else if ct.Length != nil {
983 buf.Myprintf("(%v)", ct.Length)
984 }
985
986 opts := make([]string, 0, 16)
987 if ct.Unsigned {
988 opts = append(opts, keywordStrings[UNSIGNED])
989 }
990 if ct.Zerofill {
991 opts = append(opts, keywordStrings[ZEROFILL])
992 }
993 if len(opts) != 0 {
994 buf.Myprintf(" %s", strings.Join(opts, " "))
995 }
996 return buf.String()
997 }
998
999 // SQLType returns the sqltypes type code for the given column
1000 func (ct *ColumnType) SQLType() querypb.Type {
1001 switch ct.Type {
1002 case keywordStrings[TINYINT]:
1003 if ct.Unsigned {
1004 return sqltypes.Uint8
1005 }
1006 return sqltypes.Int8
1007 case keywordStrings[SMALLINT]:
1008 if ct.Unsigned {
1009 return sqltypes.Uint16
1010 }
1011 return sqltypes.Int16
1012 case keywordStrings[MEDIUMINT]:
1013 if ct.Unsigned {
1014 return sqltypes.Uint24
1015 }
1016 return sqltypes.Int24
1017 case keywordStrings[INT]:
1018 fallthrough
1019 case keywordStrings[INTEGER]:
1020 if ct.Unsigned {
1021 return sqltypes.Uint32
1022 }
1023 return sqltypes.Int32
1024 case keywordStrings[BIGINT]:
1025 if ct.Unsigned {
1026 return sqltypes.Uint64
1027 }
1028 return sqltypes.Int64
1029 case keywordStrings[TEXT]:
1030 return sqltypes.Text
1031 case keywordStrings[TINYTEXT]:
1032 return sqltypes.Text
1033 case keywordStrings[MEDIUMTEXT]:
1034 return sqltypes.Text
1035 case keywordStrings[LONGTEXT]:
1036 return sqltypes.Text
1037 case keywordStrings[BLOB]:
1038 return sqltypes.Blob
1039 case keywordStrings[TINYBLOB]:
1040 return sqltypes.Blob
1041 case keywordStrings[MEDIUMBLOB]:
1042 return sqltypes.Blob
1043 case keywordStrings[LONGBLOB]:
1044 return sqltypes.Blob
1045 case keywordStrings[CHAR]:
1046 return sqltypes.Char
1047 case keywordStrings[VARCHAR]:
1048 return sqltypes.VarChar
1049 case keywordStrings[BINARY]:
1050 return sqltypes.Binary
1051 case keywordStrings[VARBINARY]:
1052 return sqltypes.VarBinary
1053 case keywordStrings[DATE]:
1054 return sqltypes.Date
1055 case keywordStrings[TIME]:
1056 return sqltypes.Time
1057 case keywordStrings[DATETIME]:
1058 return sqltypes.Datetime
1059 case keywordStrings[TIMESTAMP]:
1060 return sqltypes.Timestamp
1061 case keywordStrings[YEAR]:
1062 return sqltypes.Year
1063 case keywordStrings[FLOAT_TYPE]:
1064 return sqltypes.Float32
1065 case keywordStrings[DOUBLE]:
1066 return sqltypes.Float64
1067 case keywordStrings[DECIMAL]:
1068 return sqltypes.Decimal
1069 case keywordStrings[BIT]:
1070 return sqltypes.Bit
1071 case keywordStrings[ENUM]:
1072 return sqltypes.Enum
1073 case keywordStrings[SET]:
1074 return sqltypes.Set
1075 case keywordStrings[JSON]:
1076 return sqltypes.TypeJSON
1077 case keywordStrings[GEOMETRY]:
1078 return sqltypes.Geometry
1079 case keywordStrings[POINT]:
1080 return sqltypes.Geometry
1081 case keywordStrings[LINESTRING]:
1082 return sqltypes.Geometry
1083 case keywordStrings[POLYGON]:
1084 return sqltypes.Geometry
1085 case keywordStrings[GEOMETRYCOLLECTION]:
1086 return sqltypes.Geometry
1087 case keywordStrings[MULTIPOINT]:
1088 return sqltypes.Geometry
1089 case keywordStrings[MULTILINESTRING]:
1090 return sqltypes.Geometry
1091 case keywordStrings[MULTIPOLYGON]:
1092 return sqltypes.Geometry
1093 }
1094 panic("unimplemented type " + ct.Type)
1095 }
1096
1097 func (ct *ColumnType) walkSubtree(visit Visit) error {
1098 return nil
1099 }
1100
1101 // IndexDefinition describes an index in a CREATE TABLE statement
1102 type IndexDefinition struct {
1103 Info *IndexInfo
1104 Columns []*IndexColumn
1105 Options []*IndexOption
1106 }
1107
1108 // Format formats the node.
1109 func (idx *IndexDefinition) Format(buf *TrackedBuffer) {
1110 buf.Myprintf("%v (", idx.Info)
1111 for i, col := range idx.Columns {
1112 if i != 0 {
1113 buf.Myprintf(", %v", col.Column)
1114 } else {
1115 buf.Myprintf("%v", col.Column)
1116 }
1117 if col.Length != nil {
1118 buf.Myprintf("(%v)", col.Length)
1119 }
1120 }
1121 buf.Myprintf(")")
1122
1123 for _, opt := range idx.Options {
1124 buf.Myprintf(" %s", opt.Name)
1125 if opt.Using != "" {
1126 buf.Myprintf(" %s", opt.Using)
1127 } else {
1128 buf.Myprintf(" %v", opt.Value)
1129 }
1130 }
1131 }
1132
1133 func (idx *IndexDefinition) walkSubtree(visit Visit) error {
1134 if idx == nil {
1135 return nil
1136 }
1137
1138 for _, n := range idx.Columns {
1139 if err := Walk(visit, n.Column); err != nil {
1140 return err
1141 }
1142 }
1143
1144 return nil
1145 }
1146
1147 // IndexInfo describes the name and type of an index in a CREATE TABLE statement
1148 type IndexInfo struct {
1149 Type string
1150 Name ColIdent
1151 Primary bool
1152 Spatial bool
1153 Unique bool
1154 }
1155
1156 // Format formats the node.
1157 func (ii *IndexInfo) Format(buf *TrackedBuffer) {
1158 if ii.Primary {
1159 buf.Myprintf("%s", ii.Type)
1160 } else {
1161 buf.Myprintf("%s %v", ii.Type, ii.Name)
1162 }
1163 }
1164
1165 func (ii *IndexInfo) walkSubtree(visit Visit) error {
1166 return Walk(visit, ii.Name)
1167 }
1168
1169 // IndexColumn describes a column in an index definition with optional length
1170 type IndexColumn struct {
1171 Column ColIdent
1172 Length *SQLVal
1173 }
1174
1175 // LengthScaleOption is used for types that have an optional length
1176 // and scale
1177 type LengthScaleOption struct {
1178 Length *SQLVal
1179 Scale *SQLVal
1180 }
1181
1182 // IndexOption is used for trailing options for indexes: COMMENT, KEY_BLOCK_SIZE, USING
1183 type IndexOption struct {
1184 Name string
1185 Value *SQLVal
1186 Using string
1187 }
1188
1189 // ColumnKeyOption indicates whether or not the given column is defined as an
1190 // index element and contains the type of the option
1191 type ColumnKeyOption int
1192
1193 const (
1194 colKeyNone ColumnKeyOption = iota
1195 colKeyPrimary
1196 colKeySpatialKey
1197 colKeyUnique
1198 colKeyUniqueKey
1199 colKey
1200 )
1201
1202 // VindexSpec defines a vindex for a CREATE VINDEX or DROP VINDEX statement
1203 type VindexSpec struct {
1204 Name ColIdent
1205 Type ColIdent
1206 Params []VindexParam
1207 }
1208
1209 // ParseParams parses the vindex parameter list, pulling out the special-case
1210 // "owner" parameter
1211 func (node *VindexSpec) ParseParams() (string, map[string]string) {
1212 var owner string
1213 params := map[string]string{}
1214 for _, p := range node.Params {
1215 if p.Key.Lowered() == VindexOwnerStr {
1216 owner = p.Val
1217 } else {
1218 params[p.Key.String()] = p.Val
1219 }
1220 }
1221 return owner, params
1222 }
1223
1224 // Format formats the node. The "CREATE VINDEX" preamble was formatted in
1225 // the containing DDL node Format, so this just prints the type, any
1226 // parameters, and optionally the owner
1227 func (node *VindexSpec) Format(buf *TrackedBuffer) {
1228 buf.Myprintf("using %v", node.Type)
1229
1230 numParams := len(node.Params)
1231 if numParams != 0 {
1232 buf.Myprintf(" with ")
1233 for i, p := range node.Params {
1234 if i != 0 {
1235 buf.Myprintf(", ")
1236 }
1237 buf.Myprintf("%v", p)
1238 }
1239 }
1240 }
1241
1242 func (node *VindexSpec) walkSubtree(visit Visit) error {
1243 err := Walk(visit,
1244 node.Name,
1245 )
1246
1247 if err != nil {
1248 return err
1249 }
1250
1251 for _, p := range node.Params {
1252 err := Walk(visit, p)
1253
1254 if err != nil {
1255 return err
1256 }
1257 }
1258 return nil
1259 }
1260
1261 // VindexParam defines a key/value parameter for a CREATE VINDEX statement
1262 type VindexParam struct {
1263 Key ColIdent
1264 Val string
1265 }
1266
1267 // Format formats the node.
1268 func (node VindexParam) Format(buf *TrackedBuffer) {
1269 buf.Myprintf("%s=%s", node.Key.String(), node.Val)
1270 }
1271
1272 func (node VindexParam) walkSubtree(visit Visit) error {
1273 return Walk(visit,
1274 node.Key,
1275 )
1276 }
1277
1278 // Show represents a show statement.
1279 type Show struct {
1280 Type string
1281 OnTable TableName
1282 ShowTablesOpt *ShowTablesOpt
1283 Scope string
1284 }
1285
1286 // Format formats the node.
1287 func (node *Show) Format(buf *TrackedBuffer) {
1288 if node.Type == "tables" && node.ShowTablesOpt != nil {
1289 opt := node.ShowTablesOpt
1290 if opt.DbName != "" {
1291 if opt.Filter != nil {
1292 buf.Myprintf("show %s%stables from %s %v", opt.Extended, opt.Full, opt.DbName, opt.Filter)
1293 } else {
1294 buf.Myprintf("show %s%stables from %s", opt.Extended, opt.Full, opt.DbName)
1295 }
1296 } else {
1297 if opt.Filter != nil {
1298 buf.Myprintf("show %s%stables %v", opt.Extended, opt.Full, opt.Filter)
1299 } else {
1300 buf.Myprintf("show %s%stables", opt.Extended, opt.Full)
1301 }
1302 }
1303 return
1304 }
1305 if node.Scope == "" {
1306 buf.Myprintf("show %s", node.Type)
1307 } else {
1308 buf.Myprintf("show %s %s", node.Scope, node.Type)
1309 }
1310 if node.HasOnTable() {
1311 buf.Myprintf(" on %v", node.OnTable)
1312 }
1313 }
1314
1315 // HasOnTable returns true if the show statement has an "on" clause
1316 func (node *Show) HasOnTable() bool {
1317 return node.OnTable.Name.v != ""
1318 }
1319
1320 func (node *Show) walkSubtree(visit Visit) error {
1321 return nil
1322 }
1323
1324 // ShowTablesOpt is show tables option
1325 type ShowTablesOpt struct {
1326 Extended string
1327 Full string
1328 DbName string
1329 Filter *ShowFilter
1330 }
1331
1332 // ShowFilter is show tables filter
1333 type ShowFilter struct {
1334 Like string
1335 Filter Expr
1336 }
1337
1338 // Format formats the node.
1339 func (node *ShowFilter) Format(buf *TrackedBuffer) {
1340 if node.Like != "" {
1341 buf.Myprintf("like '%s'", node.Like)
1342 } else {
1343 buf.Myprintf("where %v", node.Filter)
1344 }
1345 }
1346
1347 func (node *ShowFilter) walkSubtree(visit Visit) error {
1348 return nil
1349 }
1350
1351 // Use represents a use statement.
1352 type Use struct {
1353 DBName TableIdent
1354 }
1355
1356 // Format formats the node.
1357 func (node *Use) Format(buf *TrackedBuffer) {
1358 if node.DBName.v != "" {
1359 buf.Myprintf("use %v", node.DBName)
1360 } else {
1361 buf.Myprintf("use")
1362 }
1363 }
1364
1365 func (node *Use) walkSubtree(visit Visit) error {
1366 return Walk(visit, node.DBName)
1367 }
1368
1369 // Begin represents a Begin statement.
1370 type Begin struct{}
1371
1372 // Format formats the node.
1373 func (node *Begin) Format(buf *TrackedBuffer) {
1374 buf.WriteString("begin")
1375 }
1376
1377 func (node *Begin) walkSubtree(visit Visit) error {
1378 return nil
1379 }
1380
1381 // Commit represents a Commit statement.
1382 type Commit struct{}
1383
1384 // Format formats the node.
1385 func (node *Commit) Format(buf *TrackedBuffer) {
1386 buf.WriteString("commit")
1387 }
1388
1389 func (node *Commit) walkSubtree(visit Visit) error {
1390 return nil
1391 }
1392
1393 // Rollback represents a Rollback statement.
1394 type Rollback struct{}
1395
1396 // Format formats the node.
1397 func (node *Rollback) Format(buf *TrackedBuffer) {
1398 buf.WriteString("rollback")
1399 }
1400
1401 func (node *Rollback) walkSubtree(visit Visit) error {
1402 return nil
1403 }
1404
1405 // OtherRead represents a DESCRIBE, or EXPLAIN statement.
1406 // It should be used only as an indicator. It does not contain
1407 // the full AST for the statement.
1408 type OtherRead struct{}
1409
1410 // Format formats the node.
1411 func (node *OtherRead) Format(buf *TrackedBuffer) {
1412 buf.WriteString("otherread")
1413 }
1414
1415 func (node *OtherRead) walkSubtree(visit Visit) error {
1416 return nil
1417 }
1418
1419 // OtherAdmin represents a misc statement that relies on ADMIN privileges,
1420 // such as REPAIR, OPTIMIZE, or TRUNCATE statement.
1421 // It should be used only as an indicator. It does not contain
1422 // the full AST for the statement.
1423 type OtherAdmin struct{}
1424
1425 // Format formats the node.
1426 func (node *OtherAdmin) Format(buf *TrackedBuffer) {
1427 buf.WriteString("otheradmin")
1428 }
1429
1430 func (node *OtherAdmin) walkSubtree(visit Visit) error {
1431 return nil
1432 }
1433
1434 // Comments represents a list of comments.
1435 type Comments [][]byte
1436
1437 // Format formats the node.
1438 func (node Comments) Format(buf *TrackedBuffer) {
1439 for _, c := range node {
1440 buf.Myprintf("%s ", c)
1441 }
1442 }
1443
1444 func (node Comments) walkSubtree(visit Visit) error {
1445 return nil
1446 }
1447
1448 // SelectExprs represents SELECT expressions.
1449 type SelectExprs []SelectExpr
1450
1451 // Format formats the node.
1452 func (node SelectExprs) Format(buf *TrackedBuffer) {
1453 var prefix string
1454 for _, n := range node {
1455 buf.Myprintf("%s%v", prefix, n)
1456 prefix = ", "
1457 }
1458 }
1459
1460 func (node SelectExprs) walkSubtree(visit Visit) error {
1461 for _, n := range node {
1462 if err := Walk(visit, n); err != nil {
1463 return err
1464 }
1465 }
1466 return nil
1467 }
1468
1469 // SelectExpr represents a SELECT expression.
1470 type SelectExpr interface {
1471 iSelectExpr()
1472 SQLNode
1473 }
1474
1475 func (*StarExpr) iSelectExpr() {}
1476 func (*AliasedExpr) iSelectExpr() {}
1477 func (Nextval) iSelectExpr() {}
1478
1479 // StarExpr defines a '*' or 'table.*' expression.
1480 type StarExpr struct {
1481 TableName TableName
1482 }
1483
1484 // Format formats the node.
1485 func (node *StarExpr) Format(buf *TrackedBuffer) {
1486 if !node.TableName.IsEmpty() {
1487 buf.Myprintf("%v.", node.TableName)
1488 }
1489 buf.Myprintf("*")
1490 }
1491
1492 func (node *StarExpr) walkSubtree(visit Visit) error {
1493 if node == nil {
1494 return nil
1495 }
1496 return Walk(
1497 visit,
1498 node.TableName,
1499 )
1500 }
1501
1502 // AliasedExpr defines an aliased SELECT expression.
1503 type AliasedExpr struct {
1504 Expr Expr
1505 As ColIdent
1506 }
1507
1508 // Format formats the node.
1509 func (node *AliasedExpr) Format(buf *TrackedBuffer) {
1510 buf.Myprintf("%v", node.Expr)
1511 if !node.As.IsEmpty() {
1512 buf.Myprintf(" as %v", node.As)
1513 }
1514 }
1515
1516 func (node *AliasedExpr) walkSubtree(visit Visit) error {
1517 if node == nil {
1518 return nil
1519 }
1520 return Walk(
1521 visit,
1522 node.Expr,
1523 node.As,
1524 )
1525 }
1526
1527 // Nextval defines the NEXT VALUE expression.
1528 type Nextval struct {
1529 Expr Expr
1530 }
1531
1532 // Format formats the node.
1533 func (node Nextval) Format(buf *TrackedBuffer) {
1534 buf.Myprintf("next %v values", node.Expr)
1535 }
1536
1537 func (node Nextval) walkSubtree(visit Visit) error {
1538 return Walk(visit, node.Expr)
1539 }
1540
1541 // Columns represents an insert column list.
1542 type Columns []ColIdent
1543
1544 // Format formats the node.
1545 func (node Columns) Format(buf *TrackedBuffer) {
1546 if node == nil {
1547 return
1548 }
1549 prefix := "("
1550 for _, n := range node {
1551 buf.Myprintf("%s%v", prefix, n)
1552 prefix = ", "
1553 }
1554 buf.WriteString(")")
1555 }
1556
1557 func (node Columns) walkSubtree(visit Visit) error {
1558 for _, n := range node {
1559 if err := Walk(visit, n); err != nil {
1560 return err
1561 }
1562 }
1563 return nil
1564 }
1565
1566 // FindColumn finds a column in the column list, returning
1567 // the index if it exists or -1 otherwise
1568 func (node Columns) FindColumn(col ColIdent) int {
1569 for i, colName := range node {
1570 if colName.Equal(col) {
1571 return i
1572 }
1573 }
1574 return -1
1575 }
1576
1577 // Partitions is a type alias for Columns so we can handle printing efficiently
1578 type Partitions Columns
1579
1580 // Format formats the node
1581 func (node Partitions) Format(buf *TrackedBuffer) {
1582 if node == nil {
1583 return
1584 }
1585 prefix := " partition ("
1586 for _, n := range node {
1587 buf.Myprintf("%s%v", prefix, n)
1588 prefix = ", "
1589 }
1590 buf.WriteString(")")
1591 }
1592
1593 func (node Partitions) walkSubtree(visit Visit) error {
1594 for _, n := range node {
1595 if err := Walk(visit, n); err != nil {
1596 return err
1597 }
1598 }
1599 return nil
1600 }
1601
1602 // TableExprs represents a list of table expressions.
1603 type TableExprs []TableExpr
1604
1605 // Format formats the node.
1606 func (node TableExprs) Format(buf *TrackedBuffer) {
1607 var prefix string
1608 for _, n := range node {
1609 buf.Myprintf("%s%v", prefix, n)
1610 prefix = ", "
1611 }
1612 }
1613
1614 func (node TableExprs) walkSubtree(visit Visit) error {
1615 for _, n := range node {
1616 if err := Walk(visit, n); err != nil {
1617 return err
1618 }
1619 }
1620 return nil
1621 }
1622
1623 // TableExpr represents a table expression.
1624 type TableExpr interface {
1625 iTableExpr()
1626 SQLNode
1627 }
1628
1629 func (*AliasedTableExpr) iTableExpr() {}
1630 func (*ParenTableExpr) iTableExpr() {}
1631 func (*JoinTableExpr) iTableExpr() {}
1632
1633 // AliasedTableExpr represents a table expression
1634 // coupled with an optional alias or index hint.
1635 // If As is empty, no alias was used.
1636 type AliasedTableExpr struct {
1637 Expr SimpleTableExpr
1638 Partitions Partitions
1639 As TableIdent
1640 Hints *IndexHints
1641 }
1642
1643 // Format formats the node.
1644 func (node *AliasedTableExpr) Format(buf *TrackedBuffer) {
1645 buf.Myprintf("%v%v", node.Expr, node.Partitions)
1646 if !node.As.IsEmpty() {
1647 buf.Myprintf(" as %v", node.As)
1648 }
1649 if node.Hints != nil {
1650 // Hint node provides the space padding.
1651 buf.Myprintf("%v", node.Hints)
1652 }
1653 }
1654
1655 func (node *AliasedTableExpr) walkSubtree(visit Visit) error {
1656 if node == nil {
1657 return nil
1658 }
1659 return Walk(
1660 visit,
1661 node.Expr,
1662 node.As,
1663 node.Hints,
1664 )
1665 }
1666
1667 // RemoveHints returns a new AliasedTableExpr with the hints removed.
1668 func (node *AliasedTableExpr) RemoveHints() *AliasedTableExpr {
1669 noHints := *node
1670 noHints.Hints = nil
1671 return &noHints
1672 }
1673
1674 // SimpleTableExpr represents a simple table expression.
1675 type SimpleTableExpr interface {
1676 iSimpleTableExpr()
1677 SQLNode
1678 }
1679
1680 func (TableName) iSimpleTableExpr() {}
1681 func (*Subquery) iSimpleTableExpr() {}
1682
1683 // TableNames is a list of TableName.
1684 type TableNames []TableName
1685
1686 // Format formats the node.
1687 func (node TableNames) Format(buf *TrackedBuffer) {
1688 var prefix string
1689 for _, n := range node {
1690 buf.Myprintf("%s%v", prefix, n)
1691 prefix = ", "
1692 }
1693 }
1694
1695 func (node TableNames) walkSubtree(visit Visit) error {
1696 for _, n := range node {
1697 if err := Walk(visit, n); err != nil {
1698 return err
1699 }
1700 }
1701 return nil
1702 }
1703
1704 // TableName represents a table name.
1705 // Qualifier, if specified, represents a database or keyspace.
1706 // TableName is a value struct whose fields are case sensitive.
1707 // This means two TableName vars can be compared for equality
1708 // and a TableName can also be used as key in a map.
1709 type TableName struct {
1710 Name, Qualifier TableIdent
1711 }
1712
1713 // Format formats the node.
1714 func (node TableName) Format(buf *TrackedBuffer) {
1715 if node.IsEmpty() {
1716 return
1717 }
1718 if !node.Qualifier.IsEmpty() {
1719 buf.Myprintf("%v.", node.Qualifier)
1720 }
1721 buf.Myprintf("%v", node.Name)
1722 }
1723
1724 func (node TableName) walkSubtree(visit Visit) error {
1725 return Walk(
1726 visit,
1727 node.Name,
1728 node.Qualifier,
1729 )
1730 }
1731
1732 // IsEmpty returns true if TableName is nil or empty.
1733 func (node TableName) IsEmpty() bool {
1734 // If Name is empty, Qualifer is also empty.
1735 return node.Name.IsEmpty()
1736 }
1737
1738 // ToViewName returns a TableName acceptable for use as a VIEW. VIEW names are
1739 // always lowercase, so ToViewName lowercasese the name. Databases are case-sensitive
1740 // so Qualifier is left untouched.
1741 func (node TableName) ToViewName() TableName {
1742 return TableName{
1743 Qualifier: node.Qualifier,
1744 Name: NewTableIdent(strings.ToLower(node.Name.v)),
1745 }
1746 }
1747
1748 // ParenTableExpr represents a parenthesized list of TableExpr.
1749 type ParenTableExpr struct {
1750 Exprs TableExprs
1751 }
1752
1753 // Format formats the node.
1754 func (node *ParenTableExpr) Format(buf *TrackedBuffer) {
1755 buf.Myprintf("(%v)", node.Exprs)
1756 }
1757
1758 func (node *ParenTableExpr) walkSubtree(visit Visit) error {
1759 if node == nil {
1760 return nil
1761 }
1762 return Walk(
1763 visit,
1764 node.Exprs,
1765 )
1766 }
1767
1768 // JoinCondition represents the join conditions (either a ON or USING clause)
1769 // of a JoinTableExpr.
1770 type JoinCondition struct {
1771 On Expr
1772 Using Columns
1773 }
1774
1775 // Format formats the node.
1776 func (node JoinCondition) Format(buf *TrackedBuffer) {
1777 if node.On != nil {
1778 buf.Myprintf(" on %v", node.On)
1779 }
1780 if node.Using != nil {
1781 buf.Myprintf(" using %v", node.Using)
1782 }
1783 }
1784
1785 func (node JoinCondition) walkSubtree(visit Visit) error {
1786 return Walk(
1787 visit,
1788 node.On,
1789 node.Using,
1790 )
1791 }
1792
1793 // JoinTableExpr represents a TableExpr that's a JOIN operation.
1794 type JoinTableExpr struct {
1795 LeftExpr TableExpr
1796 Join string
1797 RightExpr TableExpr
1798 Condition JoinCondition
1799 }
1800
1801 // JoinTableExpr.Join
1802 const (
1803 JoinStr = "join"
1804 StraightJoinStr = "straight_join"
1805 LeftJoinStr = "left join"
1806 RightJoinStr = "right join"
1807 NaturalJoinStr = "natural join"
1808 NaturalLeftJoinStr = "natural left join"
1809 NaturalRightJoinStr = "natural right join"
1810 )
1811
1812 // Format formats the node.
1813 func (node *JoinTableExpr) Format(buf *TrackedBuffer) {
1814 buf.Myprintf("%v %s %v%v", node.LeftExpr, node.Join, node.RightExpr, node.Condition)
1815 }
1816
1817 func (node *JoinTableExpr) walkSubtree(visit Visit) error {
1818 if node == nil {
1819 return nil
1820 }
1821 return Walk(
1822 visit,
1823 node.LeftExpr,
1824 node.RightExpr,
1825 node.Condition,
1826 )
1827 }
1828
1829 // IndexHints represents a list of index hints.
1830 type IndexHints struct {
1831 Type string
1832 Indexes []ColIdent
1833 }
1834
1835 // Index hints.
1836 const (
1837 UseStr = "use "
1838 IgnoreStr = "ignore "
1839 ForceStr = "force "
1840 )
1841
1842 // Format formats the node.
1843 func (node *IndexHints) Format(buf *TrackedBuffer) {
1844 buf.Myprintf(" %sindex ", node.Type)
1845 prefix := "("
1846 for _, n := range node.Indexes {
1847 buf.Myprintf("%s%v", prefix, n)
1848 prefix = ", "
1849 }
1850 buf.Myprintf(")")
1851 }
1852
1853 func (node *IndexHints) walkSubtree(visit Visit) error {
1854 if node == nil {
1855 return nil
1856 }
1857 for _, n := range node.Indexes {
1858 if err := Walk(visit, n); err != nil {
1859 return err
1860 }
1861 }
1862 return nil
1863 }
1864
1865 // Where represents a WHERE or HAVING clause.
1866 type Where struct {
1867 Type string
1868 Expr Expr
1869 }
1870
1871 // Where.Type
1872 const (
1873 WhereStr = "where"
1874 HavingStr = "having"
1875 )
1876
1877 // NewWhere creates a WHERE or HAVING clause out
1878 // of a Expr. If the expression is nil, it returns nil.
1879 func NewWhere(typ string, expr Expr) *Where {
1880 if expr == nil {
1881 return nil
1882 }
1883 return &Where{Type: typ, Expr: expr}
1884 }
1885
1886 // Format formats the node.
1887 func (node *Where) Format(buf *TrackedBuffer) {
1888 if node == nil || node.Expr == nil {
1889 return
1890 }
1891 buf.Myprintf(" %s %v", node.Type, node.Expr)
1892 }
1893
1894 func (node *Where) walkSubtree(visit Visit) error {
1895 if node == nil {
1896 return nil
1897 }
1898 return Walk(
1899 visit,
1900 node.Expr,
1901 )
1902 }
1903
1904 // Expr represents an expression.
1905 type Expr interface {
1906 iExpr()
1907 // replace replaces any subexpression that matches
1908 // from with to. The implementation can use the
1909 // replaceExprs convenience function.
1910 replace(from, to Expr) bool
1911 SQLNode
1912 }
1913
1914 func (*AndExpr) iExpr() {}
1915 func (*OrExpr) iExpr() {}
1916 func (*NotExpr) iExpr() {}
1917 func (*ParenExpr) iExpr() {}
1918 func (*ComparisonExpr) iExpr() {}
1919 func (*RangeCond) iExpr() {}
1920 func (*IsExpr) iExpr() {}
1921 func (*ExistsExpr) iExpr() {}
1922 func (*SQLVal) iExpr() {}
1923 func (*NullVal) iExpr() {}
1924 func (BoolVal) iExpr() {}
1925 func (*ColName) iExpr() {}
1926 func (ValTuple) iExpr() {}
1927 func (*Subquery) iExpr() {}
1928 func (ListArg) iExpr() {}
1929 func (*BinaryExpr) iExpr() {}
1930 func (*UnaryExpr) iExpr() {}
1931 func (*IntervalExpr) iExpr() {}
1932 func (*CollateExpr) iExpr() {}
1933 func (*FuncExpr) iExpr() {}
1934 func (*CaseExpr) iExpr() {}
1935 func (*ValuesFuncExpr) iExpr() {}
1936 func (*ConvertExpr) iExpr() {}
1937 func (*SubstrExpr) iExpr() {}
1938 func (*ConvertUsingExpr) iExpr() {}
1939 func (*MatchExpr) iExpr() {}
1940 func (*GroupConcatExpr) iExpr() {}
1941 func (*Default) iExpr() {}
1942
1943 // ReplaceExpr finds the from expression from root
1944 // and replaces it with to. If from matches root,
1945 // then to is returned.
1946 func ReplaceExpr(root, from, to Expr) Expr {
1947 if root == from {
1948 return to
1949 }
1950 root.replace(from, to)
1951 return root
1952 }
1953
1954 // replaceExprs is a convenience function used by implementors
1955 // of the replace method.
1956 func replaceExprs(from, to Expr, exprs ...*Expr) bool {
1957 for _, expr := range exprs {
1958 if *expr == nil {
1959 continue
1960 }
1961 if *expr == from {
1962 *expr = to
1963 return true
1964 }
1965 if (*expr).replace(from, to) {
1966 return true
1967 }
1968 }
1969 return false
1970 }
1971
1972 // Exprs represents a list of value expressions.
1973 // It's not a valid expression because it's not parenthesized.
1974 type Exprs []Expr
1975
1976 // Format formats the node.
1977 func (node Exprs) Format(buf *TrackedBuffer) {
1978 var prefix string
1979 for _, n := range node {
1980 buf.Myprintf("%s%v", prefix, n)
1981 prefix = ", "
1982 }
1983 }
1984
1985 func (node Exprs) walkSubtree(visit Visit) error {
1986 for _, n := range node {
1987 if err := Walk(visit, n); err != nil {
1988 return err
1989 }
1990 }
1991 return nil
1992 }
1993
1994 // AndExpr represents an AND expression.
1995 type AndExpr struct {
1996 Left, Right Expr
1997 }
1998
1999 // Format formats the node.
2000 func (node *AndExpr) Format(buf *TrackedBuffer) {
2001 buf.Myprintf("%v and %v", node.Left, node.Right)
2002 }
2003
2004 func (node *AndExpr) walkSubtree(visit Visit) error {
2005 if node == nil {
2006 return nil
2007 }
2008 return Walk(
2009 visit,
2010 node.Left,
2011 node.Right,
2012 )
2013 }
2014
2015 func (node *AndExpr) replace(from, to Expr) bool {
2016 return replaceExprs(from, to, &node.Left, &node.Right)
2017 }
2018
2019 // OrExpr represents an OR expression.
2020 type OrExpr struct {
2021 Left, Right Expr
2022 }
2023
2024 // Format formats the node.
2025 func (node *OrExpr) Format(buf *TrackedBuffer) {
2026 buf.Myprintf("%v or %v", node.Left, node.Right)
2027 }
2028
2029 func (node *OrExpr) walkSubtree(visit Visit) error {
2030 if node == nil {
2031 return nil
2032 }
2033 return Walk(
2034 visit,
2035 node.Left,
2036 node.Right,
2037 )
2038 }
2039
2040 func (node *OrExpr) replace(from, to Expr) bool {
2041 return replaceExprs(from, to, &node.Left, &node.Right)
2042 }
2043
2044 // NotExpr represents a NOT expression.
2045 type NotExpr struct {
2046 Expr Expr
2047 }
2048
2049 // Format formats the node.
2050 func (node *NotExpr) Format(buf *TrackedBuffer) {
2051 buf.Myprintf("not %v", node.Expr)
2052 }
2053
2054 func (node *NotExpr) walkSubtree(visit Visit) error {
2055 if node == nil {
2056 return nil
2057 }
2058 return Walk(
2059 visit,
2060 node.Expr,
2061 )
2062 }
2063
2064 func (node *NotExpr) replace(from, to Expr) bool {
2065 return replaceExprs(from, to, &node.Expr)
2066 }
2067
2068 // ParenExpr represents a parenthesized boolean expression.
2069 type ParenExpr struct {
2070 Expr Expr
2071 }
2072
2073 // Format formats the node.
2074 func (node *ParenExpr) Format(buf *TrackedBuffer) {
2075 buf.Myprintf("(%v)", node.Expr)
2076 }
2077
2078 func (node *ParenExpr) walkSubtree(visit Visit) error {
2079 if node == nil {
2080 return nil
2081 }
2082 return Walk(
2083 visit,
2084 node.Expr,
2085 )
2086 }
2087
2088 func (node *ParenExpr) replace(from, to Expr) bool {
2089 return replaceExprs(from, to, &node.Expr)
2090 }
2091
2092 // ComparisonExpr represents a two-value comparison expression.
2093 type ComparisonExpr struct {
2094 Operator string
2095 Left, Right Expr
2096 Escape Expr
2097 }
2098
2099 // ComparisonExpr.Operator
2100 const (
2101 EqualStr = "="
2102 LessThanStr = "<"
2103 GreaterThanStr = ">"
2104 LessEqualStr = "<="
2105 GreaterEqualStr = ">="
2106 NotEqualStr = "!="
2107 NullSafeEqualStr = "<=>"
2108 InStr = "in"
2109 NotInStr = "not in"
2110 LikeStr = "like"
2111 NotLikeStr = "not like"
2112 RegexpStr = "regexp"
2113 NotRegexpStr = "not regexp"
2114 JSONExtractOp = "->"
2115 JSONUnquoteExtractOp = "->>"
2116 )
2117
2118 // Format formats the node.
2119 func (node *ComparisonExpr) Format(buf *TrackedBuffer) {
2120 buf.Myprintf("%v %s %v", node.Left, node.Operator, node.Right)
2121 if node.Escape != nil {
2122 buf.Myprintf(" escape %v", node.Escape)
2123 }
2124 }
2125
2126 func (node *ComparisonExpr) walkSubtree(visit Visit) error {
2127 if node == nil {
2128 return nil
2129 }
2130 return Walk(
2131 visit,
2132 node.Left,
2133 node.Right,
2134 node.Escape,
2135 )
2136 }
2137
2138 func (node *ComparisonExpr) replace(from, to Expr) bool {
2139 return replaceExprs(from, to, &node.Left, &node.Right, &node.Escape)
2140 }
2141
2142 // RangeCond represents a BETWEEN or a NOT BETWEEN expression.
2143 type RangeCond struct {
2144 Operator string
2145 Left Expr
2146 From, To Expr
2147 }
2148
2149 // RangeCond.Operator
2150 const (
2151 BetweenStr = "between"
2152 NotBetweenStr = "not between"
2153 )
2154
2155 // Format formats the node.
2156 func (node *RangeCond) Format(buf *TrackedBuffer) {
2157 buf.Myprintf("%v %s %v and %v", node.Left, node.Operator, node.From, node.To)
2158 }
2159
2160 func (node *RangeCond) walkSubtree(visit Visit) error {
2161 if node == nil {
2162 return nil
2163 }
2164 return Walk(
2165 visit,
2166 node.Left,
2167 node.From,
2168 node.To,
2169 )
2170 }
2171
2172 func (node *RangeCond) replace(from, to Expr) bool {
2173 return replaceExprs(from, to, &node.Left, &node.From, &node.To)
2174 }
2175
2176 // IsExpr represents an IS ... or an IS NOT ... expression.
2177 type IsExpr struct {
2178 Operator string
2179 Expr Expr
2180 }
2181
2182 // IsExpr.Operator
2183 const (
2184 IsNullStr = "is null"
2185 IsNotNullStr = "is not null"
2186 IsTrueStr = "is true"
2187 IsNotTrueStr = "is not true"
2188 IsFalseStr = "is false"
2189 IsNotFalseStr = "is not false"
2190 )
2191
2192 // Format formats the node.
2193 func (node *IsExpr) Format(buf *TrackedBuffer) {
2194 buf.Myprintf("%v %s", node.Expr, node.Operator)
2195 }
2196
2197 func (node *IsExpr) walkSubtree(visit Visit) error {
2198 if node == nil {
2199 return nil
2200 }
2201 return Walk(
2202 visit,
2203 node.Expr,
2204 )
2205 }
2206
2207 func (node *IsExpr) replace(from, to Expr) bool {
2208 return replaceExprs(from, to, &node.Expr)
2209 }
2210
2211 // ExistsExpr represents an EXISTS expression.
2212 type ExistsExpr struct {
2213 Subquery *Subquery
2214 }
2215
2216 // Format formats the node.
2217 func (node *ExistsExpr) Format(buf *TrackedBuffer) {
2218 buf.Myprintf("exists %v", node.Subquery)
2219 }
2220
2221 func (node *ExistsExpr) walkSubtree(visit Visit) error {
2222 if node == nil {
2223 return nil
2224 }
2225 return Walk(
2226 visit,
2227 node.Subquery,
2228 )
2229 }
2230
2231 func (node *ExistsExpr) replace(from, to Expr) bool {
2232 return false
2233 }
2234
2235 // ExprFromValue converts the given Value into an Expr or returns an error.
2236 func ExprFromValue(value sqltypes.Value) (Expr, error) {
2237 // The type checks here follow the rules defined in sqltypes/types.go.
2238 switch {
2239 case value.Type() == sqltypes.Null:
2240 return &NullVal{}, nil
2241 case value.IsIntegral():
2242 return NewIntVal(value.ToBytes()), nil
2243 case value.IsFloat() || value.Type() == sqltypes.Decimal:
2244 return NewFloatVal(value.ToBytes()), nil
2245 case value.IsQuoted():
2246 return NewStrVal(value.ToBytes()), nil
2247 default:
2248 // We cannot support sqltypes.Expression, or any other invalid type.
2249 return nil, fmt.Errorf("cannot convert value %v to AST", value)
2250 }
2251 }
2252
2253 // ValType specifies the type for SQLVal.
2254 type ValType int
2255
2256 // These are the possible Valtype values.
2257 // HexNum represents a 0x... value. It cannot
2258 // be treated as a simple value because it can
2259 // be interpreted differently depending on the
2260 // context.
2261 const (
2262 StrVal = ValType(iota)
2263 IntVal
2264 FloatVal
2265 HexNum
2266 HexVal
2267 ValArg
2268 BitVal
2269 )
2270
2271 // SQLVal represents a single value.
2272 type SQLVal struct {
2273 Type ValType
2274 Val []byte
2275 }
2276
2277 // NewStrVal builds a new StrVal.
2278 func NewStrVal(in []byte) *SQLVal {
2279 return &SQLVal{Type: StrVal, Val: in}
2280 }
2281
2282 // NewIntVal builds a new IntVal.
2283 func NewIntVal(in []byte) *SQLVal {
2284 return &SQLVal{Type: IntVal, Val: in}
2285 }
2286
2287 // NewFloatVal builds a new FloatVal.
2288 func NewFloatVal(in []byte) *SQLVal {
2289 return &SQLVal{Type: FloatVal, Val: in}
2290 }
2291
2292 // NewHexNum builds a new HexNum.
2293 func NewHexNum(in []byte) *SQLVal {
2294 return &SQLVal{Type: HexNum, Val: in}
2295 }
2296
2297 // NewHexVal builds a new HexVal.
2298 func NewHexVal(in []byte) *SQLVal {
2299 return &SQLVal{Type: HexVal, Val: in}
2300 }
2301
2302 // NewBitVal builds a new BitVal containing a bit literal.
2303 func NewBitVal(in []byte) *SQLVal {
2304 return &SQLVal{Type: BitVal, Val: in}
2305 }
2306
2307 // NewValArg builds a new ValArg.
2308 func NewValArg(in []byte) *SQLVal {
2309 return &SQLVal{Type: ValArg, Val: in}
2310 }
2311
2312 // Format formats the node.
2313 func (node *SQLVal) Format(buf *TrackedBuffer) {
2314 switch node.Type {
2315 case StrVal:
2316 sqltypes.MakeTrusted(sqltypes.VarBinary, node.Val).EncodeSQL(buf)
2317 case IntVal, FloatVal, HexNum:
2318 buf.Myprintf("%s", []byte(node.Val))
2319 case HexVal:
2320 buf.Myprintf("X'%s'", []byte(node.Val))
2321 case BitVal:
2322 buf.Myprintf("B'%s'", []byte(node.Val))
2323 case ValArg:
2324 buf.WriteArg(string(node.Val))
2325 default:
2326 panic("unexpected")
2327 }
2328 }
2329
2330 func (node *SQLVal) walkSubtree(visit Visit) error {
2331 return nil
2332 }
2333
2334 func (node *SQLVal) replace(from, to Expr) bool {
2335 return false
2336 }
2337
2338 // HexDecode decodes the hexval into bytes.
2339 func (node *SQLVal) HexDecode() ([]byte, error) {
2340 dst := make([]byte, hex.DecodedLen(len([]byte(node.Val))))
2341 _, err := hex.Decode(dst, []byte(node.Val))
2342 if err != nil {
2343 return nil, err
2344 }
2345 return dst, err
2346 }
2347
2348 // NullVal represents a NULL value.
2349 type NullVal struct{}
2350
2351 // Format formats the node.
2352 func (node *NullVal) Format(buf *TrackedBuffer) {
2353 buf.Myprintf("null")
2354 }
2355
2356 func (node *NullVal) walkSubtree(visit Visit) error {
2357 return nil
2358 }
2359
2360 func (node *NullVal) replace(from, to Expr) bool {
2361 return false
2362 }
2363
2364 // BoolVal is true or false.
2365 type BoolVal bool
2366
2367 // Format formats the node.
2368 func (node BoolVal) Format(buf *TrackedBuffer) {
2369 if node {
2370 buf.Myprintf("true")
2371 } else {
2372 buf.Myprintf("false")
2373 }
2374 }
2375
2376 func (node BoolVal) walkSubtree(visit Visit) error {
2377 return nil
2378 }
2379
2380 func (node BoolVal) replace(from, to Expr) bool {
2381 return false
2382 }
2383
2384 // ColName represents a column name.
2385 type ColName struct {
2386 // Metadata is not populated by the parser.
2387 // It's a placeholder for analyzers to store
2388 // additional data, typically info about which
2389 // table or column this node references.
2390 Metadata interface{}
2391 Name ColIdent
2392 Qualifier TableName
2393 }
2394
2395 // Format formats the node.
2396 func (node *ColName) Format(buf *TrackedBuffer) {
2397 if !node.Qualifier.IsEmpty() {
2398 buf.Myprintf("%v.", node.Qualifier)
2399 }
2400 buf.Myprintf("%v", node.Name)
2401 }
2402
2403 func (node *ColName) walkSubtree(visit Visit) error {
2404 if node == nil {
2405 return nil
2406 }
2407 return Walk(
2408 visit,
2409 node.Name,
2410 node.Qualifier,
2411 )
2412 }
2413
2414 func (node *ColName) replace(from, to Expr) bool {
2415 return false
2416 }
2417
2418 // Equal returns true if the column names match.
2419 func (node *ColName) Equal(c *ColName) bool {
2420 // Failsafe: ColName should not be empty.
2421 if node == nil || c == nil {
2422 return false
2423 }
2424 return node.Name.Equal(c.Name) && node.Qualifier == c.Qualifier
2425 }
2426
2427 // ColTuple represents a list of column values.
2428 // It can be ValTuple, Subquery, ListArg.
2429 type ColTuple interface {
2430 iColTuple()
2431 Expr
2432 }
2433
2434 func (ValTuple) iColTuple() {}
2435 func (*Subquery) iColTuple() {}
2436 func (ListArg) iColTuple() {}
2437
2438 // ValTuple represents a tuple of actual values.
2439 type ValTuple Exprs
2440
2441 // Format formats the node.
2442 func (node ValTuple) Format(buf *TrackedBuffer) {
2443 buf.Myprintf("(%v)", Exprs(node))
2444 }
2445
2446 func (node ValTuple) walkSubtree(visit Visit) error {
2447 return Walk(visit, Exprs(node))
2448 }
2449
2450 func (node ValTuple) replace(from, to Expr) bool {
2451 for i := range node {
2452 if replaceExprs(from, to, &node[i]) {
2453 return true
2454 }
2455 }
2456 return false
2457 }
2458
2459 // Subquery represents a subquery.
2460 type Subquery struct {
2461 Select SelectStatement
2462 }
2463
2464 // Format formats the node.
2465 func (node *Subquery) Format(buf *TrackedBuffer) {
2466 buf.Myprintf("(%v)", node.Select)
2467 }
2468
2469 func (node *Subquery) walkSubtree(visit Visit) error {
2470 if node == nil {
2471 return nil
2472 }
2473 return Walk(
2474 visit,
2475 node.Select,
2476 )
2477 }
2478
2479 func (node *Subquery) replace(from, to Expr) bool {
2480 return false
2481 }
2482
2483 // ListArg represents a named list argument.
2484 type ListArg []byte
2485
2486 // Format formats the node.
2487 func (node ListArg) Format(buf *TrackedBuffer) {
2488 buf.WriteArg(string(node))
2489 }
2490
2491 func (node ListArg) walkSubtree(visit Visit) error {
2492 return nil
2493 }
2494
2495 func (node ListArg) replace(from, to Expr) bool {
2496 return false
2497 }
2498
2499 // BinaryExpr represents a binary value expression.
2500 type BinaryExpr struct {
2501 Operator string
2502 Left, Right Expr
2503 }
2504
2505 // BinaryExpr.Operator
2506 const (
2507 BitAndStr = "&"
2508 BitOrStr = "|"
2509 BitXorStr = "^"
2510 PlusStr = "+"
2511 MinusStr = "-"
2512 MultStr = "*"
2513 DivStr = "/"
2514 IntDivStr = "div"
2515 ModStr = "%"
2516 ShiftLeftStr = "<<"
2517 ShiftRightStr = ">>"
2518 )
2519
2520 // Format formats the node.
2521 func (node *BinaryExpr) Format(buf *TrackedBuffer) {
2522 buf.Myprintf("%v %s %v", node.Left, node.Operator, node.Right)
2523 }
2524
2525 func (node *BinaryExpr) walkSubtree(visit Visit) error {
2526 if node == nil {
2527 return nil
2528 }
2529 return Walk(
2530 visit,
2531 node.Left,
2532 node.Right,
2533 )
2534 }
2535
2536 func (node *BinaryExpr) replace(from, to Expr) bool {
2537 return replaceExprs(from, to, &node.Left, &node.Right)
2538 }
2539
2540 // UnaryExpr represents a unary value expression.
2541 type UnaryExpr struct {
2542 Operator string
2543 Expr Expr
2544 }
2545
2546 // UnaryExpr.Operator
2547 const (
2548 UPlusStr = "+"
2549 UMinusStr = "-"
2550 TildaStr = "~"
2551 BangStr = "!"
2552 BinaryStr = "binary "
2553 UBinaryStr = "_binary "
2554 )
2555
2556 // Format formats the node.
2557 func (node *UnaryExpr) Format(buf *TrackedBuffer) {
2558 if _, unary := node.Expr.(*UnaryExpr); unary {
2559 buf.Myprintf("%s %v", node.Operator, node.Expr)
2560 return
2561 }
2562 buf.Myprintf("%s%v", node.Operator, node.Expr)
2563 }
2564
2565 func (node *UnaryExpr) walkSubtree(visit Visit) error {
2566 if node == nil {
2567 return nil
2568 }
2569 return Walk(
2570 visit,
2571 node.Expr,
2572 )
2573 }
2574
2575 func (node *UnaryExpr) replace(from, to Expr) bool {
2576 return replaceExprs(from, to, &node.Expr)
2577 }
2578
2579 // IntervalExpr represents a date-time INTERVAL expression.
2580 type IntervalExpr struct {
2581 Expr Expr
2582 Unit string
2583 }
2584
2585 // Format formats the node.
2586 func (node *IntervalExpr) Format(buf *TrackedBuffer) {
2587 buf.Myprintf("interval %v %s", node.Expr, node.Unit)
2588 }
2589
2590 func (node *IntervalExpr) walkSubtree(visit Visit) error {
2591 if node == nil {
2592 return nil
2593 }
2594 return Walk(
2595 visit,
2596 node.Expr,
2597 )
2598 }
2599
2600 func (node *IntervalExpr) replace(from, to Expr) bool {
2601 return replaceExprs(from, to, &node.Expr)
2602 }
2603
2604 // CollateExpr represents dynamic collate operator.
2605 type CollateExpr struct {
2606 Expr Expr
2607 Charset string
2608 }
2609
2610 // Format formats the node.
2611 func (node *CollateExpr) Format(buf *TrackedBuffer) {
2612 buf.Myprintf("%v collate %s", node.Expr, node.Charset)
2613 }
2614
2615 func (node *CollateExpr) walkSubtree(visit Visit) error {
2616 if node == nil {
2617 return nil
2618 }
2619 return Walk(
2620 visit,
2621 node.Expr,
2622 )
2623 }
2624
2625 func (node *CollateExpr) replace(from, to Expr) bool {
2626 return replaceExprs(from, to, &node.Expr)
2627 }
2628
2629 // FuncExpr represents a function call.
2630 type FuncExpr struct {
2631 Qualifier TableIdent
2632 Name ColIdent
2633 Distinct bool
2634 Exprs SelectExprs
2635 }
2636
2637 // Format formats the node.
2638 func (node *FuncExpr) Format(buf *TrackedBuffer) {
2639 var distinct string
2640 if node.Distinct {
2641 distinct = "distinct "
2642 }
2643 if !node.Qualifier.IsEmpty() {
2644 buf.Myprintf("%v.", node.Qualifier)
2645 }
2646 // Function names should not be back-quoted even
2647 // if they match a reserved word. So, print the
2648 // name as is.
2649 buf.Myprintf("%s(%s%v)", node.Name.String(), distinct, node.Exprs)
2650 }
2651
2652 func (node *FuncExpr) walkSubtree(visit Visit) error {
2653 if node == nil {
2654 return nil
2655 }
2656 return Walk(
2657 visit,
2658 node.Qualifier,
2659 node.Name,
2660 node.Exprs,
2661 )
2662 }
2663
2664 func (node *FuncExpr) replace(from, to Expr) bool {
2665 for _, sel := range node.Exprs {
2666 aliased, ok := sel.(*AliasedExpr)
2667 if !ok {
2668 continue
2669 }
2670 if replaceExprs(from, to, &aliased.Expr) {
2671 return true
2672 }
2673 }
2674 return false
2675 }
2676
2677 // Aggregates is a map of all aggregate functions.
2678 var Aggregates = map[string]bool{
2679 "avg": true,
2680 "bit_and": true,
2681 "bit_or": true,
2682 "bit_xor": true,
2683 "count": true,
2684 "group_concat": true,
2685 "max": true,
2686 "min": true,
2687 "std": true,
2688 "stddev_pop": true,
2689 "stddev_samp": true,
2690 "stddev": true,
2691 "sum": true,
2692 "var_pop": true,
2693 "var_samp": true,
2694 "variance": true,
2695 }
2696
2697 // IsAggregate returns true if the function is an aggregate.
2698 func (node *FuncExpr) IsAggregate() bool {
2699 return Aggregates[node.Name.Lowered()]
2700 }
2701
2702 // GroupConcatExpr represents a call to GROUP_CONCAT
2703 type GroupConcatExpr struct {
2704 Distinct string
2705 Exprs SelectExprs
2706 OrderBy OrderBy
2707 Separator string
2708 }
2709
2710 // Format formats the node
2711 func (node *GroupConcatExpr) Format(buf *TrackedBuffer) {
2712 buf.Myprintf("group_concat(%s%v%v%s)", node.Distinct, node.Exprs, node.OrderBy, node.Separator)
2713 }
2714
2715 func (node *GroupConcatExpr) walkSubtree(visit Visit) error {
2716 if node == nil {
2717 return nil
2718 }
2719 return Walk(
2720 visit,
2721 node.Exprs,
2722 node.OrderBy,
2723 )
2724 }
2725
2726 func (node *GroupConcatExpr) replace(from, to Expr) bool {
2727 for _, sel := range node.Exprs {
2728 aliased, ok := sel.(*AliasedExpr)
2729 if !ok {
2730 continue
2731 }
2732 if replaceExprs(from, to, &aliased.Expr) {
2733 return true
2734 }
2735 }
2736 for _, order := range node.OrderBy {
2737 if replaceExprs(from, to, &order.Expr) {
2738 return true
2739 }
2740 }
2741 return false
2742 }
2743
2744 // ValuesFuncExpr represents a function call.
2745 type ValuesFuncExpr struct {
2746 Name *ColName
2747 }
2748
2749 // Format formats the node.
2750 func (node *ValuesFuncExpr) Format(buf *TrackedBuffer) {
2751 buf.Myprintf("values(%v)", node.Name)
2752 }
2753
2754 func (node *ValuesFuncExpr) walkSubtree(visit Visit) error {
2755 if node == nil {
2756 return nil
2757 }
2758 return Walk(
2759 visit,
2760 node.Name,
2761 )
2762 }
2763
2764 func (node *ValuesFuncExpr) replace(from, to Expr) bool {
2765 return false
2766 }
2767
2768 // SubstrExpr represents a call to SubstrExpr(column, value_expression) or SubstrExpr(column, value_expression,value_expression)
2769 // also supported syntax SubstrExpr(column from value_expression for value_expression)
2770 type SubstrExpr struct {
2771 Name *ColName
2772 From Expr
2773 To Expr
2774 }
2775
2776 // Format formats the node.
2777 func (node *SubstrExpr) Format(buf *TrackedBuffer) {
2778
2779 if node.To == nil {
2780 buf.Myprintf("substr(%v, %v)", node.Name, node.From)
2781 } else {
2782 buf.Myprintf("substr(%v, %v, %v)", node.Name, node.From, node.To)
2783 }
2784 }
2785
2786 func (node *SubstrExpr) replace(from, to Expr) bool {
2787 return replaceExprs(from, to, &node.From, &node.To)
2788 }
2789
2790 func (node *SubstrExpr) walkSubtree(visit Visit) error {
2791 if node == nil {
2792 return nil
2793 }
2794 return Walk(
2795 visit,
2796 node.Name,
2797 node.From,
2798 node.To,
2799 )
2800 }
2801
2802 // ConvertExpr represents a call to CONVERT(expr, type)
2803 // or it's equivalent CAST(expr AS type). Both are rewritten to the former.
2804 type ConvertExpr struct {
2805 Expr Expr
2806 Type *ConvertType
2807 }
2808
2809 // Format formats the node.
2810 func (node *ConvertExpr) Format(buf *TrackedBuffer) {
2811 buf.Myprintf("convert(%v, %v)", node.Expr, node.Type)
2812 }
2813
2814 func (node *ConvertExpr) walkSubtree(visit Visit) error {
2815 if node == nil {
2816 return nil
2817 }
2818 return Walk(
2819 visit,
2820 node.Expr,
2821 node.Type,
2822 )
2823 }
2824
2825 func (node *ConvertExpr) replace(from, to Expr) bool {
2826 return replaceExprs(from, to, &node.Expr)
2827 }
2828
2829 // ConvertUsingExpr represents a call to CONVERT(expr USING charset).
2830 type ConvertUsingExpr struct {
2831 Expr Expr
2832 Type string
2833 }
2834
2835 // Format formats the node.
2836 func (node *ConvertUsingExpr) Format(buf *TrackedBuffer) {
2837 buf.Myprintf("convert(%v using %s)", node.Expr, node.Type)
2838 }
2839
2840 func (node *ConvertUsingExpr) walkSubtree(visit Visit) error {
2841 if node == nil {
2842 return nil
2843 }
2844 return Walk(
2845 visit,
2846 node.Expr,
2847 )
2848 }
2849
2850 func (node *ConvertUsingExpr) replace(from, to Expr) bool {
2851 return replaceExprs(from, to, &node.Expr)
2852 }
2853
2854 // ConvertType represents the type in call to CONVERT(expr, type)
2855 type ConvertType struct {
2856 Type string
2857 Length *SQLVal
2858 Scale *SQLVal
2859 Operator string
2860 Charset string
2861 }
2862
2863 // this string is "character set" and this comment is required
2864 const (
2865 CharacterSetStr = " character set"
2866 )
2867
2868 // Format formats the node.
2869 func (node *ConvertType) Format(buf *TrackedBuffer) {
2870 buf.Myprintf("%s", node.Type)
2871 if node.Length != nil {
2872 buf.Myprintf("(%v", node.Length)
2873 if node.Scale != nil {
2874 buf.Myprintf(", %v", node.Scale)
2875 }
2876 buf.Myprintf(")")
2877 }
2878 if node.Charset != "" {
2879 buf.Myprintf("%s %s", node.Operator, node.Charset)
2880 }
2881 }
2882
2883 func (node *ConvertType) walkSubtree(visit Visit) error {
2884 return nil
2885 }
2886
2887 // MatchExpr represents a call to the MATCH function
2888 type MatchExpr struct {
2889 Columns SelectExprs
2890 Expr Expr
2891 Option string
2892 }
2893
2894 // MatchExpr.Option
2895 const (
2896 BooleanModeStr = " in boolean mode"
2897 NaturalLanguageModeStr = " in natural language mode"
2898 NaturalLanguageModeWithQueryExpansionStr = " in natural language mode with query expansion"
2899 QueryExpansionStr = " with query expansion"
2900 )
2901
2902 // Format formats the node
2903 func (node *MatchExpr) Format(buf *TrackedBuffer) {
2904 buf.Myprintf("match(%v) against (%v%s)", node.Columns, node.Expr, node.Option)
2905 }
2906
2907 func (node *MatchExpr) walkSubtree(visit Visit) error {
2908 if node == nil {
2909 return nil
2910 }
2911 return Walk(
2912 visit,
2913 node.Columns,
2914 node.Expr,
2915 )
2916 }
2917
2918 func (node *MatchExpr) replace(from, to Expr) bool {
2919 for _, sel := range node.Columns {
2920 aliased, ok := sel.(*AliasedExpr)
2921 if !ok {
2922 continue
2923 }
2924 if replaceExprs(from, to, &aliased.Expr) {
2925 return true
2926 }
2927 }
2928 return replaceExprs(from, to, &node.Expr)
2929 }
2930
2931 // CaseExpr represents a CASE expression.
2932 type CaseExpr struct {
2933 Expr Expr
2934 Whens []*When
2935 Else Expr
2936 }
2937
2938 // Format formats the node.
2939 func (node *CaseExpr) Format(buf *TrackedBuffer) {
2940 buf.Myprintf("case ")
2941 if node.Expr != nil {
2942 buf.Myprintf("%v ", node.Expr)
2943 }
2944 for _, when := range node.Whens {
2945 buf.Myprintf("%v ", when)
2946 }
2947 if node.Else != nil {
2948 buf.Myprintf("else %v ", node.Else)
2949 }
2950 buf.Myprintf("end")
2951 }
2952
2953 func (node *CaseExpr) walkSubtree(visit Visit) error {
2954 if node == nil {
2955 return nil
2956 }
2957 if err := Walk(visit, node.Expr); err != nil {
2958 return err
2959 }
2960 for _, n := range node.Whens {
2961 if err := Walk(visit, n); err != nil {
2962 return err
2963 }
2964 }
2965 return Walk(visit, node.Else)
2966 }
2967
2968 func (node *CaseExpr) replace(from, to Expr) bool {
2969 for _, when := range node.Whens {
2970 if replaceExprs(from, to, &when.Cond, &when.Val) {
2971 return true
2972 }
2973 }
2974 return replaceExprs(from, to, &node.Expr, &node.Else)
2975 }
2976
2977 // Default represents a DEFAULT expression.
2978 type Default struct {
2979 ColName string
2980 }
2981
2982 // Format formats the node.
2983 func (node *Default) Format(buf *TrackedBuffer) {
2984 buf.Myprintf("default")
2985 if node.ColName != "" {
2986 buf.Myprintf("(%s)", node.ColName)
2987 }
2988 }
2989
2990 func (node *Default) walkSubtree(visit Visit) error {
2991 return nil
2992 }
2993
2994 func (node *Default) replace(from, to Expr) bool {
2995 return false
2996 }
2997
2998 // When represents a WHEN sub-expression.
2999 type When struct {
3000 Cond Expr
3001 Val Expr
3002 }
3003
3004 // Format formats the node.
3005 func (node *When) Format(buf *TrackedBuffer) {
3006 buf.Myprintf("when %v then %v", node.Cond, node.Val)
3007 }
3008
3009 func (node *When) walkSubtree(visit Visit) error {
3010 if node == nil {
3011 return nil
3012 }
3013 return Walk(
3014 visit,
3015 node.Cond,
3016 node.Val,
3017 )
3018 }
3019
3020 // GroupBy represents a GROUP BY clause.
3021 type GroupBy []Expr
3022
3023 // Format formats the node.
3024 func (node GroupBy) Format(buf *TrackedBuffer) {
3025 prefix := " group by "
3026 for _, n := range node {
3027 buf.Myprintf("%s%v", prefix, n)
3028 prefix = ", "
3029 }
3030 }
3031
3032 func (node GroupBy) walkSubtree(visit Visit) error {
3033 for _, n := range node {
3034 if err := Walk(visit, n); err != nil {
3035 return err
3036 }
3037 }
3038 return nil
3039 }
3040
3041 // OrderBy represents an ORDER By clause.
3042 type OrderBy []*Order
3043
3044 // Format formats the node.
3045 func (node OrderBy) Format(buf *TrackedBuffer) {
3046 prefix := " order by "
3047 for _, n := range node {
3048 buf.Myprintf("%s%v", prefix, n)
3049 prefix = ", "
3050 }
3051 }
3052
3053 func (node OrderBy) walkSubtree(visit Visit) error {
3054 for _, n := range node {
3055 if err := Walk(visit, n); err != nil {
3056 return err
3057 }
3058 }
3059 return nil
3060 }
3061
3062 // Order represents an ordering expression.
3063 type Order struct {
3064 Expr Expr
3065 Direction string
3066 }
3067
3068 // Order.Direction
3069 const (
3070 AscScr = "asc"
3071 DescScr = "desc"
3072 )
3073
3074 // Format formats the node.
3075 func (node *Order) Format(buf *TrackedBuffer) {
3076 if node, ok := node.Expr.(*NullVal); ok {
3077 buf.Myprintf("%v", node)
3078 return
3079 }
3080 if node, ok := node.Expr.(*FuncExpr); ok {
3081 if node.Name.Lowered() == "rand" {
3082 buf.Myprintf("%v", node)
3083 return
3084 }
3085 }
3086
3087 buf.Myprintf("%v %s", node.Expr, node.Direction)
3088 }
3089
3090 func (node *Order) walkSubtree(visit Visit) error {
3091 if node == nil {
3092 return nil
3093 }
3094 return Walk(
3095 visit,
3096 node.Expr,
3097 )
3098 }
3099
3100 // Limit represents a LIMIT clause.
3101 type Limit struct {
3102 Offset, Rowcount Expr
3103 }
3104
3105 // Format formats the node.
3106 func (node *Limit) Format(buf *TrackedBuffer) {
3107 if node == nil {
3108 return
3109 }
3110 buf.Myprintf(" limit ")
3111 if node.Offset != nil {
3112 buf.Myprintf("%v, ", node.Offset)
3113 }
3114 buf.Myprintf("%v", node.Rowcount)
3115 }
3116
3117 func (node *Limit) walkSubtree(visit Visit) error {
3118 if node == nil {
3119 return nil
3120 }
3121 return Walk(
3122 visit,
3123 node.Offset,
3124 node.Rowcount,
3125 )
3126 }
3127
3128 // Values represents a VALUES clause.
3129 type Values []ValTuple
3130
3131 // Format formats the node.
3132 func (node Values) Format(buf *TrackedBuffer) {
3133 prefix := "values "
3134 for _, n := range node {
3135 buf.Myprintf("%s%v", prefix, n)
3136 prefix = ", "
3137 }
3138 }
3139
3140 func (node Values) walkSubtree(visit Visit) error {
3141 for _, n := range node {
3142 if err := Walk(visit, n); err != nil {
3143 return err
3144 }
3145 }
3146 return nil
3147 }
3148
3149 // UpdateExprs represents a list of update expressions.
3150 type UpdateExprs []*UpdateExpr
3151
3152 // Format formats the node.
3153 func (node UpdateExprs) Format(buf *TrackedBuffer) {
3154 var prefix string
3155 for _, n := range node {
3156 buf.Myprintf("%s%v", prefix, n)
3157 prefix = ", "
3158 }
3159 }
3160
3161 func (node UpdateExprs) walkSubtree(visit Visit) error {
3162 for _, n := range node {
3163 if err := Walk(visit, n); err != nil {
3164 return err
3165 }
3166 }
3167 return nil
3168 }
3169
3170 // UpdateExpr represents an update expression.
3171 type UpdateExpr struct {
3172 Name *ColName
3173 Expr Expr
3174 }
3175
3176 // Format formats the node.
3177 func (node *UpdateExpr) Format(buf *TrackedBuffer) {
3178 buf.Myprintf("%v = %v", node.Name, node.Expr)
3179 }
3180
3181 func (node *UpdateExpr) walkSubtree(visit Visit) error {
3182 if node == nil {
3183 return nil
3184 }
3185 return Walk(
3186 visit,
3187 node.Name,
3188 node.Expr,
3189 )
3190 }
3191
3192 // SetExprs represents a list of set expressions.
3193 type SetExprs []*SetExpr
3194
3195 // Format formats the node.
3196 func (node SetExprs) Format(buf *TrackedBuffer) {
3197 var prefix string
3198 for _, n := range node {
3199 buf.Myprintf("%s%v", prefix, n)
3200 prefix = ", "
3201 }
3202 }
3203
3204 func (node SetExprs) walkSubtree(visit Visit) error {
3205 for _, n := range node {
3206 if err := Walk(visit, n); err != nil {
3207 return err
3208 }
3209 }
3210 return nil
3211 }
3212
3213 // SetExpr represents a set expression.
3214 type SetExpr struct {
3215 Name ColIdent
3216 Expr Expr
3217 }
3218
3219 // Format formats the node.
3220 func (node *SetExpr) Format(buf *TrackedBuffer) {
3221 // We don't have to backtick set variable names.
3222 if node.Name.EqualString("charset") || node.Name.EqualString("names") {
3223 buf.Myprintf("%s %v", node.Name.String(), node.Expr)
3224 } else {
3225 buf.Myprintf("%s = %v", node.Name.String(), node.Expr)
3226 }
3227 }
3228
3229 func (node *SetExpr) walkSubtree(visit Visit) error {
3230 if node == nil {
3231 return nil
3232 }
3233 return Walk(
3234 visit,
3235 node.Name,
3236 node.Expr,
3237 )
3238 }
3239
3240 // OnDup represents an ON DUPLICATE KEY clause.
3241 type OnDup UpdateExprs
3242
3243 // Format formats the node.
3244 func (node OnDup) Format(buf *TrackedBuffer) {
3245 if node == nil {
3246 return
3247 }
3248 buf.Myprintf(" on duplicate key update %v", UpdateExprs(node))
3249 }
3250
3251 func (node OnDup) walkSubtree(visit Visit) error {
3252 return Walk(visit, UpdateExprs(node))
3253 }
3254
3255 // ColIdent is a case insensitive SQL identifier. It will be escaped with
3256 // backquotes if necessary.
3257 type ColIdent struct {
3258 // This artifact prevents this struct from being compared
3259 // with itself. It consumes no space as long as it's not the
3260 // last field in the struct.
3261 _ [0]struct{ _ []byte }
3262 val, lowered string
3263 }
3264
3265 // NewColIdent makes a new ColIdent.
3266 func NewColIdent(str string) ColIdent {
3267 return ColIdent{
3268 val: str,
3269 }
3270 }
3271
3272 // Format formats the node.
3273 func (node ColIdent) Format(buf *TrackedBuffer) {
3274 formatID(buf, node.val, node.Lowered())
3275 }
3276
3277 func (node ColIdent) walkSubtree(visit Visit) error {
3278 return nil
3279 }
3280
3281 // IsEmpty returns true if the name is empty.
3282 func (node ColIdent) IsEmpty() bool {
3283 return node.val == ""
3284 }
3285
3286 // String returns the unescaped column name. It must
3287 // not be used for SQL generation. Use sqlparser.String
3288 // instead. The Stringer conformance is for usage
3289 // in templates.
3290 func (node ColIdent) String() string {
3291 return node.val
3292 }
3293
3294 // CompliantName returns a compliant id name
3295 // that can be used for a bind var.
3296 func (node ColIdent) CompliantName() string {
3297 return compliantName(node.val)
3298 }
3299
3300 // Lowered returns a lower-cased column name.
3301 // This function should generally be used only for optimizing
3302 // comparisons.
3303 func (node ColIdent) Lowered() string {
3304 if node.val == "" {
3305 return ""
3306 }
3307 if node.lowered == "" {
3308 node.lowered = strings.ToLower(node.val)
3309 }
3310 return node.lowered
3311 }
3312
3313 // Equal performs a case-insensitive compare.
3314 func (node ColIdent) Equal(in ColIdent) bool {
3315 return node.Lowered() == in.Lowered()
3316 }
3317
3318 // EqualString performs a case-insensitive compare with str.
3319 func (node ColIdent) EqualString(str string) bool {
3320 return node.Lowered() == strings.ToLower(str)
3321 }
3322
3323 // MarshalJSON marshals into JSON.
3324 func (node ColIdent) MarshalJSON() ([]byte, error) {
3325 return json.Marshal(node.val)
3326 }
3327
3328 // UnmarshalJSON unmarshals from JSON.
3329 func (node *ColIdent) UnmarshalJSON(b []byte) error {
3330 var result string
3331 err := json.Unmarshal(b, &result)
3332 if err != nil {
3333 return err
3334 }
3335 node.val = result
3336 return nil
3337 }
3338
3339 // TableIdent is a case sensitive SQL identifier. It will be escaped with
3340 // backquotes if necessary.
3341 type TableIdent struct {
3342 v string
3343 }
3344
3345 // NewTableIdent creates a new TableIdent.
3346 func NewTableIdent(str string) TableIdent {
3347 return TableIdent{v: str}
3348 }
3349
3350 // Format formats the node.
3351 func (node TableIdent) Format(buf *TrackedBuffer) {
3352 formatID(buf, node.v, strings.ToLower(node.v))
3353 }
3354
3355 func (node TableIdent) walkSubtree(visit Visit) error {
3356 return nil
3357 }
3358
3359 // IsEmpty returns true if TabIdent is empty.
3360 func (node TableIdent) IsEmpty() bool {
3361 return node.v == ""
3362 }
3363
3364 // String returns the unescaped table name. It must
3365 // not be used for SQL generation. Use sqlparser.String
3366 // instead. The Stringer conformance is for usage
3367 // in templates.
3368 func (node TableIdent) String() string {
3369 return node.v
3370 }
3371
3372 // CompliantName returns a compliant id name
3373 // that can be used for a bind var.
3374 func (node TableIdent) CompliantName() string {
3375 return compliantName(node.v)
3376 }
3377
3378 // MarshalJSON marshals into JSON.
3379 func (node TableIdent) MarshalJSON() ([]byte, error) {
3380 return json.Marshal(node.v)
3381 }
3382
3383 // UnmarshalJSON unmarshals from JSON.
3384 func (node *TableIdent) UnmarshalJSON(b []byte) error {
3385 var result string
3386 err := json.Unmarshal(b, &result)
3387 if err != nil {
3388 return err
3389 }
3390 node.v = result
3391 return nil
3392 }
3393
3394 // Backtick produces a backticked literal given an input string.
3395 func Backtick(in string) string {
3396 var buf bytes.Buffer
3397 buf.WriteByte('`')
3398 for _, c := range in {
3399 buf.WriteRune(c)
3400 if c == '`' {
3401 buf.WriteByte('`')
3402 }
3403 }
3404 buf.WriteByte('`')
3405 return buf.String()
3406 }
3407
3408 func formatID(buf *TrackedBuffer, original, lowered string) {
3409 isDbSystemVariable := false
3410 if len(original) > 1 && original[:2] == "@@" {
3411 isDbSystemVariable = true
3412 }
3413
3414 for i, c := range original {
3415 if !isLetter(uint16(c)) && (!isDbSystemVariable || !isCarat(uint16(c))) {
3416 if i == 0 || !isDigit(uint16(c)) {
3417 goto mustEscape
3418 }
3419 }
3420 }
3421 if _, ok := keywords[lowered]; ok {
3422 goto mustEscape
3423 }
3424 buf.Myprintf("%s", original)
3425 return
3426
3427 mustEscape:
3428 buf.WriteByte('`')
3429 for _, c := range original {
3430 buf.WriteRune(c)
3431 if c == '`' {
3432 buf.WriteByte('`')
3433 }
3434 }
3435 buf.WriteByte('`')
3436 }
3437
3438 func compliantName(in string) string {
3439 var buf bytes.Buffer
3440 for i, c := range in {
3441 if !isLetter(uint16(c)) {
3442 if i == 0 || !isDigit(uint16(c)) {
3443 buf.WriteByte('_')
3444 continue
3445 }
3446 }
3447 buf.WriteRune(c)
3448 }
3449 return buf.String()
3450 }