-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
Copy pathMySqlParser.g4
3519 lines (3105 loc) · 92.2 KB
/
MySqlParser.g4
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
/*
MySQL (Positive Technologies) grammar
The MIT License (MIT).
Copyright (c) 2015-2017, Ivan Kochurkin (kvanttt@gmail.com), Positive Technologies.
Copyright (c) 2017, Ivan Khudyashev (IHudyashov@ptsecurity.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// $antlr-format alignTrailingComments true, columnLimit 150, minEmptyLines 1, maxEmptyLinesToKeep 1, reflowComments false, useTab false
// $antlr-format allowShortRulesOnASingleLine false, allowShortBlocksOnASingleLine true, alignSemicolons hanging, alignColons hanging
parser grammar MySqlParser;
options {
tokenVocab = MySqlLexer;
}
// Top Level Description
root
: sqlStatements? (MINUS MINUS)? EOF
;
sqlStatements
: (sqlStatement (MINUS MINUS)? SEMI? | emptyStatement_)* (
sqlStatement ((MINUS MINUS)? SEMI)?
| emptyStatement_
)
;
sqlStatement
: ddlStatement
| dmlStatement
| transactionStatement
| replicationStatement
| preparedStatement
| administrationStatement
| utilityStatement
;
emptyStatement_
: SEMI
;
ddlStatement
: createDatabase
| createEvent
| createIndex
| createLogfileGroup
| createProcedure
| createFunction
| createServer
| createTable
| createTablespaceInnodb
| createTablespaceNdb
| createTrigger
| createView
| createRole
| alterDatabase
| alterEvent
| alterFunction
| alterInstance
| alterLogfileGroup
| alterProcedure
| alterServer
| alterTable
| alterTablespace
| alterView
| dropDatabase
| dropEvent
| dropIndex
| dropLogfileGroup
| dropProcedure
| dropFunction
| dropServer
| dropTable
| dropTablespace
| dropTrigger
| dropView
| dropRole
| setRole
| renameTable
| truncateTable
;
dmlStatement
: selectStatement
| insertStatement
| updateStatement
| deleteStatement
| replaceStatement
| callStatement
| loadDataStatement
| loadXmlStatement
| doStatement
| handlerStatement
| valuesStatement
| withStatement
| tableStatement
;
transactionStatement
: startTransaction
| beginWork
| commitWork
| rollbackWork
| savepointStatement
| rollbackStatement
| releaseStatement
| lockTables
| unlockTables
;
replicationStatement
: changeMaster
| changeReplicationFilter
| purgeBinaryLogs
| resetMaster
| resetSlave
| startSlave
| stopSlave
| startGroupReplication
| stopGroupReplication
| xaStartTransaction
| xaEndTransaction
| xaPrepareStatement
| xaCommitWork
| xaRollbackWork
| xaRecoverWork
;
preparedStatement
: prepareStatement
| executeStatement
| deallocatePrepare
;
// remark: NOT INCLUDED IN sqlStatement, but include in body
// of routine's statements
compoundStatement
: blockStatement
| caseStatement
| ifStatement
| leaveStatement
| loopStatement
| repeatStatement
| whileStatement
| iterateStatement
| returnStatement
| cursorStatement
| withStatement dmlStatement
;
administrationStatement
: alterUser
| createUser
| dropUser
| grantStatement
| grantProxy
| renameUser
| revokeStatement
| revokeProxy
| analyzeTable
| checkTable
| checksumTable
| optimizeTable
| repairTable
| createUdfunction
| installPlugin
| uninstallPlugin
| setStatement
| showStatement
| binlogStatement
| cacheIndexStatement
| flushStatement
| killStatement
| loadIndexIntoCache
| resetStatement
| shutdownStatement
;
utilityStatement
: simpleDescribeStatement
| fullDescribeStatement
| helpStatement
| useStatement
| signalStatement
| resignalStatement
| diagnosticsStatement
;
// Data Definition Language
// Create statements
createDatabase
: CREATE dbFormat = (DATABASE | SCHEMA) ifNotExists? uid createDatabaseOption*
;
createEvent
: CREATE ownerStatement? EVENT ifNotExists? fullId ON SCHEDULE scheduleExpression (
ON COMPLETION NOT? PRESERVE
)? enableType? (COMMENT STRING_LITERAL)? DO routineBody
;
createIndex
: CREATE intimeAction = (ONLINE | OFFLINE)? indexCategory = (UNIQUE | FULLTEXT | SPATIAL)? INDEX uid indexType? ON tableName indexColumnNames
indexOption* (
ALGORITHM EQUAL_SYMBOL? algType = (DEFAULT | INPLACE | COPY)
| LOCK EQUAL_SYMBOL? lockType = (DEFAULT | NONE | SHARED | EXCLUSIVE)
)*
;
createLogfileGroup
: CREATE LOGFILE GROUP uid ADD UNDOFILE undoFile = STRING_LITERAL (
INITIAL_SIZE '='? initSize = fileSizeLiteral
)? (UNDO_BUFFER_SIZE '='? undoSize = fileSizeLiteral)? (
REDO_BUFFER_SIZE '='? redoSize = fileSizeLiteral
)? (NODEGROUP '='? uid)? WAIT? (COMMENT '='? comment = STRING_LITERAL)? ENGINE '='? engineName
;
createProcedure
: CREATE ownerStatement? PROCEDURE ifNotExists? fullId '(' procedureParameter? (',' procedureParameter)* ')' routineOption* routineBody
;
createFunction
: CREATE ownerStatement? AGGREGATE? FUNCTION ifNotExists? fullId '(' functionParameter? (
',' functionParameter
)* ')' RETURNS dataType routineOption* (routineBody | returnStatement)
;
createRole
: CREATE ROLE ifNotExists? roleName (',' roleName)*
;
createServer
: CREATE SERVER uid FOREIGN DATA WRAPPER wrapperName = (MYSQL | STRING_LITERAL) OPTIONS '(' serverOption (
',' serverOption
)* ')'
;
createTable
: CREATE TEMPORARY? TABLE ifNotExists? tableName (
LIKE tableName
| '(' LIKE parenthesisTable = tableName ')'
) # copyCreateTable
| CREATE TEMPORARY? TABLE ifNotExists? tableName createDefinitions? (
tableOption (','? tableOption)*
)? partitionDefinitions? keyViolate = (IGNORE | REPLACE)? AS? selectStatement # queryCreateTable
| CREATE TEMPORARY? TABLE ifNotExists? tableName createDefinitions (
tableOption (','? tableOption)*
)? partitionDefinitions? # columnCreateTable
;
createTablespaceInnodb
: CREATE TABLESPACE uid ADD DATAFILE datafile = STRING_LITERAL (
FILE_BLOCK_SIZE '=' fileBlockSize = fileSizeLiteral
)? (ENGINE '='? engineName)?
;
createTablespaceNdb
: CREATE TABLESPACE uid ADD DATAFILE datafile = STRING_LITERAL USE LOGFILE GROUP uid (
EXTENT_SIZE '='? extentSize = fileSizeLiteral
)? (INITIAL_SIZE '='? initialSize = fileSizeLiteral)? (
AUTOEXTEND_SIZE '='? autoextendSize = fileSizeLiteral
)? (MAX_SIZE '='? maxSize = fileSizeLiteral)? (NODEGROUP '='? uid)? WAIT? (
COMMENT '='? comment = STRING_LITERAL
)? ENGINE '='? engineName
;
createTrigger
: CREATE ownerStatement? TRIGGER ifNotExists? thisTrigger = fullId triggerTime = (
BEFORE
| AFTER
) triggerEvent = (INSERT | UPDATE | DELETE) ON tableName FOR EACH ROW (
triggerPlace = (FOLLOWS | PRECEDES) otherTrigger = fullId
)? routineBody
;
withClause
: WITH RECURSIVE? commonTableExpressions
;
commonTableExpressions
: cteName ('(' cteColumnName (',' cteColumnName)* ')')? AS '(' dmlStatement ')' (
',' commonTableExpressions
)?
;
cteName
: uid
;
cteColumnName
: uid
;
createView
: CREATE orReplace? (ALGORITHM '=' algType = (UNDEFINED | MERGE | TEMPTABLE))? ownerStatement? (
SQL SECURITY secContext = (DEFINER | INVOKER)
)? VIEW fullId ('(' uidList ')')? AS (
'(' withClause? selectStatement ')'
| withClause? selectStatement (WITH checkOption = (CASCADED | LOCAL)? CHECK OPTION)?
)
;
// details
createDatabaseOption
: DEFAULT? charSet '='? (charsetName | DEFAULT)
| DEFAULT? COLLATE '='? collationName
| DEFAULT? ENCRYPTION '='? STRING_LITERAL
| READ ONLY '='? (DEFAULT | ZERO_DECIMAL | ONE_DECIMAL)
;
charSet
: CHARACTER SET
| CHARSET
| CHAR SET
;
currentUserExpression
: CURRENT_USER ('(' ')')?
;
ownerStatement
: DEFINER '=' (userName | currentUserExpression)
;
scheduleExpression
: AT timestampValue intervalExpr* # preciseSchedule
| EVERY (decimalLiteral | expression) intervalType (
STARTS startTimestamp = timestampValue (startIntervals += intervalExpr)*
)? (ENDS endTimestamp = timestampValue (endIntervals += intervalExpr)*)? # intervalSchedule
;
timestampValue
: CURRENT_TIMESTAMP
| stringLiteral
| decimalLiteral
| expression
;
intervalExpr
: '+' INTERVAL (decimalLiteral | expression) intervalType
;
intervalType
: intervalTypeBase
| YEAR
| YEAR_MONTH
| DAY_HOUR
| DAY_MINUTE
| DAY_SECOND
| HOUR_MINUTE
| HOUR_SECOND
| MINUTE_SECOND
| SECOND_MICROSECOND
| MINUTE_MICROSECOND
| HOUR_MICROSECOND
| DAY_MICROSECOND
;
enableType
: ENABLE
| DISABLE
| DISABLE ON SLAVE
;
indexType
: USING (BTREE | HASH)
;
indexOption
: KEY_BLOCK_SIZE EQUAL_SYMBOL? fileSizeLiteral
| indexType
| WITH PARSER uid
| COMMENT STRING_LITERAL
| (VISIBLE | INVISIBLE)
| ENGINE_ATTRIBUTE EQUAL_SYMBOL? STRING_LITERAL
| SECONDARY_ENGINE_ATTRIBUTE EQUAL_SYMBOL? STRING_LITERAL
;
procedureParameter
: direction = (IN | OUT | INOUT)? uid dataType
;
functionParameter
: uid dataType
;
routineOption
: COMMENT STRING_LITERAL # routineComment
| LANGUAGE SQL # routineLanguage
| NOT? DETERMINISTIC # routineBehavior
| ( CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA) # routineData
| SQL SECURITY context = (DEFINER | INVOKER) # routineSecurity
;
serverOption
: HOST STRING_LITERAL
| DATABASE STRING_LITERAL
| USER STRING_LITERAL
| PASSWORD STRING_LITERAL
| SOCKET STRING_LITERAL
| OWNER STRING_LITERAL
| PORT decimalLiteral
;
createDefinitions
: '(' createDefinition (',' createDefinition)* ')'
;
createDefinition
: fullColumnName columnDefinition # columnDeclaration
| tableConstraint NOT? ENFORCED? # constraintDeclaration
| indexColumnDefinition # indexDeclaration
;
columnDefinition
: dataType columnConstraint* NOT? ENFORCED?
;
columnConstraint
: nullNotnull # nullColumnConstraint
| DEFAULT defaultValue # defaultColumnConstraint
| VISIBLE # visibilityColumnConstraint
| INVISIBLE # invisibilityColumnConstraint
| (AUTO_INCREMENT | ON UPDATE currentTimestamp) # autoIncrementColumnConstraint
| PRIMARY? KEY # primaryKeyColumnConstraint
| CLUSTERING KEY # clusteringKeyColumnConstraint // Tokudb-specific only
| UNIQUE KEY? # uniqueKeyColumnConstraint
| COMMENT STRING_LITERAL # commentColumnConstraint
| COLUMN_FORMAT colformat = (FIXED | DYNAMIC | DEFAULT) # formatColumnConstraint
| STORAGE storageval = (DISK | MEMORY | DEFAULT) # storageColumnConstraint
| referenceDefinition # referenceColumnConstraint
| COLLATE collationName # collateColumnConstraint
| (GENERATED ALWAYS)? AS '(' expression ')' (VIRTUAL | STORED)? # generatedColumnConstraint
| SERIAL DEFAULT VALUE # serialDefaultColumnConstraint
| (CONSTRAINT name = uid?)? CHECK '(' expression ')' # checkColumnConstraint
;
tableConstraint
: (CONSTRAINT name = uid?)? PRIMARY KEY index = uid? indexType? indexColumnNames indexOption* # primaryKeyTableConstraint
| (CONSTRAINT name = uid?)? UNIQUE indexFormat = (INDEX | KEY)? index = uid? indexType? indexColumnNames indexOption* # uniqueKeyTableConstraint
| (CONSTRAINT name = uid?)? FOREIGN KEY index = uid? indexColumnNames referenceDefinition # foreignKeyTableConstraint
| (CONSTRAINT name = uid?)? CHECK '(' expression ')' # checkTableConstraint
| CLUSTERING KEY index = uid? indexColumnNames # clusteringKeyTableConstraint
// Tokudb-specific only
;
referenceDefinition
: REFERENCES tableName indexColumnNames? (MATCH matchType = (FULL | PARTIAL | SIMPLE))? referenceAction?
;
referenceAction
: ON DELETE onDelete = referenceControlType (ON UPDATE onUpdate = referenceControlType)?
| ON UPDATE onUpdate = referenceControlType (ON DELETE onDelete = referenceControlType)?
;
referenceControlType
: RESTRICT
| CASCADE
| SET NULL_LITERAL
| NO ACTION
| SET DEFAULT
;
indexColumnDefinition
: indexFormat = (INDEX | KEY) uid? indexType? indexColumnNames indexOption* # simpleIndexDeclaration
| (FULLTEXT | SPATIAL) indexFormat = (INDEX | KEY)? uid? indexColumnNames indexOption* # specialIndexDeclaration
;
tableOption
: ENGINE '='? engineName? # tableOptionEngine
| ENGINE_ATTRIBUTE '='? STRING_LITERAL # tableOptionEngineAttribute
| AUTOEXTEND_SIZE '='? decimalLiteral # tableOptionAutoextendSize
| AUTO_INCREMENT '='? decimalLiteral # tableOptionAutoIncrement
| AVG_ROW_LENGTH '='? decimalLiteral # tableOptionAverage
| DEFAULT? charSet '='? (charsetName | DEFAULT) # tableOptionCharset
| (CHECKSUM | PAGE_CHECKSUM) '='? boolValue = ('0' | '1') # tableOptionChecksum
| DEFAULT? COLLATE '='? collationName # tableOptionCollate
| COMMENT '='? STRING_LITERAL # tableOptionComment
| COMPRESSION '='? (STRING_LITERAL | ID) # tableOptionCompression
| CONNECTION '='? STRING_LITERAL # tableOptionConnection
| (DATA | INDEX) DIRECTORY '='? STRING_LITERAL # tableOptionDataDirectory
| DELAY_KEY_WRITE '='? boolValue = ('0' | '1') # tableOptionDelay
| ENCRYPTION '='? STRING_LITERAL # tableOptionEncryption
| (PAGE_COMPRESSED | STRING_LITERAL) '='? ('0' | '1') # tableOptionPageCompressed
| (PAGE_COMPRESSION_LEVEL | STRING_LITERAL) '='? decimalLiteral # tableOptionPageCompressionLevel
| ENCRYPTION_KEY_ID '='? decimalLiteral # tableOptionEncryptionKeyId
| INDEX DIRECTORY '='? STRING_LITERAL # tableOptionIndexDirectory
| INSERT_METHOD '='? insertMethod = (NO | FIRST | LAST) # tableOptionInsertMethod
| KEY_BLOCK_SIZE '='? fileSizeLiteral # tableOptionKeyBlockSize
| MAX_ROWS '='? decimalLiteral # tableOptionMaxRows
| MIN_ROWS '='? decimalLiteral # tableOptionMinRows
| PACK_KEYS '='? extBoolValue = ('0' | '1' | DEFAULT) # tableOptionPackKeys
| PASSWORD '='? STRING_LITERAL # tableOptionPassword
| ROW_FORMAT '='? rowFormat = (
DEFAULT
| DYNAMIC
| FIXED
| COMPRESSED
| REDUNDANT
| COMPACT
| ID
) # tableOptionRowFormat
| START TRANSACTION # tableOptionStartTransaction
| SECONDARY_ENGINE '='? (ID | STRING_LITERAL) # tableOptionSecondaryEngine
// HeatWave-specific only
| SECONDARY_ENGINE_ATTRIBUTE '='? STRING_LITERAL # tableOptionSecondaryEngineAttribute
| STATS_AUTO_RECALC '='? extBoolValue = (DEFAULT | '0' | '1') # tableOptionRecalculation
| STATS_PERSISTENT '='? extBoolValue = (DEFAULT | '0' | '1') # tableOptionPersistent
| STATS_SAMPLE_PAGES '='? (DEFAULT | decimalLiteral) # tableOptionSamplePage
| TABLESPACE uid tablespaceStorage? # tableOptionTablespace
| TABLE_TYPE '=' tableType # tableOptionTableType
| tablespaceStorage # tableOptionTablespace
| TRANSACTIONAL '='? ('0' | '1') # tableOptionTransactional
| UNION '='? '(' tables ')' # tableOptionUnion
;
tableType
: MYSQL
| ODBC
;
tablespaceStorage
: STORAGE (DISK | MEMORY | DEFAULT)
;
partitionDefinitions
: PARTITION BY partitionFunctionDefinition (PARTITIONS count = decimalLiteral)? (
SUBPARTITION BY subpartitionFunctionDefinition (SUBPARTITIONS subCount = decimalLiteral)?
)? ('(' partitionDefinition (',' partitionDefinition)* ')')?
;
partitionFunctionDefinition
: LINEAR? HASH '(' expression ')' # partitionFunctionHash
| LINEAR? KEY (ALGORITHM '=' algType = ('1' | '2'))? '(' uidList? ')' # partitionFunctionKey // Optional uidList for MySQL only
| RANGE ('(' expression ')' | COLUMNS '(' uidList ')') # partitionFunctionRange
| LIST ('(' expression ')' | COLUMNS '(' uidList ')') # partitionFunctionList
;
subpartitionFunctionDefinition
: LINEAR? HASH '(' expression ')' # subPartitionFunctionHash
| LINEAR? KEY (ALGORITHM '=' algType = ('1' | '2'))? '(' uidList ')' # subPartitionFunctionKey
;
partitionDefinition
: PARTITION uid VALUES LESS THAN '(' partitionDefinerAtom (',' partitionDefinerAtom)* ')' partitionOption* (
'(' subpartitionDefinition (',' subpartitionDefinition)* ')'
)? # partitionComparison
| PARTITION uid VALUES LESS THAN partitionDefinerAtom partitionOption* (
'(' subpartitionDefinition (',' subpartitionDefinition)* ')'
)? # partitionComparison
| PARTITION uid VALUES IN '(' partitionDefinerAtom (',' partitionDefinerAtom)* ')' partitionOption* (
'(' subpartitionDefinition (',' subpartitionDefinition)* ')'
)? # partitionListAtom
| PARTITION uid VALUES IN '(' partitionDefinerVector (',' partitionDefinerVector)* ')' partitionOption* (
'(' subpartitionDefinition (',' subpartitionDefinition)* ')'
)? # partitionListVector
| PARTITION uid partitionOption* ('(' subpartitionDefinition (',' subpartitionDefinition)* ')')? # partitionSimple
;
partitionDefinerAtom
: constant
| expression
| MAXVALUE
;
partitionDefinerVector
: '(' partitionDefinerAtom (',' partitionDefinerAtom)+ ')'
;
subpartitionDefinition
: SUBPARTITION uid partitionOption*
;
partitionOption
: DEFAULT? STORAGE? ENGINE '='? engineName # partitionOptionEngine
| COMMENT '='? comment = STRING_LITERAL # partitionOptionComment
| DATA DIRECTORY '='? dataDirectory = STRING_LITERAL # partitionOptionDataDirectory
| INDEX DIRECTORY '='? indexDirectory = STRING_LITERAL # partitionOptionIndexDirectory
| MAX_ROWS '='? maxRows = decimalLiteral # partitionOptionMaxRows
| MIN_ROWS '='? minRows = decimalLiteral # partitionOptionMinRows
| TABLESPACE '='? tablespace = uid # partitionOptionTablespace
| NODEGROUP '='? nodegroup = uid # partitionOptionNodeGroup
;
// Alter statements
alterDatabase
: ALTER dbFormat = (DATABASE | SCHEMA) uid? createDatabaseOption+ # alterSimpleDatabase
| ALTER dbFormat = (DATABASE | SCHEMA) uid UPGRADE DATA DIRECTORY NAME # alterUpgradeName
;
alterEvent
: ALTER ownerStatement? EVENT fullId (ON SCHEDULE scheduleExpression)? (
ON COMPLETION NOT? PRESERVE
)? (RENAME TO fullId)? enableType? (COMMENT STRING_LITERAL)? (DO routineBody)?
;
alterFunction
: ALTER FUNCTION fullId routineOption*
;
alterInstance
: ALTER INSTANCE ROTATE INNODB MASTER KEY
;
alterLogfileGroup
: ALTER LOGFILE GROUP uid ADD UNDOFILE STRING_LITERAL (INITIAL_SIZE '='? fileSizeLiteral)? WAIT? ENGINE '='? engineName
;
alterProcedure
: ALTER PROCEDURE fullId routineOption*
;
alterServer
: ALTER SERVER uid OPTIONS '(' serverOption (',' serverOption)* ')'
;
alterTable
: ALTER intimeAction = (ONLINE | OFFLINE)? IGNORE? TABLE tableName (
alterSpecification (',' alterSpecification)*
)? partitionDefinitions?
;
alterTablespace
: ALTER TABLESPACE uid objectAction = (ADD | DROP) DATAFILE STRING_LITERAL (
INITIAL_SIZE '=' fileSizeLiteral
)? WAIT? ENGINE '='? engineName
;
alterView
: ALTER (ALGORITHM '=' algType = (UNDEFINED | MERGE | TEMPTABLE))? ownerStatement? (
SQL SECURITY secContext = (DEFINER | INVOKER)
)? VIEW fullId ('(' uidList ')')? AS selectStatement (
WITH checkOpt = (CASCADED | LOCAL)? CHECK OPTION
)?
;
// details
alterSpecification
: tableOption (','? tableOption)* # alterByTableOption
| ADD COLUMN? uid columnDefinition (FIRST | AFTER uid)? # alterByAddColumn
| ADD COLUMN? '(' uid columnDefinition (',' uid columnDefinition)* ')' # alterByAddColumns
| ADD indexFormat = (INDEX | KEY) uid? indexType? indexColumnNames indexOption* # alterByAddIndex
| ADD (CONSTRAINT name = uid?)? PRIMARY KEY index = uid? indexType? indexColumnNames indexOption* # alterByAddPrimaryKey
| ADD (CONSTRAINT name = uid?)? UNIQUE indexFormat = (INDEX | KEY)? indexName = uid? indexType? indexColumnNames indexOption* # alterByAddUniqueKey
| ADD keyType = (FULLTEXT | SPATIAL) indexFormat = (INDEX | KEY)? uid? indexColumnNames indexOption* # alterByAddSpecialIndex
| ADD (CONSTRAINT name = uid?)? FOREIGN KEY indexName = uid? indexColumnNames referenceDefinition # alterByAddForeignKey
| ADD (CONSTRAINT name = uid?)? CHECK (uid | stringLiteral | '(' expression ')') NOT? ENFORCED? # alterByAddCheckTableConstraint
| ALTER (CONSTRAINT name = uid?)? CHECK (uid | stringLiteral | '(' expression ')') NOT? ENFORCED? # alterByAlterCheckTableConstraint
| ADD (CONSTRAINT name = uid?)? CHECK '(' expression ')' # alterByAddCheckTableConstraint
| ALGORITHM '='? algType = (DEFAULT | INSTANT | INPLACE | COPY) # alterBySetAlgorithm
| ALTER COLUMN? uid (SET DEFAULT defaultValue | DROP DEFAULT) # alterByChangeDefault
| CHANGE COLUMN? oldColumn = uid newColumn = uid columnDefinition (
FIRST
| AFTER afterColumn = uid
)? # alterByChangeColumn
| RENAME COLUMN oldColumn = uid TO newColumn = uid # alterByRenameColumn
| LOCK '='? lockType = (DEFAULT | NONE | SHARED | EXCLUSIVE) # alterByLock
| MODIFY COLUMN? uid columnDefinition (FIRST | AFTER uid)? # alterByModifyColumn
| DROP COLUMN? uid RESTRICT? # alterByDropColumn
| DROP (CONSTRAINT | CHECK) uid # alterByDropConstraintCheck
| DROP PRIMARY KEY # alterByDropPrimaryKey
| DROP indexFormat = (INDEX | KEY) uid # alterByDropIndex
| RENAME indexFormat = (INDEX | KEY) uid TO uid # alterByRenameIndex
| ALTER COLUMN? uid (
SET DEFAULT ( stringLiteral | '(' expression ')')
| SET (VISIBLE | INVISIBLE)
| DROP DEFAULT
) # alterByAlterColumnDefault
| ALTER INDEX uid (VISIBLE | INVISIBLE) # alterByAlterIndexVisibility
| DROP FOREIGN KEY uid dottedId? # alterByDropForeignKey
| DISABLE KEYS # alterByDisableKeys
| ENABLE KEYS # alterByEnableKeys
| RENAME renameFormat = (TO | AS)? (uid | fullId) # alterByRename
| ORDER BY uidList # alterByOrder
| CONVERT TO (CHARSET | CHARACTER SET) charsetName (COLLATE collationName)? # alterByConvertCharset
| DEFAULT? CHARACTER SET '=' charsetName (COLLATE '=' collationName)? # alterByDefaultCharset
| DISCARD TABLESPACE # alterByDiscardTablespace
| IMPORT TABLESPACE # alterByImportTablespace
| FORCE # alterByForce
| validationFormat = (WITHOUT | WITH) VALIDATION # alterByValidate
| ADD COLUMN? '(' createDefinition (',' createDefinition)* ')' # alterByAddDefinitions
| alterPartitionSpecification # alterPartition
;
alterPartitionSpecification
: ADD PARTITION '(' partitionDefinition (',' partitionDefinition)* ')' # alterByAddPartition
| DROP PARTITION uidList # alterByDropPartition
| DISCARD PARTITION (uidList | ALL) TABLESPACE # alterByDiscardPartition
| IMPORT PARTITION (uidList | ALL) TABLESPACE # alterByImportPartition
| TRUNCATE PARTITION (uidList | ALL) # alterByTruncatePartition
| COALESCE PARTITION decimalLiteral # alterByCoalescePartition
| REORGANIZE PARTITION uidList INTO '(' partitionDefinition (',' partitionDefinition)* ')' # alterByReorganizePartition
| EXCHANGE PARTITION uid WITH TABLE tableName (validationFormat = (WITH | WITHOUT) VALIDATION)? # alterByExchangePartition
| ANALYZE PARTITION (uidList | ALL) # alterByAnalyzePartition
| CHECK PARTITION (uidList | ALL) # alterByCheckPartition
| OPTIMIZE PARTITION (uidList | ALL) # alterByOptimizePartition
| REBUILD PARTITION (uidList | ALL) # alterByRebuildPartition
| REPAIR PARTITION (uidList | ALL) # alterByRepairPartition
| REMOVE PARTITIONING # alterByRemovePartitioning
| UPGRADE PARTITIONING # alterByUpgradePartitioning
;
// Drop statements
dropDatabase
: DROP dbFormat = (DATABASE | SCHEMA) ifExists? uid
;
dropEvent
: DROP EVENT ifExists? fullId
;
dropIndex
: DROP INDEX intimeAction = (ONLINE | OFFLINE)? uid ON tableName (
ALGORITHM '='? algType = (DEFAULT | INPLACE | COPY)
| LOCK '='? lockType = (DEFAULT | NONE | SHARED | EXCLUSIVE)
)*
;
dropLogfileGroup
: DROP LOGFILE GROUP uid ENGINE '=' engineName
;
dropProcedure
: DROP PROCEDURE ifExists? fullId
;
dropFunction
: DROP FUNCTION ifExists? fullId
;
dropServer
: DROP SERVER ifExists? uid
;
dropTable
: DROP TEMPORARY? TABLE ifExists? tables dropType = (RESTRICT | CASCADE)?
;
dropTablespace
: DROP TABLESPACE uid (ENGINE '='? engineName)?
;
dropTrigger
: DROP TRIGGER ifExists? fullId
;
dropView
: DROP VIEW ifExists? fullId (',' fullId)* dropType = (RESTRICT | CASCADE)?
;
dropRole
: DROP ROLE ifExists? roleName (',' roleName)*
;
setRole
: SET DEFAULT ROLE (NONE | ALL | roleName (',' roleName)*) TO (userName | uid) (
',' (userName | uid)
)*
| SET ROLE roleOption
;
// Other DDL statements
renameTable
: RENAME TABLE renameTableClause (',' renameTableClause)*
;
renameTableClause
: tableName TO tableName
;
truncateTable
: TRUNCATE TABLE? tableName
;
// Data Manipulation Language
// Primary DML Statements
callStatement
: CALL fullId ('(' (constants | expressions)? ')')?
;
deleteStatement
: singleDeleteStatement
| multipleDeleteStatement
;
doStatement
: DO expressions
;
handlerStatement
: handlerOpenStatement
| handlerReadIndexStatement
| handlerReadStatement
| handlerCloseStatement
;
insertStatement
: INSERT priority = (LOW_PRIORITY | DELAYED | HIGH_PRIORITY)? IGNORE? INTO? tableName (
PARTITION '(' partitions = uidList? ')'
)? (
('(' columns = fullColumnNameList? ')')? insertStatementValue (AS? uid)?
| SET setFirst = updatedElement (',' setElements += updatedElement)*
) (
ON DUPLICATE KEY UPDATE duplicatedFirst = updatedElement (
',' duplicatedElements += updatedElement
)*
)?
;
loadDataStatement
: LOAD DATA priority = (LOW_PRIORITY | CONCURRENT)? LOCAL? INFILE filename = STRING_LITERAL violation = (
REPLACE
| IGNORE
)? INTO TABLE tableName (PARTITION '(' uidList ')')? (CHARACTER SET charset = charsetName)? (
fieldsFormat = (FIELDS | COLUMNS) selectFieldsInto+
)? (LINES selectLinesInto+)? (IGNORE decimalLiteral linesFormat = (LINES | ROWS))? (
'(' assignmentField (',' assignmentField)* ')'
)? (SET updatedElement (',' updatedElement)*)?
;
loadXmlStatement
: LOAD XML priority = (LOW_PRIORITY | CONCURRENT)? LOCAL? INFILE filename = STRING_LITERAL violation = (
REPLACE
| IGNORE
)? INTO TABLE tableName (CHARACTER SET charset = charsetName)? (
ROWS IDENTIFIED BY '<' tag = STRING_LITERAL '>'
)? (IGNORE decimalLiteral linesFormat = (LINES | ROWS))? (
'(' assignmentField (',' assignmentField)* ')'
)? (SET updatedElement (',' updatedElement)*)?
;
replaceStatement
: REPLACE priority = (LOW_PRIORITY | DELAYED)? INTO? tableName (
PARTITION '(' partitions = uidList ')'
)? (
('(' columns = uidList ')')? insertStatementValue
| SET setFirst = updatedElement (',' setElements += updatedElement)*
)
;
selectStatement
: querySpecification lockClause? # simpleSelect
| queryExpression lockClause? # parenthesisSelect
| (querySpecificationNointo | queryExpressionNointo) unionStatement+ (
UNION unionType = (ALL | DISTINCT)? (querySpecification | queryExpression)
)? orderByClause? limitClause? lockClause? # unionSelect
| queryExpressionNointo unionParenthesis+ (UNION unionType = (ALL | DISTINCT)? queryExpression)? orderByClause? limitClause? lockClause? #
unionParenthesisSelect
| querySpecificationNointo (',' lateralStatement)+ # withLateralStatement
;
updateStatement
: singleUpdateStatement
| multipleUpdateStatement
;
// https://dev.mysql.com/doc/refman/8.0/en/values.html
valuesStatement
: VALUES '(' expressionsWithDefaults? ')' (',' '(' expressionsWithDefaults? ')')*
;
// details
insertStatementValue
: selectStatement
| insertFormat = (VALUES | VALUE) '(' expressionsWithDefaults? ')' (
',' '(' expressionsWithDefaults? ')'
)*
;
updatedElement
: fullColumnName '=' (expression | DEFAULT)
;
assignmentField
: uid
| LOCAL_ID
;
lockClause
: FOR UPDATE
| LOCK IN SHARE MODE
;
// Detailed DML Statements
singleDeleteStatement
: DELETE priority = LOW_PRIORITY? QUICK? IGNORE? FROM tableName (AS? uid)? (
PARTITION '(' uidList ')'
)? (WHERE expression)? orderByClause? (LIMIT limitClauseAtom)?
;
multipleDeleteStatement
: DELETE priority = LOW_PRIORITY? QUICK? IGNORE? (
tableName ('.' '*')? ( ',' tableName ('.' '*')?)* FROM tableSources
| FROM tableName ('.' '*')? ( ',' tableName ('.' '*')?)* USING tableSources
) (WHERE expression)?
;
handlerOpenStatement
: HANDLER tableName OPEN (AS? uid)?
;
handlerReadIndexStatement
: HANDLER tableName READ index = uid (
comparisonOperator '(' constants ')'
| moveOrder = (FIRST | NEXT | PREV | LAST)
) (WHERE expression)? (LIMIT limitClauseAtom)?
;
handlerReadStatement
: HANDLER tableName READ moveOrder = (FIRST | NEXT) (WHERE expression)? (LIMIT limitClauseAtom)?
;
handlerCloseStatement
: HANDLER tableName CLOSE
;
singleUpdateStatement
: UPDATE priority = LOW_PRIORITY? IGNORE? tableSources (AS? uid)? SET updatedElement (
',' updatedElement
)* (WHERE expression)? orderByClause? limitClause?
;
multipleUpdateStatement
: UPDATE priority = LOW_PRIORITY? IGNORE? tableSources SET updatedElement (',' updatedElement)* (
WHERE expression
)?
;
// details
orderByClause
: ORDER BY orderByExpression (',' orderByExpression)*
;
orderByExpression
: expression order = (ASC | DESC)?
;
tableSources
: tableSource (',' tableSource)*
;
tableSource
: tableSourceItem joinPart* # tableSourceBase
| '(' tableSourceItem joinPart* ')' # tableSourceNested
| jsonTable # tableJson
;
tableSourceItem
: tableName (PARTITION '(' uidList ')')? (AS? alias = uid)? (indexHint (',' indexHint)*)? # atomTableItem
| (selectStatement | '(' parenthesisSubquery = selectStatement ')') AS? alias = uid # subqueryTableItem
| '(' tableSources ')' # tableSourcesItem
;
indexHint
: indexHintAction = (USE | IGNORE | FORCE) keyFormat = (INDEX | KEY) (FOR indexHintType)? '(' uidList ')'
;
indexHintType
: JOIN
| ORDER BY
| GROUP BY
;
joinPart
: (INNER | CROSS)? JOIN LATERAL? tableSourceItem joinSpec* # innerJoin
| STRAIGHT_JOIN tableSourceItem (ON expression)* # straightJoin
| (LEFT | RIGHT) OUTER? JOIN LATERAL? tableSourceItem joinSpec* # outerJoin
| NATURAL ((LEFT | RIGHT) OUTER?)? JOIN tableSourceItem # naturalJoin
;