forked from xwb1989/sqlparser
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsql.y
8654 lines (8175 loc) · 182 KB
/
sql.y
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2019 The Vitess Authors.
Licensed under the Apache License, Version 2.0 (the "License");
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
%{
package sqlparser
import "vitess.io/vitess/go/ptr"
func setParseTree(yylex yyLexer, stmt Statement) {
yylex.(*Tokenizer).ParseTree = stmt
}
func setAllowComments(yylex yyLexer, allow bool) {
yylex.(*Tokenizer).AllowComments = allow
}
func setDDL(yylex yyLexer, node Statement) {
yylex.(*Tokenizer).partialDDL = node
}
// skipToEnd forces the lexer to end prematurely. Not all SQL statements
// are supported by the Parser, thus calling skipToEnd will make the lexer
// return EOF early.
func skipToEnd(yylex yyLexer) {
yylex.(*Tokenizer).SkipToEnd = true
}
func markBindVariable(yylex yyLexer, bvar string) {
yylex.(*Tokenizer).BindVars[bvar] = struct{}{}
}
%}
%struct {
empty struct{}
LengthScaleOption LengthScaleOption
tableName TableName
identifierCS IdentifierCS
str string
strs []string
vindexParam VindexParam
jsonObjectParam *JSONObjectParam
identifierCI IdentifierCI
joinCondition *JoinCondition
databaseOption DatabaseOption
columnType *ColumnType
columnCharset ColumnCharset
}
%union {
statement Statement
selStmt SelectStatement
tableExpr TableExpr
expr Expr
colTuple ColTuple
optVal Expr
constraintInfo ConstraintInfo
alterOption AlterOption
ins *Insert
colName *ColName
colNames []*ColName
indexHint *IndexHint
indexHints IndexHints
indexHintForType IndexHintForType
literal *Literal
subquery *Subquery
derivedTable *DerivedTable
when *When
with *With
cte *CommonTableExpr
ctes []*CommonTableExpr
order *Order
limit *Limit
rowAlias *RowAlias
updateExpr *UpdateExpr
setExpr *SetExpr
convertType *ConvertType
aliasedTableName *AliasedTableExpr
tableSpec *TableSpec
columnDefinition *ColumnDefinition
indexDefinition *IndexDefinition
indexInfo *IndexInfo
indexOption *IndexOption
indexColumn *IndexColumn
partDef *PartitionDefinition
partSpec *PartitionSpec
showFilter *ShowFilter
optLike *OptLike
selectInto *SelectInto
createDatabase *CreateDatabase
alterDatabase *AlterDatabase
createTable *CreateTable
tableAndLockType *TableAndLockType
alterTable *AlterTable
tableOption *TableOption
columnTypeOptions *ColumnTypeOptions
partitionDefinitionOptions *PartitionDefinitionOptions
subPartitionDefinition *SubPartitionDefinition
subPartitionDefinitions SubPartitionDefinitions
subPartitionDefinitionOptions *SubPartitionDefinitionOptions
constraintDefinition *ConstraintDefinition
revertMigration *RevertMigration
alterMigration *AlterMigration
trimType TrimType
frameClause *FrameClause
framePoint *FramePoint
frameUnitType FrameUnitType
framePointType FramePointType
argumentLessWindowExprType ArgumentLessWindowExprType
windowSpecification *WindowSpecification
overClause *OverClause
nullTreatmentClause *NullTreatmentClause
nullTreatmentType NullTreatmentType
firstOrLastValueExprType FirstOrLastValueExprType
fromFirstLastType FromFirstLastType
fromFirstLastClause *FromFirstLastClause
lagLeadExprType LagLeadExprType
windowDefinition *WindowDefinition
windowDefinitions WindowDefinitions
namedWindow *NamedWindow
namedWindows NamedWindows
whens []*When
columnDefinitions []*ColumnDefinition
indexOptions []*IndexOption
indexColumns []*IndexColumn
databaseOptions []DatabaseOption
tableAndLockTypes TableAndLockTypes
renameTablePairs []*RenameTablePair
alterOptions []AlterOption
vindexParams []VindexParam
jsonObjectParams []*JSONObjectParam
partDefs []*PartitionDefinition
partitionValueRange *PartitionValueRange
partitionEngine *PartitionEngine
partSpecs []*PartitionSpec
selectExpr SelectExpr
columns Columns
partitions Partitions
tableExprs TableExprs
tableNames TableNames
exprs Exprs
values Values
valTuple ValTuple
orderBy OrderBy
updateExprs UpdateExprs
setExprs SetExprs
selectExprs SelectExprs
tableOptions TableOptions
starExpr StarExpr
groupBy *GroupBy
colKeyOpt ColumnKeyOption
referenceAction ReferenceAction
matchAction MatchAction
insertAction InsertAction
scope Scope
lock Lock
joinType JoinType
comparisonExprOperator ComparisonExprOperator
isExprOperator IsExprOperator
matchExprOption MatchExprOption
orderDirection OrderDirection
explainType ExplainType
vexplainType VExplainType
intervalType IntervalType
lockType LockType
referenceDefinition *ReferenceDefinition
txAccessModes []TxAccessMode
txAccessMode TxAccessMode
killType KillType
columnStorage ColumnStorage
columnFormat ColumnFormat
boolean bool
boolVal BoolVal
ignore Ignore
partitionOption *PartitionOption
subPartition *SubPartition
partitionByType PartitionByType
definer *Definer
integer int
intPtr *int
JSONTableExpr *JSONTableExpr
jtColumnDefinition *JtColumnDefinition
jtColumnList []*JtColumnDefinition
jtOnResponse *JtOnResponse
variables []*Variable
variable *Variable
}
// These precedence rules are there to handle shift-reduce conflicts.
%nonassoc <str> MEMBER
// MULTIPLE_TEXT_LITERAL is used to resolve shift-reduce conflicts occuring due to multiple STRING symbols occuring one after the other.
// According to the ANSI standard, these strings should be concatenated together.
// The shift-reduce conflict occurrs because after seeing a STRING, if we see another one, then we can either shift to concatenate them or
// reduce the STRING into a text_literal, eventually into a simple_expr and use the coming string as an alias.
// The way to fix this conflict is to give shifting higher precedence than reducing.
// Adding no precedence also works, since shifting is the default, but it reports a conflict which we can avoid by adding this precedence rule.
// In order to ensure lower precedence of reduction, this rule has to come before the precedence declaration of STRING.
// This precedence should not be used anywhere else other than with rules where text_literal is being reduced.
%nonassoc <str> MULTIPLE_TEXT_LITERAL
// FUNCTION_CALL_NON_KEYWORD is used to resolve shift-reduce conflicts occuring due to function_call_generic symbol and
// having special parsing for functions whose names are non-reserved keywords. The shift-reduce conflict occurrs because
// after seeing a non-reserved keyword, if we see '(', then we can either shift to use the special parsing grammar rule or
// reduce the non-reserved keyword into sql_id and eventually use a rule from function_call_generic.
// The way to fix this conflict is to give shifting higher precedence than reducing.
// Adding no precedence also works, since shifting is the default, but it reports a large number of conflicts
// Shifting on '(' already has an assigned precedence.
// All we need to add is a lower precedence to reducing the grammar symbol to non-reserved keywords.
// In order to ensure lower precedence of reduction, this rule has to come before the precedence declaration of '('.
// This precedence should not be used anywhere else other than with function names that are non-reserved-keywords.
%nonassoc <str> FUNCTION_CALL_NON_KEYWORD
// STRING_TYPE_PREFIX_NON_KEYWORD is used to resolve shift-reduce conflicts occuring due to column_name symbol and
// being able to use keywords like DATE and TIME as prefixes to strings to denote their type. The shift-reduce conflict occurrs because
// after seeing one of these non-reserved keywords, if we see a STRING, then we can either shift to use the STRING typed rule in literal or
// reduce the non-reserved keyword into column_name and eventually use a rule from simple_expr.
// The way to fix this conflict is to give shifting higher precedence than reducing.
// Adding no precedence also works, since shifting is the default, but it reports some conflicts
// Precedence is also assined to shifting on STRING.
// We also need to add a lower precedence to reducing the grammar symbol to non-reserved keywords.
// In order to ensure lower precedence of reduction, this rule has to come before the precedence declaration of STRING.
// This precedence should not be used anywhere else other than with non-reserved-keywords that are also used for type-casting a STRING.
%nonassoc <str> STRING_TYPE_PREFIX_NON_KEYWORD
%token LEX_ERROR
%left <str> UNION
%token <str> SELECT STREAM VSTREAM INSERT UPDATE DELETE FROM WHERE GROUP HAVING ORDER BY LIMIT OFFSET FOR
%token <str> ALL DISTINCT AS EXISTS ASC DESC INTO DUPLICATE DEFAULT SET LOCK UNLOCK KEYS DO CALL
%token <str> DISTINCTROW PARSER GENERATED ALWAYS
%token <str> OUTFILE S3 DATA LOAD LINES TERMINATED ESCAPED ENCLOSED
%token <str> DUMPFILE CSV HEADER MANIFEST OVERWRITE STARTING OPTIONALLY
%token <str> VALUES LAST_INSERT_ID
%token <str> NEXT VALUE SHARE MODE
%token <str> SQL_NO_CACHE SQL_CACHE SQL_CALC_FOUND_ROWS
%left <str> JOIN STRAIGHT_JOIN LEFT RIGHT INNER OUTER CROSS NATURAL USE FORCE
%left <str> ON USING INPLACE COPY INSTANT ALGORITHM NONE SHARED EXCLUSIVE
%left <str> SUBQUERY_AS_EXPR
%left <str> '(' ',' ')'
%nonassoc <str> STRING
%token <str> ID AT_ID AT_AT_ID HEX NCHAR_STRING INTEGRAL FLOAT DECIMAL HEXNUM COMMENT COMMENT_KEYWORD BITNUM BIT_LITERAL COMPRESSION
%token <str> VALUE_ARG LIST_ARG OFFSET_ARG
%token <str> JSON_PRETTY JSON_STORAGE_SIZE JSON_STORAGE_FREE JSON_CONTAINS JSON_CONTAINS_PATH JSON_EXTRACT JSON_KEYS JSON_OVERLAPS JSON_SEARCH JSON_VALUE
%token <str> EXTRACT
%token <str> NULL UNKNOWN TRUE FALSE OFF
%token <str> DISCARD IMPORT ENABLE DISABLE TABLESPACE
%token <str> VIRTUAL STORED
%token <str> BOTH LEADING TRAILING
%token <str> KILL
%left EMPTY_FROM_CLAUSE
%right INTO
// Precedence dictated by mysql. But the vitess grammar is simplified.
// Some of these operators don't conflict in our situation. Nevertheless,
// it's better to have these listed in the correct order. Also, we don't
// support all operators yet.
// * NOTE: If you change anything here, update precedence.go as well *
%nonassoc <str> LOWER_THAN_CHARSET
%nonassoc <str> CHARSET
// Resolve column attribute ambiguity.
%right <str> UNIQUE KEY
%left <str> EXPRESSION_PREC_SETTER
%left <str> OR '|'
%left <str> XOR
%left <str> AND
%right <str> NOT '!'
%left <str> BETWEEN CASE WHEN THEN ELSE END
%left <str> '=' '<' '>' LE GE NE NULL_SAFE_EQUAL IS LIKE REGEXP RLIKE IN ASSIGNMENT_OPT
%left <str> '&'
%left <str> SHIFT_LEFT SHIFT_RIGHT
%left <str> '+' '-'
%left <str> '*' '/' DIV '%' MOD
%left <str> '^'
%right <str> '~' UNARY
%left <str> COLLATE
%right <str> BINARY UNDERSCORE_ARMSCII8 UNDERSCORE_ASCII UNDERSCORE_BIG5 UNDERSCORE_BINARY UNDERSCORE_CP1250 UNDERSCORE_CP1251
%right <str> UNDERSCORE_CP1256 UNDERSCORE_CP1257 UNDERSCORE_CP850 UNDERSCORE_CP852 UNDERSCORE_CP866 UNDERSCORE_CP932
%right <str> UNDERSCORE_DEC8 UNDERSCORE_EUCJPMS UNDERSCORE_EUCKR UNDERSCORE_GB18030 UNDERSCORE_GB2312 UNDERSCORE_GBK UNDERSCORE_GEOSTD8
%right <str> UNDERSCORE_GREEK UNDERSCORE_HEBREW UNDERSCORE_HP8 UNDERSCORE_KEYBCS2 UNDERSCORE_KOI8R UNDERSCORE_KOI8U UNDERSCORE_LATIN1 UNDERSCORE_LATIN2 UNDERSCORE_LATIN5
%right <str> UNDERSCORE_LATIN7 UNDERSCORE_MACCE UNDERSCORE_MACROMAN UNDERSCORE_SJIS UNDERSCORE_SWE7 UNDERSCORE_TIS620 UNDERSCORE_UCS2 UNDERSCORE_UJIS UNDERSCORE_UTF16
%right <str> UNDERSCORE_UTF16LE UNDERSCORE_UTF32 UNDERSCORE_UTF8 UNDERSCORE_UTF8MB4 UNDERSCORE_UTF8MB3
%right <str> INTERVAL
%nonassoc <str> '.'
%left <str> WINDOW_EXPR
// There is no need to define precedence for the JSON
// operators because the syntax is restricted enough that
// they don't cause conflicts.
%token <empty> JSON_EXTRACT_OP JSON_UNQUOTE_EXTRACT_OP
// DDL Tokens
%token <str> CREATE ALTER DROP RENAME ANALYZE ADD FLUSH CHANGE MODIFY DEALLOCATE
%token <str> REVERT QUERIES
%token <str> SCHEMA TABLE INDEX VIEW TO IGNORE IF PRIMARY COLUMN SPATIAL FULLTEXT KEY_BLOCK_SIZE CHECK INDEXES
%token <str> ACTION CASCADE CONSTRAINT FOREIGN NO REFERENCES RESTRICT
%token <str> SHOW DESCRIBE EXPLAIN DATE ESCAPE REPAIR OPTIMIZE TRUNCATE COALESCE EXCHANGE REBUILD PARTITIONING REMOVE PREPARE EXECUTE
%token <str> MAXVALUE PARTITION REORGANIZE LESS THAN PROCEDURE TRIGGER
%token <str> VINDEX VINDEXES DIRECTORY NAME UPGRADE
%token <str> STATUS VARIABLES WARNINGS CASCADED DEFINER OPTION SQL UNDEFINED
%token <str> SEQUENCE MERGE TEMPORARY TEMPTABLE INVOKER SECURITY FIRST AFTER LAST
// Migration tokens
%token <str> VITESS_MIGRATION CANCEL RETRY LAUNCH COMPLETE CLEANUP THROTTLE UNTHROTTLE FORCE_CUTOVER EXPIRE RATIO
// Throttler tokens
%token <str> VITESS_THROTTLER
// Transaction Tokens
%token <str> BEGIN START TRANSACTION COMMIT ROLLBACK SAVEPOINT RELEASE WORK
%token <str> CONSISTENT SNAPSHOT
// Type Tokens
%token <str> BIT TINYINT SMALLINT MEDIUMINT INT INTEGER BIGINT INTNUM
%token <str> REAL DOUBLE FLOAT_TYPE FLOAT4_TYPE FLOAT8_TYPE DECIMAL_TYPE NUMERIC
%token <str> TIME TIMESTAMP DATETIME YEAR
%token <str> CHAR VARCHAR BOOL CHARACTER VARBINARY NCHAR
%token <str> TEXT TINYTEXT MEDIUMTEXT LONGTEXT
%token <str> BLOB TINYBLOB MEDIUMBLOB LONGBLOB JSON JSON_SCHEMA_VALID JSON_SCHEMA_VALIDATION_REPORT ENUM
%token <str> GEOMETRY POINT LINESTRING POLYGON GEOMCOLLECTION GEOMETRYCOLLECTION MULTIPOINT MULTILINESTRING MULTIPOLYGON
%token <str> ASCII UNICODE // used in CONVERT/CAST types
// Type Modifiers
%token <str> NULLX AUTO_INCREMENT APPROXNUM SIGNED UNSIGNED ZEROFILL
// PURGE tokens
%token <str> PURGE BEFORE
// SHOW tokens
%token <str> CODE COLLATION COLUMNS DATABASES ENGINES EVENT EXTENDED FIELDS FULL FUNCTION GTID_EXECUTED
%token <str> KEYSPACES OPEN PLUGINS PRIVILEGES PROCESSLIST SCHEMAS TABLES TRIGGERS USER
%token <str> VGTID_EXECUTED VITESS_KEYSPACES VITESS_METADATA VITESS_MIGRATIONS VITESS_REPLICATION_STATUS VITESS_SHARDS VITESS_TABLETS VITESS_TARGET VSCHEMA VITESS_THROTTLED_APPS
// SET tokens
%token <str> NAMES GLOBAL SESSION ISOLATION LEVEL READ WRITE ONLY REPEATABLE COMMITTED UNCOMMITTED SERIALIZABLE
// Functions
%token <str> ADDDATE CURRENT_TIMESTAMP DATABASE CURRENT_DATE CURDATE DATE_ADD DATE_SUB NOW SUBDATE
%token <str> CURTIME CURRENT_TIME LOCALTIME LOCALTIMESTAMP CURRENT_USER
%token <str> UTC_DATE UTC_TIME UTC_TIMESTAMP SYSDATE
%token <str> DAY DAY_HOUR DAY_MICROSECOND DAY_MINUTE DAY_SECOND HOUR HOUR_MICROSECOND HOUR_MINUTE HOUR_SECOND MICROSECOND MINUTE MINUTE_MICROSECOND MINUTE_SECOND MONTH QUARTER SECOND SECOND_MICROSECOND YEAR_MONTH WEEK
%token <str> SQL_TSI_DAY SQL_TSI_WEEK SQL_TSI_HOUR SQL_TSI_MINUTE SQL_TSI_MONTH SQL_TSI_QUARTER SQL_TSI_SECOND SQL_TSI_MICROSECOND SQL_TSI_YEAR
%token <str> REPLACE
%token <str> CONVERT CAST
%token <str> SUBSTR SUBSTRING MID
%token <str> SEPARATOR
%token <str> TIMESTAMPADD TIMESTAMPDIFF
%token <str> WEIGHT_STRING
%token <str> LTRIM RTRIM TRIM
%token <str> JSON_ARRAY JSON_OBJECT JSON_QUOTE
%token <str> JSON_DEPTH JSON_TYPE JSON_LENGTH JSON_VALID
%token <str> JSON_ARRAY_APPEND JSON_ARRAY_INSERT JSON_INSERT JSON_MERGE JSON_MERGE_PATCH JSON_MERGE_PRESERVE JSON_REMOVE JSON_REPLACE JSON_SET JSON_UNQUOTE
%token <str> COUNT AVG MAX MIN SUM GROUP_CONCAT BIT_AND BIT_OR BIT_XOR STD STDDEV STDDEV_POP STDDEV_SAMP VAR_POP VAR_SAMP VARIANCE ANY_VALUE
%token <str> REGEXP_INSTR REGEXP_LIKE REGEXP_REPLACE REGEXP_SUBSTR
%token <str> ExtractValue UpdateXML
%token <str> GET_LOCK RELEASE_LOCK RELEASE_ALL_LOCKS IS_FREE_LOCK IS_USED_LOCK
%token <str> LOCATE POSITION
%token <str> ST_GeometryCollectionFromText ST_GeometryFromText ST_LineStringFromText ST_MultiLineStringFromText ST_MultiPointFromText ST_MultiPolygonFromText ST_PointFromText ST_PolygonFromText
%token <str> ST_GeometryCollectionFromWKB ST_GeometryFromWKB ST_LineStringFromWKB ST_MultiLineStringFromWKB ST_MultiPointFromWKB ST_MultiPolygonFromWKB ST_PointFromWKB ST_PolygonFromWKB
%token <str> ST_AsBinary ST_AsText ST_Dimension ST_Envelope ST_IsSimple ST_IsEmpty ST_GeometryType ST_X ST_Y ST_Latitude ST_Longitude ST_EndPoint ST_IsClosed ST_Length ST_NumPoints ST_StartPoint ST_PointN
%token <str> ST_Area ST_Centroid ST_ExteriorRing ST_InteriorRingN ST_NumInteriorRings ST_NumGeometries ST_GeometryN ST_LongFromGeoHash ST_PointFromGeoHash ST_LatFromGeoHash ST_GeoHash ST_AsGeoJSON ST_GeomFromGeoJSON
// Match
%token <str> MATCH AGAINST BOOLEAN LANGUAGE WITH QUERY EXPANSION WITHOUT VALIDATION ROLLUP
// MySQL reserved words that are unused by this grammar will map to this token.
%token <str> UNUSED ARRAY BYTE CUME_DIST DESCRIPTION DENSE_RANK EMPTY EXCEPT FIRST_VALUE GROUPING GROUPS JSON_TABLE LAG LAST_VALUE LATERAL LEAD
%token <str> NTH_VALUE NTILE OF OVER PERCENT_RANK RANK RECURSIVE ROW_NUMBER SYSTEM WINDOW
%token <str> ACTIVE ADMIN AUTOEXTEND_SIZE BUCKETS CLONE COLUMN_FORMAT COMPONENT DEFINITION ENFORCED ENGINE_ATTRIBUTE EXCLUDE FOLLOWING GET_MASTER_PUBLIC_KEY HISTOGRAM HISTORY
%token <str> INACTIVE INVISIBLE LOCKED MASTER_COMPRESSION_ALGORITHMS MASTER_PUBLIC_KEY_PATH MASTER_TLS_CIPHERSUITES MASTER_ZSTD_COMPRESSION_LEVEL
%token <str> NESTED NETWORK_NAMESPACE NOWAIT NULLS OJ OLD OPTIONAL ORDINALITY ORGANIZATION OTHERS PARTIAL PATH PERSIST PERSIST_ONLY PRECEDING PRIVILEGE_CHECKS_USER PROCESS
%token <str> RANDOM REFERENCE REQUIRE_ROW_FORMAT RESOURCE RESPECT RESTART RETAIN REUSE ROLE SECONDARY SECONDARY_ENGINE SECONDARY_ENGINE_ATTRIBUTE SECONDARY_LOAD SECONDARY_UNLOAD SIMPLE SKIP SRID
%token <str> THREAD_PRIORITY TIES UNBOUNDED VCPU VISIBLE RETURNING
// Performance Schema Functions
%token <str> FORMAT_BYTES FORMAT_PICO_TIME PS_CURRENT_THREAD_ID PS_THREAD_ID
// GTID Functions
%token <str> GTID_SUBSET GTID_SUBTRACT WAIT_FOR_EXECUTED_GTID_SET WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS
// Explain tokens
%token <str> FORMAT TREE VITESS TRADITIONAL VTEXPLAIN VEXPLAIN PLAN
// Lock type tokens
%token <str> LOCAL LOW_PRIORITY
// Flush tokens
%token <str> NO_WRITE_TO_BINLOG LOGS ERROR GENERAL HOSTS OPTIMIZER_COSTS USER_RESOURCES SLOW CHANNEL RELAY EXPORT
// Window Functions Token
%token <str> CURRENT ROW ROWS
// TableOptions tokens
%token <str> AVG_ROW_LENGTH CONNECTION CHECKSUM DELAY_KEY_WRITE ENCRYPTION ENGINE INSERT_METHOD MAX_ROWS MIN_ROWS PACK_KEYS PASSWORD
%token <str> FIXED DYNAMIC COMPRESSED REDUNDANT COMPACT ROW_FORMAT STATS_AUTO_RECALC STATS_PERSISTENT STATS_SAMPLE_PAGES STORAGE MEMORY DISK
// Partitions tokens
%token <str> PARTITIONS LINEAR RANGE LIST SUBPARTITION SUBPARTITIONS HASH
%type <partitionByType> range_or_list
%type <integer> partitions_opt algorithm_opt subpartitions_opt partition_max_rows partition_min_rows
%type <statement> command kill_statement
%type <statement> explain_statement explainable_statement vexplain_statement
%type <statement> prepare_statement execute_statement deallocate_statement
%type <statement> stream_statement vstream_statement insert_statement update_statement delete_statement set_statement set_transaction_statement
%type <statement> create_statement alter_statement rename_statement drop_statement truncate_statement flush_statement do_statement
%type <selStmt> select_statement select_stmt_with_into query_expression_parens query_expression query_expression_body query_primary
%type <with> with_clause_opt with_clause
%type <cte> common_table_expr
%type <ctes> with_list
%type <renameTablePairs> rename_list
%type <createTable> create_table_prefix
%type <alterTable> alter_table_prefix
%type <alterOption> alter_option alter_commands_modifier lock_index algorithm_index
%type <alterOptions> alter_options alter_commands_list alter_commands_modifier_list algorithm_lock_opt
%type <alterTable> create_index_prefix
%type <createDatabase> create_database_prefix
%type <alterDatabase> alter_database_prefix
%type <databaseOption> collate character_set encryption
%type <databaseOptions> create_options create_options_opt
%type <boolean> default_optional first_opt linear_opt jt_exists_opt jt_path_opt partition_storage_opt
%type <statement> analyze_statement show_statement use_statement purge_statement other_statement
%type <statement> begin_statement commit_statement rollback_statement savepoint_statement release_statement load_statement
%type <statement> lock_statement unlock_statement call_statement
%type <statement> revert_statement
%type <strs> comment_opt comment_list
%type <str> wild_opt check_option_opt cascade_or_local_opt restrict_or_cascade_opt
%type <explainType> explain_format_opt
%type <vexplainType> vexplain_type_opt
%type <trimType> trim_type
%type <frameUnitType> frame_units
%type <argumentLessWindowExprType> argument_less_window_expr_type
%type <framePoint> frame_point
%type <frameClause> frame_clause frame_clause_opt
%type <windowSpecification> window_spec
%type <overClause> over_clause
%type <overClause> over_clause_opt
%type <nullTreatmentType> null_treatment_type
%type <nullTreatmentClause> null_treatment_clause null_treatment_clause_opt
%type <fromFirstLastType> from_first_last_type
%type <fromFirstLastClause> from_first_last_clause from_first_last_clause_opt
%type <firstOrLastValueExprType> first_or_last_value_expr_type
%type <lagLeadExprType> lag_lead_expr_type
%type <windowDefinition> window_definition
%type <windowDefinitions> window_definition_list
%type <namedWindow> named_window
%type <namedWindows> named_windows_list named_windows_list_opt
%type <insertAction> insert_or_replace
%type <str> explain_synonyms
%type <partitionOption> partitions_options_opt partitions_options_beginning
%type <partitionDefinitionOptions> partition_definition_attribute_list_opt
%type <subPartition> subpartition_opt
%type <subPartitionDefinition> subpartition_definition
%type <subPartitionDefinitions> subpartition_definition_list subpartition_definition_list_with_brackets
%type <subPartitionDefinitionOptions> subpartition_definition_attribute_list_opt
%type <intervalType> interval timestampadd_interval
%type <str> cache_opt separator_opt flush_option for_channel_opt maxvalue
%type <matchExprOption> match_option
%type <boolean> distinct_opt union_op replace_opt local_opt
%type <selectExprs> select_expression_list
%type <selectExpr> select_expression
%type <strs> select_options select_options_opt flush_option_list
%type <str> select_option algorithm_view security_view security_view_opt
%type <str> generated_always_opt user_username address_opt
%type <definer> definer_opt user
%type <expr> expression signed_literal signed_literal_or_null null_as_literal now_or_signed_literal signed_literal bit_expr regular_expressions xml_expressions
%type <expr> simple_expr literal NUM_literal text_start text_literal text_literal_or_arg bool_pri literal_or_null now predicate tuple_expression null_int_variable_arg performance_schema_function_expressions gtid_function_expressions
%type <tableExprs> from_opt table_references from_clause
%type <tableExpr> table_reference table_factor join_table json_table_function
%type <jtColumnDefinition> jt_column
%type <jtColumnList> jt_columns_clause columns_list
%type <jtOnResponse> on_error on_empty json_on_response
%type <joinCondition> join_condition join_condition_opt on_expression_opt
%type <tableNames> table_name_list delete_table_list view_name_list
%type <joinType> inner_join outer_join straight_join natural_join
%type <tableName> table_name into_table_name delete_table_name
%type <aliasedTableName> aliased_table_name
%type <indexHint> index_hint
%type <indexHintForType> index_hint_for_opt
%type <indexHints> index_hint_list index_hint_list_opt
%type <expr> where_expression_opt
%type <boolVal> boolean_value
%type <comparisonExprOperator> compare
%type <ins> insert_data
%type <expr> num_val
%type <expr> function_call_keyword function_call_nonkeyword function_call_generic function_call_conflict
%type <isExprOperator> is_suffix
%type <colTuple> col_tuple
%type <exprs> expression_list expression_list_opt window_partition_clause_opt
%type <values> tuple_list
%type <valTuple> row_tuple tuple_or_empty
%type <subquery> subquery
%type <derivedTable> derived_table
%type <colName> column_name after_opt
%type <expr> column_name_or_offset
%type <colNames> column_names column_names_opt_paren
%type <whens> when_expression_list
%type <when> when_expression
%type <expr> expression_opt else_expression_opt default_with_comma_opt
%type <groupBy> group_by_opt
%type <expr> having_opt
%type <orderBy> order_by_opt order_list order_by_clause
%type <order> order
%type <orderDirection> asc_desc_opt
%type <limit> limit_opt limit_clause
%type <selectInto> into_clause
%type <columnTypeOptions> column_attribute_list_opt generated_column_attribute_list_opt
%type <str> header_opt export_options manifest_opt overwrite_opt format_opt optionally_opt regexp_symbol
%type <str> fields_opts fields_opt_list fields_opt lines_opts lines_opt lines_opt_list
%type <lock> locking_clause
%type <columns> ins_column_list column_list column_list_opt column_list_empty index_list
%type <variable> variable_expr set_variable user_defined_variable
%type <variables> at_id_list execute_statement_list_opt
%type <partitions> opt_partition_clause partition_list
%type <updateExprs> on_dup_opt
%type <updateExprs> update_list
%type <setExprs> set_list transaction_chars
%type <setExpr> set_expression transaction_char
%type <str> charset_or_character_set charset_or_character_set_or_names isolation_level
%type <updateExpr> update_expression
%type <str> for_from from_or_on
%type <str> default_opt
%type <ignore> ignore_opt
%type <str> columns_or_fields extended_opt storage_opt
%type <showFilter> like_or_where_opt like_opt
%type <boolean> exists_opt not_exists_opt enforced enforced_opt temp_opt full_opt
%type <empty> to_opt
%type <str> reserved_keyword non_reserved_keyword
%type <identifierCI> sql_id sql_id_opt reserved_sql_id col_alias as_ci_opt
%type <expr> charset_value
%type <identifierCS> table_id reserved_table_id table_alias as_opt_id table_id_opt from_database_opt use_table_name
%type <rowAlias> row_alias_opt
%type <empty> as_opt work_opt savepoint_opt
%type <empty> skip_to_end ddl_skip_to_end
%type <str> charset
%type <scope> set_session_or_global
%type <convertType> convert_type returning_type_opt convert_type_weight_string
%type <boolean> array_opt rollup_opt
%type <columnType> column_type
%type <columnType> int_type decimal_type numeric_type time_type char_type spatial_type
%type <literal> partition_comment partition_data_directory partition_index_directory
%type <intPtr> length_opt
%type <integer> func_datetime_precision
%type <columnCharset> charset_opt
%type <str> collate_opt
%type <boolean> binary_opt
%type <LengthScaleOption> double_length_opt float_length_opt decimal_length_opt
%type <boolean> unsigned_opt zero_fill_opt without_valid_opt
%type <strs> enum_values
%type <columnDefinition> column_definition
%type <columnDefinitions> column_definition_list
%type <indexDefinition> index_definition
%type <constraintDefinition> constraint_definition check_constraint_definition
%type <str> index_or_key index_symbols from_or_in index_or_key_opt
%type <str> name_opt constraint_name_opt
%type <str> equal_opt partition_tablespace_name
%type <tableSpec> table_spec table_column_list
%type <optLike> create_like
%type <str> table_opt_value
%type <tableOption> table_option
%type <tableOptions> table_option_list table_option_list_opt space_separated_table_option_list
%type <indexInfo> index_info
%type <indexColumn> index_column
%type <indexColumns> index_column_list
%type <indexOption> index_option using_index_type
%type <indexOptions> index_option_list index_option_list_opt using_opt
%type <constraintInfo> constraint_info check_constraint_info
%type <partDefs> partition_definitions partition_definitions_opt
%type <partDef> partition_definition partition_name
%type <partitionValueRange> partition_value_range
%type <partitionEngine> partition_engine
%type <partSpec> partition_operation
%type <vindexParam> vindex_param
%type <vindexParams> vindex_param_list vindex_params_opt
%type <jsonObjectParam> json_object_param
%type <jsonObjectParams> json_object_param_list json_object_param_opt
%type <identifierCI> ci_identifier vindex_type vindex_type_opt
%type <str> database_or_schema column_opt insert_method_options row_format_options
%type <referenceAction> fk_reference_action fk_on_delete fk_on_update
%type <matchAction> fk_match fk_match_opt fk_match_action
%type <tableAndLockTypes> lock_table_list
%type <tableAndLockType> lock_table
%type <lockType> lock_type
%type <empty> session_or_local_opt
%type <columnStorage> column_storage
%type <columnFormat> column_format
%type <colKeyOpt> keys
%type <referenceDefinition> reference_definition reference_definition_opt
%type <str> underscore_charsets
%type <str> expire_opt null_or_unknown
%type <literal> ratio_opt
%type <txAccessModes> tx_chacteristics_opt tx_chars
%type <txAccessMode> tx_char
%type <killType> kill_type_opt
%start any_command
%%
any_command:
comment_opt command semicolon_opt
{
stmt := $2
// If the statement is empty and we have comments
// then we create a special struct which stores them.
// This is required because we need to update the rows_returned
// and other query stats and not return a `query was empty` error
if stmt == nil && $1 != nil {
stmt = &CommentOnly{Comments: $1}
}
setParseTree(yylex, stmt)
}
semicolon_opt:
/*empty*/ {}
| ';' {}
command:
select_statement
{
$$ = $1
}
| stream_statement
| vstream_statement
| insert_statement
| update_statement
| delete_statement
| set_statement
| set_transaction_statement
| create_statement
| alter_statement
| rename_statement
| drop_statement
| truncate_statement
| analyze_statement
| purge_statement
| show_statement
| use_statement
| begin_statement
| commit_statement
| rollback_statement
| savepoint_statement
| release_statement
| explain_statement
| vexplain_statement
| other_statement
| flush_statement
| do_statement
| load_statement
| lock_statement
| unlock_statement
| call_statement
| revert_statement
| prepare_statement
| execute_statement
| deallocate_statement
| kill_statement
| /*empty*/
{
setParseTree(yylex, nil)
}
user_defined_variable:
AT_ID
{
$$ = NewVariableExpression($1, SingleAt)
}
ci_identifier:
ID
{
$$ = NewIdentifierCI(string($1))
}
variable_expr:
AT_ID
{
$$ = NewVariableExpression(string($1), SingleAt)
}
| AT_AT_ID
{
$$ = NewVariableExpression(string($1), DoubleAt)
}
do_statement:
DO expression_list
{
$$ = &OtherAdmin{}
}
load_statement:
LOAD DATA skip_to_end
{
$$ = &Load{}
}
with_clause:
WITH with_list
{
$$ = &With{CTEs: $2, Recursive: false}
}
| WITH RECURSIVE with_list
{
$$ = &With{CTEs: $3, Recursive: true}
}
with_clause_opt:
{
$$ = nil
}
| with_clause
{
$$ = $1
}
with_list:
with_list ',' common_table_expr
{
$$ = append($1, $3)
}
| common_table_expr
{
$$ = []*CommonTableExpr{$1}
}
common_table_expr:
table_id column_list_opt AS subquery
{
$$ = &CommonTableExpr{ID: $1, Columns: $2, Subquery: $4}
}
query_expression_parens:
openb query_expression_parens closeb
{
$$ = $2
}
| openb query_expression closeb
{
$$ = $2
}
| openb query_expression locking_clause closeb
{
setLockInSelect($2, $3)
$$ = $2
}
// TODO; (Manan, Ritwiz) : Use this in create, insert statements
//query_expression_or_parens:
// query_expression
// {
// $$ = $1
// }
// | query_expression locking_clause
// {
// setLockInSelect($1, $2)
// $$ = $1
// }
// | query_expression_parens
// {
// $$ = $1
// }
query_expression:
query_expression_body order_by_opt limit_opt
{
$1.SetOrderBy($2)
$1.SetLimit($3)
$$ = $1
}
| query_expression_parens limit_clause
{
$1.SetLimit($2)
$$ = $1
}
| query_expression_parens order_by_clause limit_opt
{
$1.SetOrderBy($2)
$1.SetLimit($3)
$$ = $1
}
| with_clause query_expression_body order_by_opt limit_opt
{
$2.SetWith($1)
$2.SetOrderBy($3)
$2.SetLimit($4)
$$ = $2
}
| with_clause query_expression_parens limit_clause
{
$2.SetWith($1)
$2.SetLimit($3)
$$ = $2
}
| with_clause query_expression_parens order_by_clause limit_opt
{
$2.SetWith($1)
$2.SetOrderBy($3)
$2.SetLimit($4)
$$ = $2
}
| with_clause query_expression_parens
{
$2.SetWith($1)
}
| SELECT comment_opt cache_opt NEXT num_val for_from table_name
{
$$ = NewSelect(Comments($2), SelectExprs{&Nextval{Expr: $5}}, []string{$3}/*options*/, nil, TableExprs{&AliasedTableExpr{Expr: $7}}, nil/*where*/, nil/*groupBy*/, nil/*having*/, nil)
}
query_expression_body:
query_primary
{
$$ = $1
}
| query_expression_body union_op query_primary
{
$$ = &Union{Left: $1, Distinct: $2, Right: $3}
}
| query_expression_parens union_op query_primary
{
$$ = &Union{Left: $1, Distinct: $2, Right: $3}
}
| query_expression_body union_op query_expression_parens
{
$$ = &Union{Left: $1, Distinct: $2, Right: $3}
}
| query_expression_parens union_op query_expression_parens
{
$$ = &Union{Left: $1, Distinct: $2, Right: $3}
}
select_statement:
query_expression
{
$$ = $1
}
| query_expression locking_clause
{
setLockInSelect($1, $2)
$$ = $1
}
| query_expression_parens
{
$$ = $1
}
| select_stmt_with_into
{
$$ = $1
}
select_stmt_with_into:
openb select_stmt_with_into closeb
{
$$ = $2
}
| query_expression into_clause
{
$1.SetInto($2)
$$ = $1
}
| query_expression into_clause locking_clause
{
$1.SetInto($2)
$1.SetLock($3)
$$ = $1
}
| query_expression locking_clause into_clause
{
$1.SetInto($3)
$1.SetLock($2)
$$ = $1
}
| query_expression_parens into_clause
{
$1.SetInto($2)
$$ = $1
}
stream_statement:
STREAM comment_opt select_expression FROM table_name
{
$$ = &Stream{Comments: Comments($2).Parsed(), SelectExpr: $3, Table: $5}
}
vstream_statement:
VSTREAM comment_opt select_expression FROM table_name where_expression_opt limit_opt
{
$$ = &VStream{Comments: Comments($2).Parsed(), SelectExpr: $3, Table: $5, Where: NewWhere(WhereClause, $6), Limit: $7}
}
// query_primary is an unparenthesized SELECT with no order by clause or beyond.
query_primary:
// 1 2 3 4 5 6 7 8 9 10
SELECT comment_opt select_options_opt select_expression_list into_clause from_opt where_expression_opt group_by_opt having_opt named_windows_list_opt
{
$$ = NewSelect(Comments($2), $4/*SelectExprs*/, $3/*options*/, $5/*into*/, $6/*from*/, NewWhere(WhereClause, $7), $8, NewWhere(HavingClause, $9), $10)
}
| SELECT comment_opt select_options_opt select_expression_list from_opt where_expression_opt group_by_opt having_opt named_windows_list_opt
{
$$ = NewSelect(Comments($2), $4/*SelectExprs*/, $3/*options*/, nil, $5/*from*/, NewWhere(WhereClause, $6), $7, NewWhere(HavingClause, $8), $9)
}
insert_statement:
insert_or_replace comment_opt ignore_opt into_table_name opt_partition_clause insert_data on_dup_opt
{
// insert_data returns a *Insert pre-filled with Columns & Values
ins := $6
ins.Action = $1
ins.Comments = Comments($2).Parsed()
ins.Ignore = $3
ins.Table = getAliasedTableExprFromTableName($4)
ins.Partitions = $5
ins.OnDup = OnDup($7)
$$ = ins
}
| insert_or_replace comment_opt ignore_opt into_table_name opt_partition_clause SET update_list on_dup_opt
{
cols := make(Columns, 0, len($7))
vals := make(ValTuple, 0, len($8))
for _, updateList := range $7 {
cols = append(cols, updateList.Name.Name)
vals = append(vals, updateList.Expr)
}
$$ = &Insert{Action: $1, Comments: Comments($2).Parsed(), Ignore: $3, Table: getAliasedTableExprFromTableName($4), Partitions: $5, Columns: cols, Rows: Values{vals}, OnDup: OnDup($8)}
}
insert_or_replace:
INSERT
{
$$ = InsertAct
}
| REPLACE
{
$$ = ReplaceAct
}
update_statement:
with_clause_opt UPDATE comment_opt ignore_opt table_references SET update_list where_expression_opt order_by_opt limit_opt
{
$$ = &Update{With: $1, Comments: Comments($3).Parsed(), Ignore: $4, TableExprs: $5, Exprs: $7, Where: NewWhere(WhereClause, $8), OrderBy: $9, Limit: $10}
}
delete_statement:
with_clause_opt DELETE comment_opt ignore_opt FROM table_name as_opt_id opt_partition_clause where_expression_opt order_by_opt limit_opt
{
$$ = &Delete{With: $1, Comments: Comments($3).Parsed(), Ignore: $4, TableExprs: TableExprs{&AliasedTableExpr{Expr:$6, As: $7}}, Partitions: $8, Where: NewWhere(WhereClause, $9), OrderBy: $10, Limit: $11}
}
| with_clause_opt DELETE comment_opt ignore_opt FROM table_name_list USING table_references where_expression_opt
{
$$ = &Delete{With: $1, Comments: Comments($3).Parsed(), Ignore: $4, Targets: $6, TableExprs: $8, Where: NewWhere(WhereClause, $9)}
}
| with_clause_opt DELETE comment_opt ignore_opt table_name_list from_or_using table_references where_expression_opt
{
$$ = &Delete{With: $1, Comments: Comments($3).Parsed(), Ignore: $4, Targets: $5, TableExprs: $7, Where: NewWhere(WhereClause, $8)}
}
| with_clause_opt DELETE comment_opt ignore_opt delete_table_list from_or_using table_references where_expression_opt
{
$$ = &Delete{With: $1, Comments: Comments($3).Parsed(), Ignore: $4, Targets: $5, TableExprs: $7, Where: NewWhere(WhereClause, $8)}
}
from_or_using:
FROM {}
| USING {}
view_name_list:
table_name
{
$$ = TableNames{$1}
}
| view_name_list ',' table_name
{
$$ = append($$, $3)
}
table_name_list:
table_name
{
$$ = TableNames{$1}
}
| table_name_list ',' table_name
{
$$ = append($$, $3)
}
delete_table_list:
delete_table_name