github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/sqlparse/sqlparser/ast.go (about) 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 "errors" 24 "fmt" 25 "strings" 26 27 "github.com/bingoohuang/gg/pkg/sqlparse/sqltypes" 28 tidbparser "github.com/bingoohuang/gg/pkg/sqlparse/tidbparser/parser" 29 ) 30 31 // Instructions for creating new types: If a type 32 // needs to satisfy an interface, declare that function 33 // along with that interface. This will help users 34 // identify the list of types to which they can assert 35 // those interfaces. 36 // If the member of a type has a string with a predefined 37 // list of values, declare those values as const following 38 // the type. 39 // For interfaces that define dummy functions to consolidate 40 // a set of types, define the function as iTypeName. 41 // This will help avoid name collisions. 42 43 // Parse parses the sql and returns a Statement, which 44 // is the AST representation of the query. 45 func Parse(sql string) (Statement, error) { 46 tokenizer := NewStringTokenizer(sql) 47 if yyParse(tokenizer) != 0 { 48 return nil, errors.New(tokenizer.LastError) 49 } 50 ast := tokenizer.ParseTree 51 switch stmt := ast.(type) { 52 case *DDL: 53 stmts, err := tidbparser.New().Parse(sql, "", "") 54 if err != nil { 55 return nil, err 56 } 57 return convertTiDBStmtToVitessDDL(stmts, stmt), nil 58 case *Show: 59 stmts, err := tidbparser.New().Parse(sql, "", "") 60 if err != nil { 61 return nil, err 62 } 63 return convertTiDBStmtToVitessShow(stmts, stmt), nil 64 case *OtherAdmin: 65 stmts, err := tidbparser.New().Parse(sql, "", "") 66 if err != nil { 67 return nil, err 68 } 69 return convertTiDBStmtToVitessOtherAdmin(stmts, stmt), nil 70 } 71 return ast, nil 72 } 73 74 // SQLNode defines the interface for all nodes 75 // generated by the parser. 76 type SQLNode interface { 77 Format(buf *TrackedBuffer) 78 // WalkSubtree calls visit on all underlying nodes 79 // of the subtree, but not the current one. Walking 80 // must be interrupted if visit returns an error. 81 WalkSubtree(visit Visit) error 82 } 83 84 // Visit defines the signature of a function that 85 // can be used to visit all nodes of a parse tree. 86 type Visit func(node SQLNode) (kontinue bool, err error) 87 88 // Walk calls visit on every node. 89 // If visit returns true, the underlying nodes 90 // are also visited. If it returns an error, walking 91 // is interrupted, and the error is returned. 92 func Walk(visit Visit, nodes ...SQLNode) error { 93 for _, node := range nodes { 94 if node == nil { 95 continue 96 } 97 kontinue, err := visit(node) 98 if err != nil { 99 return err 100 } 101 if kontinue { 102 err = node.WalkSubtree(visit) 103 if err != nil { 104 return err 105 } 106 } 107 } 108 return nil 109 } 110 111 // String returns a string representation of an SQLNode. 112 func String(node SQLNode) string { 113 buf := NewTrackedBuffer(nil) 114 buf.Myprintf("%v", node) 115 return buf.String() 116 } 117 118 // Append appends the SQLNode to the buffer. 119 func Append(buf *bytes.Buffer, node SQLNode) { 120 tbuf := &TrackedBuffer{ 121 Buffer: buf, 122 } 123 node.Format(tbuf) 124 } 125 126 // GenerateParsedQuery returns a ParsedQuery of the ast. 127 func GenerateParsedQuery(node SQLNode) *ParsedQuery { 128 buf := NewTrackedBuffer(nil) 129 buf.Myprintf("%v", node) 130 return buf.ParsedQuery() 131 } 132 133 // Statement represents a statement. 134 type Statement interface { 135 iStatement() 136 SQLNode 137 } 138 139 func (*Union) iStatement() {} 140 func (*Select) iStatement() {} 141 func (*Insert) iStatement() {} 142 func (*Update) iStatement() {} 143 func (*Delete) iStatement() {} 144 func (*Set) iStatement() {} 145 func (*DDL) iStatement() {} 146 func (*Show) iStatement() {} 147 func (*Use) iStatement() {} 148 func (*OtherRead) iStatement() {} 149 func (*OtherAdmin) iStatement() {} 150 func (*TruncateTable) iStatement() {} 151 152 // ParenSelect can actually not be a top level statement, 153 // but we have to allow it because it's a requirement 154 // of SelectStatement. 155 func (*ParenSelect) iStatement() {} 156 157 // SelectStatement any SELECT statement. 158 type SelectStatement interface { 159 iSelectStatement() 160 iStatement() 161 iInsertRows() 162 AddOrder(*Order) 163 SetLimit(*Limit) 164 SQLNode 165 } 166 167 func (*Select) iSelectStatement() {} 168 func (*Union) iSelectStatement() {} 169 func (*ParenSelect) iSelectStatement() {} 170 171 // Select represents a SELECT statement. 172 type Select struct { 173 Cache string 174 Comments Comments 175 Distinct string 176 Hints string 177 SelectExprs SelectExprs 178 From TableExprs 179 Where *Where 180 GroupBy GroupBy 181 Having *Where 182 OrderBy OrderBy 183 Limit *Limit 184 LimitSQLNode SQLNode 185 Lock string 186 } 187 188 func (node *Select) GetWhere() *Where { return node.Where } 189 func (node *Select) SetWhere(w *Where) { node.Where = w } 190 191 // Select.Distinct 192 const ( 193 DistinctStr = "distinct " 194 StraightJoinHint = "straight_join " 195 ) 196 197 // Select.Lock 198 const ( 199 ForUpdateStr = " for update" 200 ShareModeStr = " lock in share mode" 201 ) 202 203 // Select.Cache 204 const ( 205 SQLCacheStr = "sql_cache " 206 SQLNoCacheStr = "sql_no_cache " 207 ) 208 209 // AddOrder adds an order by element 210 func (node *Select) AddOrder(order *Order) { 211 node.OrderBy = append(node.OrderBy, order) 212 } 213 214 // SetLimit sets the limit clause 215 func (node *Select) SetLimit(limit *Limit) { 216 node.Limit = limit 217 } 218 219 // SetLimitSQLNode sets the limit clause. 220 func (node *Select) SetLimitSQLNode(limit SQLNode) { 221 node.LimitSQLNode = limit 222 } 223 224 // Format formats the node. 225 func (node *Select) Format(buf *TrackedBuffer) { 226 limit := node.LimitSQLNode 227 if limit == nil { 228 limit = node.Limit 229 } 230 231 buf.Myprintf("select %v%s%s%s%v from %v%v%v%v%v%v%s", 232 node.Comments, node.Cache, node.Distinct, node.Hints, node.SelectExprs, 233 node.From, node.Where, 234 node.GroupBy, node.Having, node.OrderBy, 235 limit, node.Lock) 236 } 237 238 // WalkSubtree walks the nodes of the subtree. 239 func (node *Select) WalkSubtree(visit Visit) error { 240 if node == nil { 241 return nil 242 } 243 return Walk( 244 visit, 245 node.Comments, 246 node.SelectExprs, 247 node.From, 248 node.Where, 249 node.GroupBy, 250 node.Having, 251 node.OrderBy, 252 node.Limit, 253 ) 254 } 255 256 // AddWhere adds the boolean expression to the 257 // WHERE clause as an AND condition. If the expression 258 // is an OR clause, it parenthesizes it. Currently, 259 // the OR operator is the only one that's lower precedence 260 // than AND. 261 func (node *Select) AddWhere(expr Expr) { 262 if _, ok := expr.(*OrExpr); ok { 263 expr = &ParenExpr{Expr: expr} 264 } 265 if node.Where == nil { 266 node.Where = &Where{ 267 Type: WhereStr, 268 Expr: expr, 269 } 270 return 271 } 272 node.Where.Expr = &AndExpr{ 273 Left: node.Where.Expr, 274 Right: expr, 275 } 276 } 277 278 // AddHaving adds the boolean expression to the 279 // HAVING clause as an AND condition. If the expression 280 // is an OR clause, it parenthesizes it. Currently, 281 // the OR operator is the only one that's lower precedence 282 // than AND. 283 func (node *Select) AddHaving(expr Expr) { 284 if _, ok := expr.(*OrExpr); ok { 285 expr = &ParenExpr{Expr: expr} 286 } 287 if node.Having == nil { 288 node.Having = &Where{ 289 Type: HavingStr, 290 Expr: expr, 291 } 292 return 293 } 294 node.Having.Expr = &AndExpr{ 295 Left: node.Having.Expr, 296 Right: expr, 297 } 298 } 299 300 // ParenSelect is a parenthesized SELECT statement. 301 type ParenSelect struct { 302 Select SelectStatement 303 } 304 305 // AddOrder adds an order by element 306 func (node *ParenSelect) AddOrder(order *Order) { 307 panic("unreachable") 308 } 309 310 // SetLimit sets the limit clause 311 func (node *ParenSelect) SetLimit(limit *Limit) { 312 panic("unreachable") 313 } 314 315 // Format formats the node. 316 func (node *ParenSelect) Format(buf *TrackedBuffer) { 317 buf.Myprintf("(%v)", node.Select) 318 } 319 320 // WalkSubtree walks the nodes of the subtree. 321 func (node *ParenSelect) WalkSubtree(visit Visit) error { 322 if node == nil { 323 return nil 324 } 325 return Walk( 326 visit, 327 node.Select, 328 ) 329 } 330 331 // Union represents a UNION statement. 332 type Union struct { 333 Type string 334 Left, Right SelectStatement 335 OrderBy OrderBy 336 Limit *Limit 337 Lock string 338 } 339 340 // Union.Type 341 const ( 342 UnionStr = "union" 343 UnionAllStr = "union all" 344 UnionDistinctStr = "union distinct" 345 ) 346 347 // AddOrder adds an order by element 348 func (node *Union) AddOrder(order *Order) { 349 node.OrderBy = append(node.OrderBy, order) 350 } 351 352 // SetLimit sets the limit clause 353 func (node *Union) SetLimit(limit *Limit) { 354 node.Limit = limit 355 } 356 357 // Format formats the node. 358 func (node *Union) Format(buf *TrackedBuffer) { 359 buf.Myprintf("%v %s %v%v%v%s", node.Left, node.Type, node.Right, 360 node.OrderBy, node.Limit, node.Lock) 361 } 362 363 // WalkSubtree walks the nodes of the subtree. 364 func (node *Union) WalkSubtree(visit Visit) error { 365 if node == nil { 366 return nil 367 } 368 return Walk( 369 visit, 370 node.Left, 371 node.Right, 372 ) 373 } 374 375 // Insert represents an INSERT or REPLACE statement. 376 // Per the MySQL docs, http://dev.mysql.com/doc/refman/5.7/en/replace.html 377 // Replace is the counterpart to `INSERT IGNORE`, and works exactly like a 378 // normal INSERT except if the row exists. In that case it first deletes 379 // the row and re-inserts with new values. For that reason we keep it as an Insert struct. 380 // Replaces are currently disallowed in sharded schemas because 381 // of the implications the deletion part may have on vindexes. 382 type Insert struct { 383 Action string 384 Comments Comments 385 Ignore string 386 Table TableName 387 Columns Columns 388 Rows InsertRows 389 OnDup OnDup 390 } 391 392 // DDL strings. 393 const ( 394 InsertStr = "insert" 395 ReplaceStr = "replace" 396 ) 397 398 // Format formats the node. 399 func (node *Insert) Format(buf *TrackedBuffer) { 400 buf.Myprintf("%s %v%sinto %v%v %v%v", 401 node.Action, 402 node.Comments, node.Ignore, 403 node.Table, node.Columns, node.Rows, node.OnDup) 404 } 405 406 // WalkSubtree walks the nodes of the subtree. 407 func (node *Insert) WalkSubtree(visit Visit) error { 408 if node == nil { 409 return nil 410 } 411 return Walk( 412 visit, 413 node.Comments, 414 node.Table, 415 node.Columns, 416 node.Rows, 417 node.OnDup, 418 ) 419 } 420 421 // InsertRows represents the rows for an INSERT statement. 422 type InsertRows interface { 423 iInsertRows() 424 SQLNode 425 } 426 427 func (*Select) iInsertRows() {} 428 func (*Union) iInsertRows() {} 429 func (Values) iInsertRows() {} 430 func (*ParenSelect) iInsertRows() {} 431 432 // Update represents an UPDATE statement. 433 type Update struct { 434 Comments Comments 435 TableExprs TableExprs 436 Exprs UpdateExprs 437 Where *Where 438 OrderBy OrderBy 439 Limit *Limit 440 } 441 442 func (node *Update) GetWhere() *Where { return node.Where } 443 func (node *Update) SetWhere(w *Where) { node.Where = w } 444 445 // Format formats the node. 446 func (node *Update) Format(buf *TrackedBuffer) { 447 buf.Myprintf("update %v%v set %v%v%v%v", 448 node.Comments, node.TableExprs, 449 node.Exprs, node.Where, node.OrderBy, node.Limit) 450 } 451 452 // WalkSubtree walks the nodes of the subtree. 453 func (node *Update) WalkSubtree(visit Visit) error { 454 if node == nil { 455 return nil 456 } 457 return Walk( 458 visit, 459 node.Comments, 460 node.TableExprs, 461 node.Exprs, 462 node.Where, 463 node.OrderBy, 464 node.Limit, 465 ) 466 } 467 468 // Delete represents a DELETE statement. 469 type Delete struct { 470 Comments Comments 471 Targets TableNames 472 TableExprs TableExprs 473 Where *Where 474 OrderBy OrderBy 475 Limit *Limit 476 } 477 478 func (node *Delete) GetWhere() *Where { return node.Where } 479 func (node *Delete) SetWhere(w *Where) { node.Where = w } 480 481 // Format formats the node. 482 func (node *Delete) Format(buf *TrackedBuffer) { 483 buf.Myprintf("delete %v", node.Comments) 484 if node.Targets != nil { 485 buf.Myprintf("%v ", node.Targets) 486 } 487 buf.Myprintf("from %v%v%v%v", node.TableExprs, node.Where, node.OrderBy, node.Limit) 488 } 489 490 // WalkSubtree walks the nodes of the subtree. 491 func (node *Delete) WalkSubtree(visit Visit) error { 492 if node == nil { 493 return nil 494 } 495 return Walk( 496 visit, 497 node.Comments, 498 node.Targets, 499 node.TableExprs, 500 node.Where, 501 node.OrderBy, 502 node.Limit, 503 ) 504 } 505 506 // Set represents a SET statement. 507 type Set struct { 508 Comments Comments 509 Exprs UpdateExprs 510 } 511 512 // Format formats the node. 513 func (node *Set) Format(buf *TrackedBuffer) { 514 buf.Myprintf("set %v%v", node.Comments, node.Exprs) 515 } 516 517 // WalkSubtree walks the nodes of the subtree. 518 func (node *Set) WalkSubtree(visit Visit) error { 519 if node == nil { 520 return nil 521 } 522 return Walk( 523 visit, 524 node.Comments, 525 node.Exprs, 526 ) 527 } 528 529 // DDL represents a CREATE, ALTER, DROP or RENAME statement. 530 // Table is set for AlterStr, DropStr, RenameStr. 531 // NewName is set for AlterStr, CreateStr, RenameStr. 532 type DDL struct { 533 Action string 534 Table TableName 535 NewName TableName 536 IfExists bool 537 } 538 539 type TableOption struct { 540 Type TableOptionType 541 StrValue string 542 UintValue uint64 543 } 544 545 type TableOptionType int 546 547 // TableOption types. 548 const ( 549 TableOptionNone TableOptionType = iota 550 TableOptionEngine 551 TableOptionCharset 552 TableOptionCollate 553 TableOptionAutoIncrement 554 TableOptionComment 555 TableOptionAvgRowLength 556 TableOptionCheckSum 557 TableOptionCompression 558 TableOptionConnection 559 TableOptionPassword 560 TableOptionKeyBlockSize 561 TableOptionMaxRows 562 TableOptionMinRows 563 TableOptionDelayKeyWrite 564 TableOptionRowFormat 565 TableOptionStatsPersistent 566 TableOptionShardRowID 567 TableOptionPackKeys 568 ) 569 570 // RowFormatType is the type for RowFormat 571 type RowFormatType uint64 572 573 // RowFormat types 574 const ( 575 RowFormatDefault RowFormatType = iota + 1 576 RowFormatDynamic 577 RowFormatFixed 578 RowFormatCompressed 579 RowFormatRedundant 580 RowFormatCompact 581 ) 582 583 func (r RowFormatType) String() string { 584 switch r { 585 case RowFormatDynamic: 586 return "DYNAMIC" 587 case RowFormatCompressed: 588 return "COMPRESSED" 589 case RowFormatRedundant: 590 return "REDUNDANT" 591 case RowFormatCompact: 592 return "COMPACT" 593 default: 594 } 595 return "" 596 } 597 598 func (t TableOptionType) String() string { 599 switch t { 600 case TableOptionEngine: 601 return "ENGINE" 602 case TableOptionCharset: 603 return "DEFAULT CHARSET" 604 case TableOptionCollate: 605 return "DEFAULT COLLATE" 606 case TableOptionAutoIncrement: 607 return "AUTO_INCREMENT" 608 case TableOptionComment: 609 return "COMMENT" 610 case TableOptionAvgRowLength: 611 return "AVG_ROW_LENGTH" 612 case TableOptionCheckSum: 613 return "CHECKSUM" 614 case TableOptionConnection: 615 return "CONNECTION" 616 case TableOptionPassword: 617 return "PASSWORD" 618 case TableOptionKeyBlockSize: 619 return "KEY_BLOCK_SIZE" 620 case TableOptionMaxRows: 621 return "MAX_ROWS" 622 case TableOptionMinRows: 623 return "MIN_ROWS" 624 case TableOptionDelayKeyWrite: 625 return "DELAY_KEY_WRITE" 626 case TableOptionRowFormat: 627 return "ROW_FORMAT" 628 case TableOptionStatsPersistent: 629 return "STATS_PERSISTENT" 630 case TableOptionPackKeys: 631 return "PACK_KEYS" 632 case TableOptionCompression: 633 case TableOptionShardRowID: 634 default: 635 } 636 return "" 637 } 638 639 func (o *TableOption) String() string { 640 if o.Type == TableOptionRowFormat { 641 return fmt.Sprintf("%s=%s", o.Type, RowFormatType(o.UintValue)) 642 } 643 if o.StrValue != "" { 644 return fmt.Sprintf("%s=%s", o.Type, o.StrValue) 645 } 646 return fmt.Sprintf("%s=%d", o.Type, o.UintValue) 647 } 648 649 type CreateTable struct { 650 *DDL 651 Columns []*ColumnDef 652 Constraints []*Constraint 653 Options []*TableOption 654 } 655 656 func (t *CreateTable) Format(buf *TrackedBuffer) { 657 var columns []string 658 for _, column := range t.Columns { 659 columns = append(columns, column.String()) 660 } 661 column := strings.Join(columns, ",\n\t") 662 if len(t.Constraints) > 0 { 663 var constraints []string 664 for _, constraint := range t.Constraints { 665 constraints = append(constraints, constraint.String()) 666 } 667 column += ",\n\t" + strings.Join(constraints, ",\n\t") 668 } 669 var options []string 670 for _, option := range t.Options { 671 options = append(options, option.String()) 672 } 673 option := strings.Join(options, " ") 674 675 if column != "" { 676 text := fmt.Sprintf("CREATE TABLE `%v` (\n\t%s\n) %s", t.NewName.Name, column, option) 677 buf.Myprintf("%s", text) 678 } else { 679 text := fmt.Sprintf("CREATE TABLE `%v` %s", t.NewName.Name, option) 680 buf.Myprintf("%s", text) 681 } 682 } 683 684 // DDL strings. 685 const ( 686 CreateStr = "create" 687 AlterStr = "alter" 688 DropStr = "drop" 689 RenameStr = "rename" 690 ) 691 692 // Format formats the node. 693 func (node *DDL) Format(buf *TrackedBuffer) { 694 switch node.Action { 695 case DropStr: 696 exists := "" 697 if node.IfExists { 698 exists = " if exists" 699 } 700 buf.Myprintf("%s table%s %v", node.Action, exists, node.Table) 701 case RenameStr: 702 buf.Myprintf("%s table %v %v", node.Action, node.Table, node.NewName) 703 default: 704 buf.Myprintf("%s table %v", node.Action, node.Table) 705 } 706 } 707 708 // WalkSubtree walks the nodes of the subtree. 709 func (node *DDL) WalkSubtree(visit Visit) error { 710 if node == nil { 711 return nil 712 } 713 return Walk( 714 visit, 715 node.Table, 716 node.NewName, 717 ) 718 } 719 720 // Show represents a show statement. 721 type Show struct { 722 Type string 723 TableName string 724 } 725 726 // The frollowing constants represent SHOW statements. 727 const ( 728 ShowDatabasesStr = "databases" 729 ShowKeyspacesStr = "vitess_keyspaces" 730 ShowShardsStr = "vitess_shards" 731 ShowTablesStr = "tables" 732 ShowVSchemaTablesStr = "vschema_tables" 733 ShowUnsupportedStr = "unsupported" 734 ) 735 736 // Format formats the node. 737 func (node *Show) Format(buf *TrackedBuffer) { 738 buf.Myprintf("show %s", node.Type) 739 } 740 741 // WalkSubtree walks the nodes of the subtree. 742 func (node *Show) WalkSubtree(visit Visit) error { 743 return nil 744 } 745 746 // Use represents a use statement. 747 type Use struct { 748 DBName TableIdent 749 } 750 751 // Format formats the node. 752 func (node *Use) Format(buf *TrackedBuffer) { 753 buf.Myprintf("use %v", node.DBName) 754 } 755 756 // WalkSubtree walks the nodes of the subtree. 757 func (node *Use) WalkSubtree(visit Visit) error { 758 return Walk(visit, node.DBName) 759 } 760 761 // OtherRead represents a DESCRIBE, or EXPLAIN statement. 762 // It should be used only as an indicator. It does not contain 763 // the full AST for the statement. 764 type OtherRead struct{} 765 766 // Format formats the node. 767 func (node *OtherRead) Format(buf *TrackedBuffer) { 768 buf.WriteString("otherread") 769 } 770 771 // WalkSubtree walks the nodes of the subtree. 772 func (node *OtherRead) WalkSubtree(visit Visit) error { 773 return nil 774 } 775 776 // OtherAdmin represents a misc statement that relies on ADMIN privileges, 777 // such as REPAIR, OPTIMIZE, or TRUNCATE statement. 778 // It should be used only as an indicator. It does not contain 779 // the full AST for the statement. 780 type OtherAdmin struct{} 781 782 type TruncateTable struct { 783 Table TableName 784 } 785 786 // Format formats the node. 787 func (node *TruncateTable) Format(buf *TrackedBuffer) { 788 buf.Myprintf("truncate %v", node.Table) 789 } 790 791 // WalkSubtree walks the nodes of the subtree. 792 func (node *TruncateTable) WalkSubtree(visit Visit) error { 793 if node == nil { 794 return nil 795 } 796 return Walk( 797 visit, 798 node.Table, 799 ) 800 } 801 802 // Format formats the node. 803 func (node *OtherAdmin) Format(buf *TrackedBuffer) { 804 buf.WriteString("otheradmin") 805 } 806 807 // WalkSubtree walks the nodes of the subtree. 808 func (node *OtherAdmin) WalkSubtree(visit Visit) error { 809 return nil 810 } 811 812 // Comments represents a list of comments. 813 type Comments [][]byte 814 815 // Format formats the node. 816 func (node Comments) Format(buf *TrackedBuffer) { 817 for _, c := range node { 818 buf.Myprintf("%s ", c) 819 } 820 } 821 822 // WalkSubtree walks the nodes of the subtree. 823 func (node Comments) WalkSubtree(visit Visit) error { 824 return nil 825 } 826 827 // SelectExprs represents SELECT expressions. 828 type SelectExprs []SelectExpr 829 830 // Format formats the node. 831 func (node SelectExprs) Format(buf *TrackedBuffer) { 832 var prefix string 833 for _, n := range node { 834 buf.Myprintf("%s%v", prefix, n) 835 prefix = ", " 836 } 837 } 838 839 // WalkSubtree walks the nodes of the subtree. 840 func (node SelectExprs) WalkSubtree(visit Visit) error { 841 for _, n := range node { 842 if err := Walk(visit, n); err != nil { 843 return err 844 } 845 } 846 return nil 847 } 848 849 // SelectExpr represents a SELECT expression. 850 type SelectExpr interface { 851 iSelectExpr() 852 SQLNode 853 } 854 855 func (*StarExpr) iSelectExpr() {} 856 func (*AliasedExpr) iSelectExpr() {} 857 func (Nextval) iSelectExpr() {} 858 859 // StarExpr defines a '*' or 'table.*' expression. 860 type StarExpr struct { 861 TableName TableName 862 } 863 864 // Format formats the node. 865 func (node *StarExpr) Format(buf *TrackedBuffer) { 866 if !node.TableName.IsEmpty() { 867 buf.Myprintf("%v.", node.TableName) 868 } 869 buf.Myprintf("*") 870 } 871 872 // WalkSubtree walks the nodes of the subtree. 873 func (node *StarExpr) WalkSubtree(visit Visit) error { 874 if node == nil { 875 return nil 876 } 877 return Walk( 878 visit, 879 node.TableName, 880 ) 881 } 882 883 // AliasedExpr defines an aliased SELECT expression. 884 type AliasedExpr struct { 885 Expr Expr 886 As ColIdent 887 } 888 889 // Format formats the node. 890 func (node *AliasedExpr) Format(buf *TrackedBuffer) { 891 buf.Myprintf("%v", node.Expr) 892 if !node.As.IsEmpty() { 893 buf.Myprintf(" as %v", node.As) 894 } 895 } 896 897 // WalkSubtree walks the nodes of the subtree. 898 func (node *AliasedExpr) WalkSubtree(visit Visit) error { 899 if node == nil { 900 return nil 901 } 902 return Walk( 903 visit, 904 node.Expr, 905 node.As, 906 ) 907 } 908 909 // Nextval defines the NEXT VALUE expression. 910 type Nextval struct { 911 Expr Expr 912 } 913 914 // Format formats the node. 915 func (node Nextval) Format(buf *TrackedBuffer) { 916 buf.Myprintf("next %v values", node.Expr) 917 } 918 919 // WalkSubtree walks the nodes of the subtree. 920 func (node Nextval) WalkSubtree(visit Visit) error { 921 return Walk(visit, node.Expr) 922 } 923 924 type ConstraintType int 925 926 const ( 927 ConstraintNoConstraint ConstraintType = iota 928 ConstraintPrimaryKey 929 ConstraintKey 930 ConstraintIndex 931 ConstraintUniq 932 ConstraintUniqKey 933 ConstraintUniqIndex 934 ConstraintForeignKey 935 ConstraintFulltext 936 ) 937 938 func (t ConstraintType) String() string { 939 switch t { 940 case ConstraintPrimaryKey: 941 return "PRIMARY KEY" 942 case ConstraintKey: 943 return "KEY" 944 case ConstraintIndex: 945 return "INDEX" 946 case ConstraintUniq: 947 return "UNIQUE" 948 case ConstraintUniqKey: 949 return "UNIQUE KEY" 950 case ConstraintUniqIndex: 951 return "UNIQUE INDEX" 952 case ConstraintForeignKey: 953 return "FOREIGN KEY" 954 case ConstraintFulltext: 955 return "FULLTEXT" 956 } 957 return "" 958 } 959 960 // Constraint is constraint for table definition. 961 type Constraint struct { 962 Type ConstraintType 963 Name string 964 // Used for PRIMARY KEY, UNIQUE, ...... 965 Keys []ColIdent 966 } 967 968 func (node Constraint) String() string { 969 var keys []string 970 for _, key := range node.Keys { 971 keys = append(keys, fmt.Sprintf("`%v`", key)) 972 } 973 name := "" 974 if node.Name != "" { 975 name = fmt.Sprintf("`%s`", node.Name) 976 } 977 return fmt.Sprintf("%s %s (%s)", node.Type.String(), name, strings.Join(keys, ", ")) 978 } 979 980 // ColumnOptionType is the type for ColumnOption. 981 type ColumnOptionType int 982 983 const ( 984 ColumnOptionNoOption ColumnOptionType = iota 985 ColumnOptionPrimaryKey 986 ColumnOptionNotNull 987 ColumnOptionAutoIncrement 988 ColumnOptionDefaultValue 989 ColumnOptionUniqKey 990 ColumnOptionNull 991 ColumnOptionOnUpdate // For Timestamp and Datetime only. 992 ColumnOptionFulltext 993 ColumnOptionComment 994 ColumnOptionGenerated 995 ColumnOptionReference 996 ) 997 998 func (o ColumnOptionType) String() string { 999 switch o { 1000 case ColumnOptionPrimaryKey: 1001 return "PRIMARY KEY" 1002 case ColumnOptionNotNull: 1003 return "NOT NULL" 1004 case ColumnOptionAutoIncrement: 1005 return "AUTO_INCREMENT" 1006 case ColumnOptionDefaultValue: 1007 return "DEFAULT" 1008 case ColumnOptionUniqKey: 1009 return "UNIQUE KEY" 1010 case ColumnOptionNull: 1011 return "NULL" 1012 case ColumnOptionOnUpdate: 1013 return "ON UPDATE" 1014 case ColumnOptionFulltext: 1015 return "FULLTEXT" 1016 case ColumnOptionComment: 1017 return "COMMENT" 1018 case ColumnOptionGenerated: 1019 case ColumnOptionReference: 1020 default: 1021 } 1022 return "" 1023 } 1024 1025 // ColumnOption is used for parsing column constraint info from SQL. 1026 type ColumnOption struct { 1027 Type ColumnOptionType 1028 Value string 1029 } 1030 1031 func (o *ColumnOption) String() string { 1032 if o.Value != "" { 1033 return fmt.Sprintf("%s %s", o.Type, o.Value) 1034 } 1035 return fmt.Sprint(o.Type) 1036 } 1037 1038 type ColumnDef struct { 1039 Name string 1040 Type string 1041 // Elems is the element list for enum and set type. 1042 Elems []string 1043 Options []*ColumnOption 1044 } 1045 1046 func (node ColumnDef) String() string { 1047 option := "" 1048 if len(node.Options) > 0 { 1049 var options []string 1050 for _, option := range node.Options { 1051 options = append(options, option.String()) 1052 } 1053 option = " " + strings.Join(options, " ") 1054 } 1055 return fmt.Sprintf("`%s` %s%s", node.Name, node.Type, option) 1056 } 1057 1058 // Columns represents an insert column list. 1059 type Columns []ColIdent 1060 1061 // Format formats the node. 1062 func (node Columns) Format(buf *TrackedBuffer) { 1063 if node == nil { 1064 return 1065 } 1066 prefix := "(" 1067 for _, n := range node { 1068 buf.Myprintf("%s%v", prefix, n) 1069 prefix = ", " 1070 } 1071 buf.WriteString(")") 1072 } 1073 1074 // WalkSubtree walks the nodes of the subtree. 1075 func (node Columns) WalkSubtree(visit Visit) error { 1076 for _, n := range node { 1077 if err := Walk(visit, n); err != nil { 1078 return err 1079 } 1080 } 1081 return nil 1082 } 1083 1084 // FindColumn finds a column in the column list, returning 1085 // the index if it exists or -1 otherwise 1086 func (node Columns) FindColumn(col ColIdent) int { 1087 for i, colName := range node { 1088 if colName.Equal(col) { 1089 return i 1090 } 1091 } 1092 return -1 1093 } 1094 1095 // TableExprs represents a list of table expressions. 1096 type TableExprs []TableExpr 1097 1098 // Format formats the node. 1099 func (node TableExprs) Format(buf *TrackedBuffer) { 1100 var prefix string 1101 for _, n := range node { 1102 buf.Myprintf("%s%v", prefix, n) 1103 prefix = ", " 1104 } 1105 } 1106 1107 // WalkSubtree walks the nodes of the subtree. 1108 func (node TableExprs) WalkSubtree(visit Visit) error { 1109 for _, n := range node { 1110 if err := Walk(visit, n); err != nil { 1111 return err 1112 } 1113 } 1114 return nil 1115 } 1116 1117 // TableExpr represents a table expression. 1118 type TableExpr interface { 1119 iTableExpr() 1120 SQLNode 1121 } 1122 1123 func (*AliasedTableExpr) iTableExpr() {} 1124 func (*ParenTableExpr) iTableExpr() {} 1125 func (*JoinTableExpr) iTableExpr() {} 1126 1127 // AliasedTableExpr represents a table expression 1128 // coupled with an optional alias or index hint. 1129 // If As is empty, no alias was used. 1130 type AliasedTableExpr struct { 1131 Expr SimpleTableExpr 1132 As TableIdent 1133 Hints *IndexHints 1134 } 1135 1136 // Format formats the node. 1137 func (node *AliasedTableExpr) Format(buf *TrackedBuffer) { 1138 buf.Myprintf("%v", node.Expr) 1139 if !node.As.IsEmpty() { 1140 buf.Myprintf(" as %v", node.As) 1141 } 1142 if node.Hints != nil { 1143 // Hint node provides the space padding. 1144 buf.Myprintf("%v", node.Hints) 1145 } 1146 } 1147 1148 // WalkSubtree walks the nodes of the subtree. 1149 func (node *AliasedTableExpr) WalkSubtree(visit Visit) error { 1150 if node == nil { 1151 return nil 1152 } 1153 return Walk( 1154 visit, 1155 node.Expr, 1156 node.As, 1157 node.Hints, 1158 ) 1159 } 1160 1161 // SimpleTableExpr represents a simple table expression. 1162 type SimpleTableExpr interface { 1163 iSimpleTableExpr() 1164 SQLNode 1165 } 1166 1167 func (TableName) iSimpleTableExpr() {} 1168 func (*Subquery) iSimpleTableExpr() {} 1169 1170 // TableNames is a list of TableName. 1171 type TableNames []TableName 1172 1173 // Format formats the node. 1174 func (node TableNames) Format(buf *TrackedBuffer) { 1175 var prefix string 1176 for _, n := range node { 1177 buf.Myprintf("%s%v", prefix, n) 1178 prefix = ", " 1179 } 1180 } 1181 1182 // WalkSubtree walks the nodes of the subtree. 1183 func (node TableNames) WalkSubtree(visit Visit) error { 1184 for _, n := range node { 1185 if err := Walk(visit, n); err != nil { 1186 return err 1187 } 1188 } 1189 return nil 1190 } 1191 1192 // TableName represents a table name. 1193 // Qualifier, if specified, represents a database or keyspace. 1194 // TableName is a value struct whose fields are case sensitive. 1195 // This means two TableName vars can be compared for equality 1196 // and a TableName can also be used as key in a map. 1197 type TableName struct { 1198 Name, Qualifier TableIdent 1199 } 1200 1201 // Format formats the node. 1202 func (node TableName) Format(buf *TrackedBuffer) { 1203 if node.IsEmpty() { 1204 return 1205 } 1206 if !node.Qualifier.IsEmpty() { 1207 buf.Myprintf("%v.", node.Qualifier) 1208 } 1209 buf.Myprintf("%v", node.Name) 1210 } 1211 1212 // WalkSubtree walks the nodes of the subtree. 1213 func (node TableName) WalkSubtree(visit Visit) error { 1214 return Walk( 1215 visit, 1216 node.Name, 1217 node.Qualifier, 1218 ) 1219 } 1220 1221 // IsEmpty returns true if TableName is nil or empty. 1222 func (node TableName) IsEmpty() bool { 1223 // If Name is empty, Qualifer is also empty. 1224 return node.Name.IsEmpty() 1225 } 1226 1227 // ToViewName returns a TableName acceptable for use as a VIEW. VIEW names are 1228 // always lowercase, so ToViewName lowercasese the name. Databases are case-sensitive 1229 // so Qualifier is left untouched. 1230 func (node TableName) ToViewName() TableName { 1231 return TableName{ 1232 Qualifier: node.Qualifier, 1233 Name: NewTableIdent(strings.ToLower(node.Name.v)), 1234 } 1235 } 1236 1237 // ParenTableExpr represents a parenthesized list of TableExpr. 1238 type ParenTableExpr struct { 1239 Exprs TableExprs 1240 } 1241 1242 // Format formats the node. 1243 func (node *ParenTableExpr) Format(buf *TrackedBuffer) { 1244 buf.Myprintf("(%v)", node.Exprs) 1245 } 1246 1247 // WalkSubtree walks the nodes of the subtree. 1248 func (node *ParenTableExpr) WalkSubtree(visit Visit) error { 1249 if node == nil { 1250 return nil 1251 } 1252 return Walk( 1253 visit, 1254 node.Exprs, 1255 ) 1256 } 1257 1258 // JoinTableExpr represents a TableExpr that's a JOIN operation. 1259 type JoinTableExpr struct { 1260 LeftExpr TableExpr 1261 Join string 1262 RightExpr TableExpr 1263 On Expr 1264 } 1265 1266 // JoinTableExpr.Join 1267 const ( 1268 JoinStr = "join" 1269 StraightJoinStr = "straight_join" 1270 LeftJoinStr = "left join" 1271 RightJoinStr = "right join" 1272 NaturalJoinStr = "natural join" 1273 NaturalLeftJoinStr = "natural left join" 1274 NaturalRightJoinStr = "natural right join" 1275 ) 1276 1277 // Format formats the node. 1278 func (node *JoinTableExpr) Format(buf *TrackedBuffer) { 1279 buf.Myprintf("%v %s %v", node.LeftExpr, node.Join, node.RightExpr) 1280 if node.On != nil { 1281 buf.Myprintf(" on %v", node.On) 1282 } 1283 } 1284 1285 // WalkSubtree walks the nodes of the subtree. 1286 func (node *JoinTableExpr) WalkSubtree(visit Visit) error { 1287 if node == nil { 1288 return nil 1289 } 1290 return Walk( 1291 visit, 1292 node.LeftExpr, 1293 node.RightExpr, 1294 node.On, 1295 ) 1296 } 1297 1298 // IndexHints represents a list of index hints. 1299 type IndexHints struct { 1300 Type string 1301 Indexes []ColIdent 1302 } 1303 1304 // Index hints. 1305 const ( 1306 UseStr = "use " 1307 IgnoreStr = "ignore " 1308 ForceStr = "force " 1309 ) 1310 1311 // Format formats the node. 1312 func (node *IndexHints) Format(buf *TrackedBuffer) { 1313 buf.Myprintf(" %sindex ", node.Type) 1314 prefix := "(" 1315 for _, n := range node.Indexes { 1316 buf.Myprintf("%s%v", prefix, n) 1317 prefix = ", " 1318 } 1319 buf.Myprintf(")") 1320 } 1321 1322 // WalkSubtree walks the nodes of the subtree. 1323 func (node *IndexHints) WalkSubtree(visit Visit) error { 1324 if node == nil { 1325 return nil 1326 } 1327 for _, n := range node.Indexes { 1328 if err := Walk(visit, n); err != nil { 1329 return err 1330 } 1331 } 1332 return nil 1333 } 1334 1335 type IWhere interface { 1336 GetWhere() *Where 1337 SetWhere(*Where) 1338 } 1339 1340 // Where represents a WHERE or HAVING clause. 1341 type Where struct { 1342 Type string 1343 Expr Expr 1344 } 1345 1346 const ( 1347 WhereStr string = "where" 1348 HavingStr string = "having" 1349 ) 1350 1351 // NewWhere creates a WHERE or HAVING clause out 1352 // of a Expr. If the expression is nil, it returns nil. 1353 func NewWhere(typ string, expr Expr) *Where { 1354 if expr == nil { 1355 return nil 1356 } 1357 return &Where{Type: typ, Expr: expr} 1358 } 1359 1360 // Format formats the node. 1361 func (node *Where) Format(buf *TrackedBuffer) { 1362 if node == nil || node.Expr == nil { 1363 return 1364 } 1365 buf.Myprintf(" %s %v", node.Type, node.Expr) 1366 } 1367 1368 // WalkSubtree walks the nodes of the subtree. 1369 func (node *Where) WalkSubtree(visit Visit) error { 1370 if node == nil { 1371 return nil 1372 } 1373 return Walk( 1374 visit, 1375 node.Expr, 1376 ) 1377 } 1378 1379 // Expr represents an expression. 1380 type Expr interface { 1381 iExpr() 1382 SQLNode 1383 } 1384 1385 func (*AndExpr) iExpr() {} 1386 func (*OrExpr) iExpr() {} 1387 func (*NotExpr) iExpr() {} 1388 func (*ParenExpr) iExpr() {} 1389 func (*ComparisonExpr) iExpr() {} 1390 func (*RangeCond) iExpr() {} 1391 func (*IsExpr) iExpr() {} 1392 func (*ExistsExpr) iExpr() {} 1393 func (*SQLVal) iExpr() {} 1394 func (*NullVal) iExpr() {} 1395 func (BoolVal) iExpr() {} 1396 func (*ColName) iExpr() {} 1397 func (ValTuple) iExpr() {} 1398 func (*Subquery) iExpr() {} 1399 func (ListArg) iExpr() {} 1400 func (*BinaryExpr) iExpr() {} 1401 func (*UnaryExpr) iExpr() {} 1402 func (*IntervalExpr) iExpr() {} 1403 func (*CollateExpr) iExpr() {} 1404 func (*FuncExpr) iExpr() {} 1405 func (*CaseExpr) iExpr() {} 1406 func (*ValuesFuncExpr) iExpr() {} 1407 func (*ConvertExpr) iExpr() {} 1408 func (*ConvertUsingExpr) iExpr() {} 1409 func (*MatchExpr) iExpr() {} 1410 func (*GroupConcatExpr) iExpr() {} 1411 func (*Default) iExpr() {} 1412 1413 // Exprs represents a list of value expressions. 1414 // It's not a valid expression because it's not parenthesized. 1415 type Exprs []Expr 1416 1417 // Format formats the node. 1418 func (node Exprs) Format(buf *TrackedBuffer) { 1419 var prefix string 1420 for _, n := range node { 1421 buf.Myprintf("%s%v", prefix, n) 1422 prefix = ", " 1423 } 1424 } 1425 1426 // WalkSubtree walks the nodes of the subtree. 1427 func (node Exprs) WalkSubtree(visit Visit) error { 1428 for _, n := range node { 1429 if err := Walk(visit, n); err != nil { 1430 return err 1431 } 1432 } 1433 return nil 1434 } 1435 1436 // AndExpr represents an AND expression. 1437 type AndExpr struct { 1438 Left, Right Expr 1439 } 1440 1441 // Format formats the node. 1442 func (node *AndExpr) Format(buf *TrackedBuffer) { 1443 buf.Myprintf("%v and %v", node.Left, node.Right) 1444 } 1445 1446 // WalkSubtree walks the nodes of the subtree. 1447 func (node *AndExpr) WalkSubtree(visit Visit) error { 1448 if node == nil { 1449 return nil 1450 } 1451 return Walk( 1452 visit, 1453 node.Left, 1454 node.Right, 1455 ) 1456 } 1457 1458 // OrExpr represents an OR expression. 1459 type OrExpr struct { 1460 Left, Right Expr 1461 } 1462 1463 // Format formats the node. 1464 func (node *OrExpr) Format(buf *TrackedBuffer) { 1465 buf.Myprintf("%v or %v", node.Left, node.Right) 1466 } 1467 1468 // WalkSubtree walks the nodes of the subtree. 1469 func (node *OrExpr) WalkSubtree(visit Visit) error { 1470 if node == nil { 1471 return nil 1472 } 1473 return Walk( 1474 visit, 1475 node.Left, 1476 node.Right, 1477 ) 1478 } 1479 1480 // NotExpr represents a NOT expression. 1481 type NotExpr struct { 1482 Expr Expr 1483 } 1484 1485 // Format formats the node. 1486 func (node *NotExpr) Format(buf *TrackedBuffer) { 1487 buf.Myprintf("not %v", node.Expr) 1488 } 1489 1490 // WalkSubtree walks the nodes of the subtree. 1491 func (node *NotExpr) WalkSubtree(visit Visit) error { 1492 if node == nil { 1493 return nil 1494 } 1495 return Walk( 1496 visit, 1497 node.Expr, 1498 ) 1499 } 1500 1501 // ParenExpr represents a parenthesized boolean expression. 1502 type ParenExpr struct { 1503 Expr Expr 1504 } 1505 1506 // Format formats the node. 1507 func (node *ParenExpr) Format(buf *TrackedBuffer) { 1508 buf.Myprintf("(%v)", node.Expr) 1509 } 1510 1511 // WalkSubtree walks the nodes of the subtree. 1512 func (node *ParenExpr) WalkSubtree(visit Visit) error { 1513 if node == nil { 1514 return nil 1515 } 1516 return Walk( 1517 visit, 1518 node.Expr, 1519 ) 1520 } 1521 1522 // ComparisonExpr represents a two-value comparison expression. 1523 type ComparisonExpr struct { 1524 Operator string 1525 Left, Right Expr 1526 Escape Expr 1527 } 1528 1529 // ComparisonExpr.Operator 1530 const ( 1531 EqualStr = "=" 1532 LessThanStr = "<" 1533 GreaterThanStr = ">" 1534 LessEqualStr = "<=" 1535 GreaterEqualStr = ">=" 1536 NotEqualStr = "!=" 1537 NullSafeEqualStr = "<=>" 1538 InStr = "in" 1539 NotInStr = "not in" 1540 LikeStr = "like" 1541 NotLikeStr = "not like" 1542 RegexpStr = "regexp" 1543 NotRegexpStr = "not regexp" 1544 JSONExtractOp = "->" 1545 JSONUnquoteExtractOp = "->>" 1546 ) 1547 1548 // Format formats the node. 1549 func (node *ComparisonExpr) Format(buf *TrackedBuffer) { 1550 buf.Myprintf("%v %s %v", node.Left, node.Operator, node.Right) 1551 if node.Escape != nil { 1552 buf.Myprintf(" escape %v", node.Escape) 1553 } 1554 } 1555 1556 // WalkSubtree walks the nodes of the subtree. 1557 func (node *ComparisonExpr) WalkSubtree(visit Visit) error { 1558 if node == nil { 1559 return nil 1560 } 1561 return Walk( 1562 visit, 1563 node.Left, 1564 node.Right, 1565 node.Escape, 1566 ) 1567 } 1568 1569 // RangeCond represents a BETWEEN or a NOT BETWEEN expression. 1570 type RangeCond struct { 1571 Operator string 1572 Left Expr 1573 From, To Expr 1574 } 1575 1576 // RangeCond.Operator 1577 const ( 1578 BetweenStr = "between" 1579 NotBetweenStr = "not between" 1580 ) 1581 1582 // Format formats the node. 1583 func (node *RangeCond) Format(buf *TrackedBuffer) { 1584 buf.Myprintf("%v %s %v and %v", node.Left, node.Operator, node.From, node.To) 1585 } 1586 1587 // WalkSubtree walks the nodes of the subtree. 1588 func (node *RangeCond) WalkSubtree(visit Visit) error { 1589 if node == nil { 1590 return nil 1591 } 1592 return Walk( 1593 visit, 1594 node.Left, 1595 node.From, 1596 node.To, 1597 ) 1598 } 1599 1600 // IsExpr represents an IS ... or an IS NOT ... expression. 1601 type IsExpr struct { 1602 Operator string 1603 Expr Expr 1604 } 1605 1606 // IsExpr.Operator 1607 const ( 1608 IsNullStr = "is null" 1609 IsNotNullStr = "is not null" 1610 IsTrueStr = "is true" 1611 IsNotTrueStr = "is not true" 1612 IsFalseStr = "is false" 1613 IsNotFalseStr = "is not false" 1614 ) 1615 1616 // Format formats the node. 1617 func (node *IsExpr) Format(buf *TrackedBuffer) { 1618 buf.Myprintf("%v %s", node.Expr, node.Operator) 1619 } 1620 1621 // WalkSubtree walks the nodes of the subtree. 1622 func (node *IsExpr) WalkSubtree(visit Visit) error { 1623 if node == nil { 1624 return nil 1625 } 1626 return Walk( 1627 visit, 1628 node.Expr, 1629 ) 1630 } 1631 1632 // ExistsExpr represents an EXISTS expression. 1633 type ExistsExpr struct { 1634 Subquery *Subquery 1635 } 1636 1637 // Format formats the node. 1638 func (node *ExistsExpr) Format(buf *TrackedBuffer) { 1639 buf.Myprintf("exists %v", node.Subquery) 1640 } 1641 1642 // WalkSubtree walks the nodes of the subtree. 1643 func (node *ExistsExpr) WalkSubtree(visit Visit) error { 1644 if node == nil { 1645 return nil 1646 } 1647 return Walk( 1648 visit, 1649 node.Subquery, 1650 ) 1651 } 1652 1653 // ValType specifies the type for SQLVal. 1654 type ValType int 1655 1656 // These are the possible Valtype values. 1657 // HexNum represents a 0x... value. It cannot 1658 // be treated as a simple value because it can 1659 // be interpreted differently depending on the 1660 // context. 1661 const ( 1662 StrVal = ValType(iota) 1663 IntVal 1664 FloatVal 1665 HexNum 1666 HexVal 1667 ValArg 1668 ) 1669 1670 // SQLVal represents a single value. 1671 type SQLVal struct { 1672 Type ValType 1673 Val []byte 1674 Seq int 1675 } 1676 1677 // NewStrVal builds a new StrVal. 1678 func NewStrVal(in []byte) *SQLVal { 1679 return &SQLVal{Type: StrVal, Val: in} 1680 } 1681 1682 // NewIntVal builds a new IntVal. 1683 func NewIntVal(in []byte) *SQLVal { 1684 return &SQLVal{Type: IntVal, Val: in} 1685 } 1686 1687 // NewFloatVal builds a new FloatVal. 1688 func NewFloatVal(in []byte) *SQLVal { 1689 return &SQLVal{Type: FloatVal, Val: in} 1690 } 1691 1692 // NewHexNum builds a new HexNum. 1693 func NewHexNum(in []byte) *SQLVal { 1694 return &SQLVal{Type: HexNum, Val: in} 1695 } 1696 1697 // NewHexVal builds a new HexVal. 1698 func NewHexVal(in []byte) *SQLVal { 1699 return &SQLVal{Type: HexVal, Val: in} 1700 } 1701 1702 // NewValArg builds a new ValArg. 1703 func NewValArg(in []byte) *SQLVal { 1704 return &SQLVal{Type: ValArg, Val: in} 1705 } 1706 1707 // Format formats the node. 1708 func (node *SQLVal) Format(buf *TrackedBuffer) { 1709 switch node.Type { 1710 case StrVal: 1711 s := sqltypes.MakeString(node.Val) 1712 s.EncodeSQL(buf) 1713 case IntVal, FloatVal, HexNum: 1714 buf.Myprintf("%s", node.Val) 1715 case HexVal: 1716 buf.Myprintf("X'%s'", node.Val) 1717 case ValArg: 1718 if buf.PlaceholderFormatter == nil { 1719 buf.WriteArg(string(node.Val)) 1720 } else { 1721 buf.WriteArg(buf.PlaceholderFormatter.FormatPlaceholder()) 1722 } 1723 default: 1724 panic("unexpected") 1725 } 1726 } 1727 1728 // WalkSubtree walks the nodes of the subtree. 1729 func (node *SQLVal) WalkSubtree(visit Visit) error { 1730 return nil 1731 } 1732 1733 // HexDecode decodes the hexval into bytes. 1734 func (node *SQLVal) HexDecode() ([]byte, error) { 1735 dst := make([]byte, hex.DecodedLen(len([]byte(node.Val)))) 1736 _, err := hex.Decode(dst, []byte(node.Val)) 1737 if err != nil { 1738 return nil, err 1739 } 1740 return dst, err 1741 } 1742 1743 // NullVal represents a NULL value. 1744 type NullVal struct{} 1745 1746 // Format formats the node. 1747 func (node *NullVal) Format(buf *TrackedBuffer) { 1748 buf.Myprintf("null") 1749 } 1750 1751 // WalkSubtree walks the nodes of the subtree. 1752 func (node *NullVal) WalkSubtree(visit Visit) error { 1753 return nil 1754 } 1755 1756 // BoolVal is true or false. 1757 type BoolVal bool 1758 1759 // Format formats the node. 1760 func (node BoolVal) Format(buf *TrackedBuffer) { 1761 if node { 1762 buf.Myprintf("true") 1763 } else { 1764 buf.Myprintf("false") 1765 } 1766 } 1767 1768 // WalkSubtree walks the nodes of the subtree. 1769 func (node BoolVal) WalkSubtree(visit Visit) error { 1770 return nil 1771 } 1772 1773 // ColName represents a column name. 1774 type ColName struct { 1775 // Metadata is not populated by the parser. 1776 // It's a placeholder for analyzers to store 1777 // additional data, typically info about which 1778 // table or column this node references. 1779 Metadata interface{} 1780 Name ColIdent 1781 Qualifier TableName 1782 } 1783 1784 // Format formats the node. 1785 func (node *ColName) Format(buf *TrackedBuffer) { 1786 if !node.Qualifier.IsEmpty() { 1787 buf.Myprintf("%v.", node.Qualifier) 1788 } 1789 buf.Myprintf("%v", node.Name) 1790 } 1791 1792 // WalkSubtree walks the nodes of the subtree. 1793 func (node *ColName) WalkSubtree(visit Visit) error { 1794 if node == nil { 1795 return nil 1796 } 1797 return Walk( 1798 visit, 1799 node.Name, 1800 node.Qualifier, 1801 ) 1802 } 1803 1804 // Equal returns true if the column names match. 1805 func (node *ColName) Equal(c *ColName) bool { 1806 // Failsafe: ColName should not be empty. 1807 if node == nil || c == nil { 1808 return false 1809 } 1810 return node.Name.Equal(c.Name) && node.Qualifier == c.Qualifier 1811 } 1812 1813 // ColTuple represents a list of column values. 1814 // It can be ValTuple, Subquery, ListArg. 1815 type ColTuple interface { 1816 iColTuple() 1817 Expr 1818 } 1819 1820 func (ValTuple) iColTuple() {} 1821 func (*Subquery) iColTuple() {} 1822 func (ListArg) iColTuple() {} 1823 1824 // ValTuple represents a tuple of actual values. 1825 type ValTuple Exprs 1826 1827 // Format formats the node. 1828 func (node ValTuple) Format(buf *TrackedBuffer) { 1829 buf.Myprintf("(%v)", Exprs(node)) 1830 } 1831 1832 // WalkSubtree walks the nodes of the subtree. 1833 func (node ValTuple) WalkSubtree(visit Visit) error { 1834 return Walk(visit, Exprs(node)) 1835 } 1836 1837 // Subquery represents a subquery. 1838 type Subquery struct { 1839 Select SelectStatement 1840 } 1841 1842 // Format formats the node. 1843 func (node *Subquery) Format(buf *TrackedBuffer) { 1844 buf.Myprintf("(%v)", node.Select) 1845 } 1846 1847 // WalkSubtree walks the nodes of the subtree. 1848 func (node *Subquery) WalkSubtree(visit Visit) error { 1849 if node == nil { 1850 return nil 1851 } 1852 return Walk( 1853 visit, 1854 node.Select, 1855 ) 1856 } 1857 1858 // ListArg represents a named list argument. 1859 type ListArg []byte 1860 1861 // Format formats the node. 1862 func (node ListArg) Format(buf *TrackedBuffer) { 1863 buf.WriteArg(string(node)) 1864 } 1865 1866 // WalkSubtree walks the nodes of the subtree. 1867 func (node ListArg) WalkSubtree(visit Visit) error { 1868 return nil 1869 } 1870 1871 // BinaryExpr represents a binary value expression. 1872 type BinaryExpr struct { 1873 Operator string 1874 Left, Right Expr 1875 } 1876 1877 // BinaryExpr.Operator 1878 const ( 1879 BitAndStr = "&" 1880 BitOrStr = "|" 1881 BitXorStr = "^" 1882 PlusStr = "+" 1883 MinusStr = "-" 1884 MultStr = "*" 1885 DivStr = "/" 1886 IntDivStr = "div" 1887 ModStr = "%" 1888 ShiftLeftStr = "<<" 1889 ShiftRightStr = ">>" 1890 ) 1891 1892 // Format formats the node. 1893 func (node *BinaryExpr) Format(buf *TrackedBuffer) { 1894 buf.Myprintf("%v %s %v", node.Left, node.Operator, node.Right) 1895 } 1896 1897 // WalkSubtree walks the nodes of the subtree. 1898 func (node *BinaryExpr) WalkSubtree(visit Visit) error { 1899 if node == nil { 1900 return nil 1901 } 1902 return Walk( 1903 visit, 1904 node.Left, 1905 node.Right, 1906 ) 1907 } 1908 1909 // UnaryExpr represents a unary value expression. 1910 type UnaryExpr struct { 1911 Operator string 1912 Expr Expr 1913 } 1914 1915 // UnaryExpr.Operator 1916 const ( 1917 UPlusStr = "+" 1918 UMinusStr = "-" 1919 TildaStr = "~" 1920 BangStr = "!" 1921 BinaryStr = "binary " 1922 ) 1923 1924 // Format formats the node. 1925 func (node *UnaryExpr) Format(buf *TrackedBuffer) { 1926 if _, unary := node.Expr.(*UnaryExpr); unary { 1927 buf.Myprintf("%s %v", node.Operator, node.Expr) 1928 return 1929 } 1930 buf.Myprintf("%s%v", node.Operator, node.Expr) 1931 } 1932 1933 // WalkSubtree walks the nodes of the subtree. 1934 func (node *UnaryExpr) WalkSubtree(visit Visit) error { 1935 if node == nil { 1936 return nil 1937 } 1938 return Walk( 1939 visit, 1940 node.Expr, 1941 ) 1942 } 1943 1944 // IntervalExpr represents a date-time INTERVAL expression. 1945 type IntervalExpr struct { 1946 Expr Expr 1947 Unit ColIdent 1948 } 1949 1950 // Format formats the node. 1951 func (node *IntervalExpr) Format(buf *TrackedBuffer) { 1952 buf.Myprintf("interval %v %v", node.Expr, node.Unit) 1953 } 1954 1955 // WalkSubtree walks the nodes of the subtree. 1956 func (node *IntervalExpr) WalkSubtree(visit Visit) error { 1957 if node == nil { 1958 return nil 1959 } 1960 return Walk( 1961 visit, 1962 node.Expr, 1963 node.Unit, 1964 ) 1965 } 1966 1967 // CollateExpr represents dynamic collate operator. 1968 type CollateExpr struct { 1969 Expr Expr 1970 Charset string 1971 } 1972 1973 // Format formats the node. 1974 func (node *CollateExpr) Format(buf *TrackedBuffer) { 1975 buf.Myprintf("%v collate %s", node.Expr, node.Charset) 1976 } 1977 1978 // WalkSubtree walks the nodes of the subtree. 1979 func (node *CollateExpr) WalkSubtree(visit Visit) error { 1980 if node == nil { 1981 return nil 1982 } 1983 return Walk( 1984 visit, 1985 node.Expr, 1986 ) 1987 } 1988 1989 // FuncExpr represents a function call. 1990 type FuncExpr struct { 1991 Qualifier TableIdent 1992 Name ColIdent 1993 Distinct bool 1994 Exprs SelectExprs 1995 } 1996 1997 // Format formats the node. 1998 func (node *FuncExpr) Format(buf *TrackedBuffer) { 1999 var distinct string 2000 if node.Distinct { 2001 distinct = "distinct " 2002 } 2003 if !node.Qualifier.IsEmpty() { 2004 buf.Myprintf("%v.", node.Qualifier) 2005 } 2006 // Function names should not be back-quoted even 2007 // if they match a reserved word. So, print the 2008 // name as is. 2009 buf.Myprintf("%s(%s%v)", node.Name.String(), distinct, node.Exprs) 2010 } 2011 2012 // WalkSubtree walks the nodes of the subtree. 2013 func (node *FuncExpr) WalkSubtree(visit Visit) error { 2014 if node == nil { 2015 return nil 2016 } 2017 return Walk( 2018 visit, 2019 node.Qualifier, 2020 node.Name, 2021 node.Exprs, 2022 ) 2023 } 2024 2025 // Aggregates is a map of all aggregate functions. 2026 var Aggregates = map[string]bool{ 2027 "avg": true, 2028 "bit_and": true, 2029 "bit_or": true, 2030 "bit_xor": true, 2031 "count": true, 2032 "group_concat": true, 2033 "max": true, 2034 "min": true, 2035 "std": true, 2036 "stddev_pop": true, 2037 "stddev_samp": true, 2038 "stddev": true, 2039 "sum": true, 2040 "var_pop": true, 2041 "var_samp": true, 2042 "variance": true, 2043 } 2044 2045 // IsAggregate returns true if the function is an aggregate. 2046 func (node *FuncExpr) IsAggregate() bool { 2047 return Aggregates[node.Name.Lowered()] 2048 } 2049 2050 // GroupConcatExpr represents a call to GROUP_CONCAT 2051 type GroupConcatExpr struct { 2052 Distinct string 2053 Exprs SelectExprs 2054 OrderBy OrderBy 2055 Separator string 2056 } 2057 2058 // Format formats the node 2059 func (node *GroupConcatExpr) Format(buf *TrackedBuffer) { 2060 buf.Myprintf("group_concat(%s%v%v%s)", node.Distinct, node.Exprs, node.OrderBy, node.Separator) 2061 } 2062 2063 // WalkSubtree walks the nodes of the subtree. 2064 func (node *GroupConcatExpr) WalkSubtree(visit Visit) error { 2065 if node == nil { 2066 return nil 2067 } 2068 return Walk( 2069 visit, 2070 node.Exprs, 2071 node.OrderBy, 2072 ) 2073 } 2074 2075 // ValuesFuncExpr represents a function call. 2076 type ValuesFuncExpr struct { 2077 Name ColIdent 2078 Resolved Expr 2079 } 2080 2081 // Format formats the node. 2082 func (node *ValuesFuncExpr) Format(buf *TrackedBuffer) { 2083 // Function names should not be back-quoted even 2084 // if they match a reserved word. So, print the 2085 // name as is. 2086 if node.Resolved != nil { 2087 buf.Myprintf("%v", node.Resolved) 2088 } else { 2089 buf.Myprintf("values(%s)", node.Name.String()) 2090 } 2091 } 2092 2093 // WalkSubtree walks the nodes of the subtree. 2094 func (node *ValuesFuncExpr) WalkSubtree(visit Visit) error { 2095 if node == nil { 2096 return nil 2097 } 2098 return Walk( 2099 visit, 2100 node.Name, 2101 node.Resolved, 2102 ) 2103 } 2104 2105 // ConvertExpr represents a call to CONVERT(expr, type) 2106 // or it's equivalent CAST(expr AS type). Both are rewritten to the former. 2107 type ConvertExpr struct { 2108 Expr Expr 2109 Type *ConvertType 2110 } 2111 2112 // Format formats the node. 2113 func (node *ConvertExpr) Format(buf *TrackedBuffer) { 2114 buf.Myprintf("convert(%v, %v)", node.Expr, node.Type) 2115 } 2116 2117 // WalkSubtree walks the nodes of the subtree. 2118 func (node *ConvertExpr) WalkSubtree(visit Visit) error { 2119 if node == nil { 2120 return nil 2121 } 2122 return Walk( 2123 visit, 2124 node.Expr, 2125 node.Type, 2126 ) 2127 } 2128 2129 // ConvertUsingExpr represents a call to CONVERT(expr USING charset). 2130 type ConvertUsingExpr struct { 2131 Expr Expr 2132 Type string 2133 } 2134 2135 // Format formats the node. 2136 func (node *ConvertUsingExpr) Format(buf *TrackedBuffer) { 2137 buf.Myprintf("convert(%v using %s)", node.Expr, node.Type) 2138 } 2139 2140 // WalkSubtree walks the nodes of the subtree. 2141 func (node *ConvertUsingExpr) WalkSubtree(visit Visit) error { 2142 if node == nil { 2143 return nil 2144 } 2145 return Walk( 2146 visit, 2147 node.Expr, 2148 ) 2149 } 2150 2151 // ConvertType represents the type in call to CONVERT(expr, type) 2152 type ConvertType struct { 2153 Type string 2154 Length *SQLVal 2155 Scale *SQLVal 2156 Operator string 2157 Charset string 2158 } 2159 2160 // this string is "character set" and this comment is required 2161 const ( 2162 CharacterSetStr = " character set" 2163 ) 2164 2165 // Format formats the node. 2166 func (node *ConvertType) Format(buf *TrackedBuffer) { 2167 buf.Myprintf("%s", node.Type) 2168 if node.Length != nil { 2169 buf.Myprintf("(%v", node.Length) 2170 if node.Scale != nil { 2171 buf.Myprintf(", %v", node.Scale) 2172 } 2173 buf.Myprintf(")") 2174 } 2175 if node.Charset != "" { 2176 buf.Myprintf("%s %s", node.Operator, node.Charset) 2177 } 2178 } 2179 2180 // WalkSubtree walks the nodes of the subtree. 2181 func (node *ConvertType) WalkSubtree(visit Visit) error { 2182 return nil 2183 } 2184 2185 // MatchExpr represents a call to the MATCH function 2186 type MatchExpr struct { 2187 Columns SelectExprs 2188 Expr Expr 2189 Option string 2190 } 2191 2192 // MatchExpr.Option 2193 const ( 2194 BooleanModeStr = " in boolean mode" 2195 NaturalLanguageModeStr = " in natural language mode" 2196 NaturalLanguageModeWithQueryExpansionStr = " in natural language mode with query expansion" 2197 QueryExpansionStr = " with query expansion" 2198 ) 2199 2200 // Format formats the node 2201 func (node *MatchExpr) Format(buf *TrackedBuffer) { 2202 buf.Myprintf("match(%v) against (%v%s)", node.Columns, node.Expr, node.Option) 2203 } 2204 2205 // WalkSubtree walks the nodes of the subtree. 2206 func (node *MatchExpr) WalkSubtree(visit Visit) error { 2207 if node == nil { 2208 return nil 2209 } 2210 return Walk( 2211 visit, 2212 node.Columns, 2213 node.Expr, 2214 ) 2215 } 2216 2217 // CaseExpr represents a CASE expression. 2218 type CaseExpr struct { 2219 Expr Expr 2220 Whens []*When 2221 Else Expr 2222 } 2223 2224 // Format formats the node. 2225 func (node *CaseExpr) Format(buf *TrackedBuffer) { 2226 buf.Myprintf("case ") 2227 if node.Expr != nil { 2228 buf.Myprintf("%v ", node.Expr) 2229 } 2230 for _, when := range node.Whens { 2231 buf.Myprintf("%v ", when) 2232 } 2233 if node.Else != nil { 2234 buf.Myprintf("else %v ", node.Else) 2235 } 2236 buf.Myprintf("end") 2237 } 2238 2239 // WalkSubtree walks the nodes of the subtree. 2240 func (node *CaseExpr) WalkSubtree(visit Visit) error { 2241 if node == nil { 2242 return nil 2243 } 2244 if err := Walk(visit, node.Expr); err != nil { 2245 return err 2246 } 2247 for _, n := range node.Whens { 2248 if err := Walk(visit, n); err != nil { 2249 return err 2250 } 2251 } 2252 if err := Walk(visit, node.Else); err != nil { 2253 return err 2254 } 2255 return nil 2256 } 2257 2258 // Default represents a DEFAULT expression. 2259 type Default struct{} 2260 2261 // Format formats the node. 2262 func (node *Default) Format(buf *TrackedBuffer) { 2263 buf.Myprintf("default") 2264 } 2265 2266 // WalkSubtree walks the nodes of the subtree. 2267 func (node *Default) WalkSubtree(visit Visit) error { 2268 return nil 2269 } 2270 2271 // When represents a WHEN sub-expression. 2272 type When struct { 2273 Cond Expr 2274 Val Expr 2275 } 2276 2277 // Format formats the node. 2278 func (node *When) Format(buf *TrackedBuffer) { 2279 buf.Myprintf("when %v then %v", node.Cond, node.Val) 2280 } 2281 2282 // WalkSubtree walks the nodes of the subtree. 2283 func (node *When) WalkSubtree(visit Visit) error { 2284 if node == nil { 2285 return nil 2286 } 2287 return Walk( 2288 visit, 2289 node.Cond, 2290 node.Val, 2291 ) 2292 } 2293 2294 // GroupBy represents a GROUP BY clause. 2295 type GroupBy []Expr 2296 2297 // Format formats the node. 2298 func (node GroupBy) Format(buf *TrackedBuffer) { 2299 prefix := " group by " 2300 for _, n := range node { 2301 buf.Myprintf("%s%v", prefix, n) 2302 prefix = ", " 2303 } 2304 } 2305 2306 // WalkSubtree walks the nodes of the subtree. 2307 func (node GroupBy) WalkSubtree(visit Visit) error { 2308 for _, n := range node { 2309 if err := Walk(visit, n); err != nil { 2310 return err 2311 } 2312 } 2313 return nil 2314 } 2315 2316 // OrderBy represents an ORDER By clause. 2317 type OrderBy []*Order 2318 2319 // Format formats the node. 2320 func (node OrderBy) Format(buf *TrackedBuffer) { 2321 prefix := " order by " 2322 for _, n := range node { 2323 buf.Myprintf("%s%v", prefix, n) 2324 prefix = ", " 2325 } 2326 } 2327 2328 // WalkSubtree walks the nodes of the subtree. 2329 func (node OrderBy) WalkSubtree(visit Visit) error { 2330 for _, n := range node { 2331 if err := Walk(visit, n); err != nil { 2332 return err 2333 } 2334 } 2335 return nil 2336 } 2337 2338 // Order represents an ordering expression. 2339 type Order struct { 2340 Expr Expr 2341 Direction string 2342 } 2343 2344 // Order.Direction 2345 const ( 2346 AscScr = "asc" 2347 DescScr = "desc" 2348 ) 2349 2350 // Format formats the node. 2351 func (node *Order) Format(buf *TrackedBuffer) { 2352 if node, ok := node.Expr.(*NullVal); ok { 2353 buf.Myprintf("%v", node) 2354 return 2355 } 2356 2357 if node.Direction == AscScr { 2358 buf.Myprintf("%v", node.Expr) 2359 } else { 2360 buf.Myprintf("%v %s", node.Expr, node.Direction) 2361 } 2362 } 2363 2364 // WalkSubtree walks the nodes of the subtree. 2365 func (node *Order) WalkSubtree(visit Visit) error { 2366 if node == nil { 2367 return nil 2368 } 2369 return Walk( 2370 visit, 2371 node.Expr, 2372 ) 2373 } 2374 2375 // Limit represents a LIMIT clause. 2376 type Limit struct { 2377 Offset, Rowcount Expr 2378 } 2379 2380 // Format formats the node. 2381 func (node *Limit) Format(buf *TrackedBuffer) { 2382 if node == nil { 2383 return 2384 } 2385 buf.Myprintf(" limit ") 2386 if node.Offset != nil { 2387 buf.Myprintf("%v, ", node.Offset) 2388 } 2389 buf.Myprintf("%v", node.Rowcount) 2390 } 2391 2392 // WalkSubtree walks the nodes of the subtree. 2393 func (node *Limit) WalkSubtree(visit Visit) error { 2394 if node == nil { 2395 return nil 2396 } 2397 return Walk( 2398 visit, 2399 node.Offset, 2400 node.Rowcount, 2401 ) 2402 } 2403 2404 // Values represents a VALUES clause. 2405 type Values []ValTuple 2406 2407 // Format formats the node. 2408 func (node Values) Format(buf *TrackedBuffer) { 2409 prefix := "values " 2410 for _, n := range node { 2411 buf.Myprintf("%s%v", prefix, n) 2412 prefix = ", " 2413 } 2414 } 2415 2416 // WalkSubtree walks the nodes of the subtree. 2417 func (node Values) WalkSubtree(visit Visit) error { 2418 for _, n := range node { 2419 if err := Walk(visit, n); err != nil { 2420 return err 2421 } 2422 } 2423 return nil 2424 } 2425 2426 // UpdateExprs represents a list of update expressions. 2427 type UpdateExprs []*UpdateExpr 2428 2429 // Format formats the node. 2430 func (node UpdateExprs) Format(buf *TrackedBuffer) { 2431 var prefix string 2432 for _, n := range node { 2433 buf.Myprintf("%s%v", prefix, n) 2434 prefix = ", " 2435 } 2436 } 2437 2438 // WalkSubtree walks the nodes of the subtree. 2439 func (node UpdateExprs) WalkSubtree(visit Visit) error { 2440 for _, n := range node { 2441 if err := Walk(visit, n); err != nil { 2442 return err 2443 } 2444 } 2445 return nil 2446 } 2447 2448 // UpdateExpr represents an update expression. 2449 type UpdateExpr struct { 2450 Name *ColName 2451 Expr Expr 2452 } 2453 2454 // Format formats the node. 2455 func (node *UpdateExpr) Format(buf *TrackedBuffer) { 2456 buf.Myprintf("%v = %v", node.Name, node.Expr) 2457 } 2458 2459 // WalkSubtree walks the nodes of the subtree. 2460 func (node *UpdateExpr) WalkSubtree(visit Visit) error { 2461 if node == nil { 2462 return nil 2463 } 2464 return Walk( 2465 visit, 2466 node.Name, 2467 node.Expr, 2468 ) 2469 } 2470 2471 // OnDup represents an ON DUPLICATE KEY clause. 2472 type OnDup UpdateExprs 2473 2474 // Format formats the node. 2475 func (node OnDup) Format(buf *TrackedBuffer) { 2476 if node == nil { 2477 return 2478 } 2479 buf.Myprintf(" on duplicate key update %v", UpdateExprs(node)) 2480 } 2481 2482 // WalkSubtree walks the nodes of the subtree. 2483 func (node OnDup) WalkSubtree(visit Visit) error { 2484 return Walk(visit, UpdateExprs(node)) 2485 } 2486 2487 // ColIdent is a case insensitive SQL identifier. It will be escaped with 2488 // backquotes if necessary. 2489 type ColIdent struct { 2490 // This artifact prevents this struct from being compared 2491 // with itself. It consumes no space as long as it's not the 2492 // last field in the struct. 2493 _ [0]struct{ _ []byte } 2494 val, lowered string 2495 } 2496 2497 // NewColIdent makes a new ColIdent. 2498 func NewColIdent(str string) ColIdent { 2499 return ColIdent{ 2500 val: str, 2501 } 2502 } 2503 2504 // Format formats the node. 2505 func (node ColIdent) Format(buf *TrackedBuffer) { 2506 formatID(buf, node.val, node.Lowered()) 2507 } 2508 2509 // WalkSubtree walks the nodes of the subtree. 2510 func (node ColIdent) WalkSubtree(visit Visit) error { 2511 return nil 2512 } 2513 2514 // IsEmpty returns true if the name is empty. 2515 func (node ColIdent) IsEmpty() bool { 2516 return node.val == "" 2517 } 2518 2519 // String returns the unescaped column name. It must 2520 // not be used for SQL generation. Use sqlparser.String 2521 // instead. The Stringer conformance is for usage 2522 // in templates. 2523 func (node ColIdent) String() string { 2524 return node.val 2525 } 2526 2527 // CompliantName returns a compliant id name 2528 // that can be used for a bind var. 2529 func (node ColIdent) CompliantName() string { 2530 return compliantName(node.val) 2531 } 2532 2533 // Lowered returns a lower-cased column name. 2534 // This function should generally be used only for optimizing 2535 // comparisons. 2536 func (node ColIdent) Lowered() string { 2537 if node.val == "" { 2538 return "" 2539 } 2540 if node.lowered == "" { 2541 node.lowered = strings.ToLower(node.val) 2542 } 2543 return node.lowered 2544 } 2545 2546 // Equal performs a case-insensitive compare. 2547 func (node ColIdent) Equal(in ColIdent) bool { 2548 return node.Lowered() == in.Lowered() 2549 } 2550 2551 // EqualString performs a case-insensitive compare with str. 2552 func (node ColIdent) EqualString(str string) bool { 2553 return node.Lowered() == strings.ToLower(str) 2554 } 2555 2556 // MarshalJSON marshals into JSON. 2557 func (node ColIdent) MarshalJSON() ([]byte, error) { 2558 return json.Marshal(node.val) 2559 } 2560 2561 // UnmarshalJSON unmarshals from JSON. 2562 func (node *ColIdent) UnmarshalJSON(b []byte) error { 2563 var result string 2564 err := json.Unmarshal(b, &result) 2565 if err != nil { 2566 return err 2567 } 2568 node.val = result 2569 return nil 2570 } 2571 2572 // TableIdent is a case sensitive SQL identifier. It will be escaped with 2573 // backquotes if necessary. 2574 type TableIdent struct { 2575 v string 2576 } 2577 2578 // NewTableIdent creates a new TableIdent. 2579 func NewTableIdent(str string) TableIdent { 2580 return TableIdent{v: str} 2581 } 2582 2583 // Format formats the node. 2584 func (node TableIdent) Format(buf *TrackedBuffer) { 2585 formatID(buf, node.v, strings.ToLower(node.v)) 2586 } 2587 2588 // WalkSubtree walks the nodes of the subtree. 2589 func (node TableIdent) WalkSubtree(visit Visit) error { 2590 return nil 2591 } 2592 2593 // IsEmpty returns true if TabIdent is empty. 2594 func (node TableIdent) IsEmpty() bool { 2595 return node.v == "" 2596 } 2597 2598 // String returns the unescaped table name. It must 2599 // not be used for SQL generation. Use sqlparser.String 2600 // instead. The Stringer conformance is for usage 2601 // in templates. 2602 func (node TableIdent) String() string { 2603 return node.v 2604 } 2605 2606 // CompliantName returns a compliant id name 2607 // that can be used for a bind var. 2608 func (node TableIdent) CompliantName() string { 2609 return compliantName(node.v) 2610 } 2611 2612 // MarshalJSON marshals into JSON. 2613 func (node TableIdent) MarshalJSON() ([]byte, error) { 2614 return json.Marshal(node.v) 2615 } 2616 2617 // UnmarshalJSON unmarshals from JSON. 2618 func (node *TableIdent) UnmarshalJSON(b []byte) error { 2619 var result string 2620 err := json.Unmarshal(b, &result) 2621 if err != nil { 2622 return err 2623 } 2624 node.v = result 2625 return nil 2626 } 2627 2628 // Backtick produces a backticked literal given an input string. 2629 func Backtick(in string) string { 2630 var buf bytes.Buffer 2631 buf.WriteByte('`') 2632 for _, c := range in { 2633 buf.WriteRune(c) 2634 if c == '`' { 2635 buf.WriteByte('`') 2636 } 2637 } 2638 buf.WriteByte('`') 2639 return buf.String() 2640 } 2641 2642 func formatID(buf *TrackedBuffer, original, lowered string) { 2643 if !shouldQuote(original) { 2644 buf.Myprintf("%s", original) 2645 return 2646 } 2647 2648 if buf.IdQuoter != nil { 2649 buf.Myprintf("%s", buf.IdQuoter.Quote(original)) 2650 return 2651 } 2652 2653 buf.Myprintf("%s", original) 2654 return 2655 } 2656 2657 func shouldQuote(s string) bool { 2658 isLetter := func(c rune) bool { return 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' } 2659 isDigit := func(c rune) bool { return '0' <= c && c <= '9' } 2660 for i, c := range s { 2661 if i == 0 { 2662 if !isLetter(c) { 2663 return true 2664 } 2665 continue 2666 } 2667 if !isLetter(c) && !isDigit(c) { 2668 return false 2669 } 2670 } 2671 2672 return true 2673 } 2674 2675 func formatID2(buf *TrackedBuffer, original, lowered string) { 2676 for i, c := range original { 2677 if !isLetter(uint16(c)) { 2678 if i == 0 || !isDigit(uint16(c)) { 2679 goto mustEscape 2680 } 2681 } 2682 } 2683 if _, ok := keywords[lowered]; ok { 2684 goto mustEscape 2685 } 2686 buf.Myprintf("%s", original) 2687 return 2688 2689 mustEscape: 2690 buf.WriteByte('`') 2691 for _, c := range original { 2692 buf.WriteRune(c) 2693 if c == '`' { 2694 buf.WriteByte('`') 2695 } 2696 } 2697 buf.WriteByte('`') 2698 } 2699 2700 func compliantName(in string) string { 2701 var buf bytes.Buffer 2702 for i, c := range in { 2703 if !isLetter(uint16(c)) { 2704 if i == 0 || !isDigit(uint16(c)) { 2705 buf.WriteByte('_') 2706 continue 2707 } 2708 } 2709 buf.WriteRune(c) 2710 } 2711 return buf.String() 2712 }