-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathMySqlParser.g4
More file actions
3628 lines (3167 loc) · 102 KB
/
MySqlParser.g4
File metadata and controls
3628 lines (3167 loc) · 102 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
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.
*/
// https://github.com/antlr/grammars-v4/blob/master/sql/mysql/Positive-Technologies/MySqlParser.g4
// SQL Statements v8.0: https://dev.mysql.com/doc/refman/8.0/en/sql-statements.html
// SQL Statements v5.7: https://dev.mysql.com/doc/refman/5.7/en/sql-statements.html
// $antlr-format alignTrailingComments true, columnLimit 150, minEmptyLines 1, maxEmptyLinesToKeep 1, reflowComments false, useTab false
// $antlr-format allowShortRulesOnASingleLine false, allowShortBlocksOnASingleLine true, alignSemicolons hanging, alignColons hanging
// $antlr-format spaceBeforeAssignmentOperators false, keepEmptyLinesAtTheStartOfBlocks true
parser grammar MySqlParser;
options {
tokenVocab= MySqlLexer;
caseInsensitive= true;
superClass=SQLParserBase;
}
@header {
import { SQLParserBase } from '../SQLParserBase';
}
// Top Level Description
program
: singleStatement* EOF
;
singleStatement
: sqlStatement SEMI?
| emptyStatement_
;
sqlStatement
: ddlStatement
| dmlStatement
| transactionStatement
| replicationStatement
| preparedStatement
| administrationStatement
| utilityStatement
;
emptyStatement_
: SEMI
;
ddlStatement
: createDatabase
| createEvent
| createIndex
| createLogFileGroup
| createProcedure
| createFunction
| createFunctionLoadable
| createServer
| createTable
| createTableSpaceInnoDB
| createTableSpaceNDB
| createTrigger
| createView
| createRole
| alterDatabase
| alterEvent
| alterFunction
| alterInstance
| alterLogFileGroup
| alterProcedure
| alterServer
| alterTable
| alterTableSpace
| alterView
| dropDatabase
| dropEvent
| dropIndex
| dropLogFileGroup
| dropProcedure
| dropFunction
| dropServer
| dropSpatial
| dropTable
| dropTableSpace
| dropTrigger
| dropView
| dropRole
| setRole
| renameTable
| truncateTable
;
dmlStatement
: selectStatement
| setOperations
| insertStatement
| updateStatement
| deleteStatement
| replaceStatement
| callStatement
| interSectStatement
| loadDataStatement
| loadXmlStatement
| parenthesizedQuery
| doStatement
| handlerStatement
| importTableStatement
| valuesStatement
| withStatement
| tableStatement
;
transactionStatement
: startTransaction
| beginWork
| commitWork
| rollbackWork
| savePointStatement
| rollbackStatement
| releaseStatement
| lockTables
| unlockTables
;
replicationStatement
: changeMaster
| changeReplicationFilter
| changeReplicationSource
| purgeBinaryLogs
| startSlaveOrReplica
| stopSlaveOrReplica
| 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
;
administrationStatement
: alterUser
| createUser
| dropUser
| grantStatement
| grantProxy
| renameUser
| revokeStatement
| alterResourceGroup
| createResourceGroup
| dropResourceGroup
| setResourceGroup
| analyzeTable
| checkTable
| checksumTable
| optimizeTable
| repairTable
| installComponent
| uninstallComponent
| installPlugin
| uninstallPlugin
| cloneStatement
| setStatement
| showStatement
| binLogStatement
| cacheIndexStatement
| flushStatement
| killStatement
| loadIndexIntoCache
| resetStatement
| resetPersist
| resetAllChannel
| reStartStatement
| shutdownStatement
;
utilityStatement
: fullDescribeStatement
| simpleDescribeStatement
| analyzeDescribeStatement
| helpStatement
| useStatement
| signalStatement
| resignalStatement
| diagnosticsStatement
;
// Data Definition Language
// Create statements
createDatabase
: KW_CREATE dbFormat=(KW_DATABASE | KW_SCHEMA) ifNotExists? databaseNameCreate createDatabaseOption*
;
createEvent
: KW_CREATE ownerStatement? KW_EVENT ifNotExists? event_name=fullId KW_ON KW_SCHEDULE scheduleExpression (
KW_ON KW_COMPLETION KW_NOT? KW_PRESERVE
)? enableType? (KW_COMMENT STRING_LITERAL)? KW_DO routineBody
;
createIndex
: KW_CREATE intimeAction=(KW_ONLINE | KW_OFFLINE)? indexCategory=(
KW_UNIQUE
| KW_FULLTEXT
| KW_SPATIAL
)? KW_INDEX indexNameCreate indexType? KW_ON tableName indexColumnNames indexOption* (
KW_ALGORITHM EQUAL_SYMBOL? algType=(KW_DEFAULT | KW_INPLACE | KW_COPY)
| KW_LOCK EQUAL_SYMBOL? lockType=(KW_DEFAULT | KW_NONE | KW_SHARED | KW_EXCLUSIVE)
)*
;
createLogFileGroup
: KW_CREATE KW_LOGFILE KW_GROUP logFileGroupName=uid KW_ADD KW_UNDOFILE undoFile=STRING_LITERAL (
KW_INITIAL_SIZE '='? initSize=fileSizeLiteral
)? (KW_UNDO_BUFFER_SIZE '='? undoSize=fileSizeLiteral)? (
KW_REDO_BUFFER_SIZE '='? redoSize=fileSizeLiteral
)? (KW_NODEGROUP '='? nodeGroup=uid)? KW_WAIT? (KW_COMMENT '='? comment=STRING_LITERAL)? KW_ENGINE '='? engineName
;
createProcedure
: KW_CREATE ownerStatement? KW_PROCEDURE ifNotExists? sp_name=fullId '(' procedureParameter? (
',' procedureParameter
)* ')' routineOption* routineBody
;
createFunction
: KW_CREATE ownerStatement? KW_AGGREGATE? KW_FUNCTION ifNotExists? functionNameCreate '(' functionParameter? (
',' functionParameter
)* ')' KW_RETURNS dataType routineOption* (routineBody | returnStatement)
;
// https://dev.mysql.com/doc/refman/8.0/en/create-function-loadable.html
createFunctionLoadable
: KW_CREATE KW_AGGREGATE? KW_FUNCTION ifNotExists? functionNameCreate KW_RETURNS returnType=(
KW_STRING
| KW_INTEGER
| KW_REAL
| KW_DECIMAL
) KW_SONAME STRING_LITERAL
;
createRole
: KW_CREATE KW_ROLE ifNotExists? userOrRoleNames
;
createServer
: KW_CREATE KW_SERVER servername=uid KW_FOREIGN KW_DATA KW_WRAPPER wrapperName=(
KW_MYSQL
| STRING_LITERAL
) KW_OPTIONS '(' serverOption (',' serverOption)* ')'
;
createTable
: KW_CREATE KW_TEMPORARY? KW_TABLE ifNotExists? tb= tableNameCreate col=createDefinitions? (
tableOption (','? tableOption)*
)? partitionDefinitions? (KW_IGNORE | KW_REPLACE)? KW_AS? selectStatement # queryCreateTable
| KW_CREATE KW_TEMPORARY? KW_TABLE ifNotExists? tableNameCreate (
KW_LIKE tableName
| '(' KW_LIKE tableName ')'
) # copyCreateTable
| KW_CREATE KW_TEMPORARY? KW_TABLE ifNotExists? tableNameCreate createDefinitions (
tableOption (','? tableOption)*
)? partitionDefinitions? # columnCreateTable
;
createTableSpaceInnoDB
: KW_CREATE KW_UNDO? KW_TABLESPACE tableSpaceNameCreate (
KW_ADD KW_DATAFILE datafile=STRING_LITERAL
)? (KW_AUTOEXTEND_SIZE '='? autoExtendSize=fileSizeLiteral)? (
KW_FILE_BLOCK_SIZE '=' fileBlockSize=fileSizeLiteral
)? (KW_ENGINE '='? engineName)? (KW_ENGINE_ATTRIBUTE '='? STRING_LITERAL)?
;
createTableSpaceNDB
: KW_CREATE KW_UNDO? KW_TABLESPACE tableSpaceNameCreate KW_ADD KW_DATAFILE datafile=STRING_LITERAL KW_USE KW_LOGFILE KW_GROUP logFileGroupName=uid
(
KW_EXTENT_SIZE '='? extentSize=fileSizeLiteral
)? (KW_INITIAL_SIZE '='? initialSize=fileSizeLiteral)? (
KW_AUTOEXTEND_SIZE '='? autoExtendSize=fileSizeLiteral
)? (KW_MAX_SIZE '='? maxSize=fileSizeLiteral)? (KW_NODEGROUP '='? nodeGroup=uid)? KW_WAIT? (
KW_COMMENT '='? comment=STRING_LITERAL
)? KW_ENGINE '='? engineName
;
createTrigger
: KW_CREATE ownerStatement? ifNotExists? KW_TRIGGER ifNotExists? trigger_name=fullId triggerTime=(
KW_BEFORE
| KW_AFTER
) triggerEvent=(KW_INSERT | KW_UPDATE | KW_DELETE) KW_ON tableName KW_FOR KW_EACH KW_ROW (
triggerPlace=(KW_FOLLOWS | KW_PRECEDES) other_trigger_name=fullId
)? routineBody
;
withClause
: KW_WITH KW_RECURSIVE? commonTableExpressions
;
commonTableExpressions
: cteName=uid ('(' cteColumnName=uid (',' cteColumnName=uid)* ')')? KW_AS '(' dmlStatement ')' (
',' commonTableExpressions
)?
;
createView
: KW_CREATE orReplace? (KW_ALGORITHM '=' algType=(KW_UNDEFINED | KW_MERGE | KW_TEMPTABLE))? ownerStatement? (
KW_SQL KW_SECURITY secContext=(KW_DEFINER | KW_INVOKER)
)? KW_VIEW viewNameCreate ('(' columnNameCreate (',' columnNameCreate)* ')')? KW_AS (
'(' withClause? selectStatement ')'
| withClause? selectStatement (
KW_WITH checkOption=(KW_CASCADED | KW_LOCAL)? KW_CHECK KW_OPTION
)?
)
;
// details
createDatabaseOption
: KW_DEFAULT? charSet '='? (charsetName | KW_DEFAULT)
| KW_DEFAULT? KW_COLLATE '='? collationName
| KW_DEFAULT? KW_ENCRYPTION '='? STRING_LITERAL
| KW_READ KW_ONLY '='? (KW_DEFAULT | ZERO_DECIMAL | ONE_DECIMAL)
;
charSet
: KW_CHARACTER KW_SET
| KW_CHARSET
| KW_CHAR KW_SET
;
currentUserExpression
: (KW_CURRENT_USER | KW_USER) ('(' ')')?
;
ownerStatement
: KW_DEFINER '=' (userName | currentUserExpression)
;
scheduleExpression
: KW_AT timestampValue intervalExpr* # preciseSchedule
| KW_EVERY (decimalLiteral | expression) intervalType (
KW_STARTS startTimestamp=timestampValue (startIntervals+=intervalExpr)*
)? (KW_ENDS endTimestamp=timestampValue (endIntervals+=intervalExpr)*)? # intervalSchedule
;
timestampValue
: KW_CURRENT_TIMESTAMP
| stringLiteral
| decimalLiteral
| expression
;
intervalExpr
: '+' KW_INTERVAL (decimalLiteral | expression) intervalType
;
intervalType
: intervalTypeBase
| KW_YEAR
| KW_YEAR_MONTH
| KW_DAY_HOUR
| KW_DAY_MINUTE
| KW_DAY_SECOND
| KW_HOUR_MINUTE
| KW_HOUR_SECOND
| KW_MINUTE_SECOND
| KW_SECOND_MICROSECOND
| KW_MINUTE_MICROSECOND
| KW_HOUR_MICROSECOND
| KW_DAY_MICROSECOND
;
enableType
: KW_ENABLE
| KW_DISABLE
| KW_DISABLE KW_ON KW_SLAVE
;
indexType
: KW_USING (KW_BTREE | KW_HASH)
;
indexOption
: KW_KEY_BLOCK_SIZE EQUAL_SYMBOL? fileSizeLiteral
| indexType
| KW_WITH KW_PARSER parserName=uid
| KW_COMMENT STRING_LITERAL
| (KW_VISIBLE | KW_INVISIBLE)
| KW_ENGINE_ATTRIBUTE EQUAL_SYMBOL? STRING_LITERAL
| KW_SECONDARY_ENGINE_ATTRIBUTE EQUAL_SYMBOL? STRING_LITERAL
;
procedureParameter
: direction=(KW_IN | KW_OUT | KW_INOUT)? paramName=uid dataType
;
functionParameter
: paramName=uid dataType
;
routineOption
: KW_COMMENT comment=STRING_LITERAL # routineComment
| KW_LANGUAGE KW_SQL # routineLanguage
| KW_NOT? KW_DETERMINISTIC # routineBehavior
| (KW_CONTAINS KW_SQL | KW_NO KW_SQL | KW_READS KW_SQL KW_DATA | KW_MODIFIES KW_SQL KW_DATA) # routineData
| KW_SQL KW_SECURITY context=(KW_DEFINER | KW_INVOKER) # routineSecurity
;
serverOption
: KW_HOST STRING_LITERAL
| KW_DATABASE STRING_LITERAL
| KW_USER STRING_LITERAL
| KW_PASSWORD STRING_LITERAL
| KW_SOCKET STRING_LITERAL
| KW_OWNER STRING_LITERAL
| KW_PORT decimalLiteral
;
createDefinitions
: '(' createDefinition (',' createDefinition)* ')'
;
createDefinition
: columnNameCreate columnDefinition
| (KW_INDEX | KW_KEY) indexName? indexType? indexColumnNames indexOption*
| (KW_FULLTEXT | KW_SPATIAL) (KW_INDEX | KW_KEY)? indexName? indexColumnNames indexOption*
| constraintSymbol? KW_PRIMARY KW_KEY indexType? indexColumnNames indexOption*
| constraintSymbol? KW_UNIQUE (KW_INDEX | KW_KEY)? indexName? indexType? indexColumnNames indexOption*
| constraintSymbol? KW_FOREIGN KW_KEY indexName? indexColumnNames referenceDefinition
| KW_CHECK '(' expression ')'
| checkConstraintDefinition
;
checkConstraintDefinition
: constraintSymbol? KW_CHECK '(' expression ')' (KW_NOT? KW_ENFORCED)?
;
constraintSymbol
: KW_CONSTRAINT symbol=uid?
;
columnDefinition
: colType=dataType columnConstraint*
;
columnConstraint
: nullNotNull # nullColumnConstraint
| KW_DEFAULT defaultValue # defaultColumnConstraint
| KW_VISIBLE # visibilityColumnConstraint
| KW_INVISIBLE # invisibilityColumnConstraint
| (KW_AUTO_INCREMENT | KW_ON KW_UPDATE currentTimestamp) # autoIncrementColumnConstraint
| KW_PRIMARY? KW_KEY # primaryKeyColumnConstraint
| KW_UNIQUE KW_KEY? # uniqueKeyColumnConstraint
| KW_COMMENT comment=STRING_LITERAL # commentColumnConstraint
| KW_COLUMN_FORMAT colformat=(KW_FIXED | KW_DYNAMIC | KW_DEFAULT) # formatColumnConstraint
| KW_STORAGE storageval=(KW_DISK | KW_MEMORY | KW_DEFAULT) # storageColumnConstraint
| referenceDefinition # referenceColumnConstraint
| KW_COLLATE collationName # collateColumnConstraint
| (KW_GENERATED KW_ALWAYS)? KW_AS '(' expression ')' (KW_VIRTUAL | KW_STORED)? # generatedColumnConstraint
| KW_SERIAL KW_DEFAULT KW_VALUE # serialDefaultColumnConstraint
| checkConstraintDefinition # checkExpr
;
referenceDefinition
: KW_REFERENCES tableName indexColumnNames? (
KW_MATCH matchType=(KW_FULL | KW_PARTIAL | KW_SIMPLE)
)? referenceAction?
;
referenceAction
: KW_ON KW_DELETE onDelete=referenceControlType (
KW_ON KW_UPDATE onUpdate=referenceControlType
)?
| KW_ON KW_UPDATE onUpdate=referenceControlType (
KW_ON KW_DELETE onDelete=referenceControlType
)?
;
referenceControlType
: KW_RESTRICT
| KW_CASCADE
| KW_SET KW_NULL_LITERAL
| KW_NO KW_ACTION
| KW_SET KW_DEFAULT
;
tableOption
: KW_ENGINE '='? engineName? # tableOptionEngine
| KW_ENGINE_ATTRIBUTE '='? STRING_LITERAL # tableOptionEngineAttribute
| KW_AUTOEXTEND_SIZE '='? decimalLiteral # tableOptionAutoExtendSize
| KW_AUTO_INCREMENT '='? decimalLiteral # tableOptionAutoIncrement
| KW_AVG_ROW_LENGTH '='? decimalLiteral # tableOptionAverage
| KW_DEFAULT? charSet '='? (charsetName | KW_DEFAULT) # tableOptionCharset
| (KW_CHECKSUM | KW_PAGE_CHECKSUM) '='? boolValue=('0' | '1') # tableOptionChecksum
| KW_DEFAULT? KW_COLLATE '='? collationName # tableOptionCollate
| KW_COMMENT '='? comment=STRING_LITERAL # tableOptionComment
| KW_COMPRESSION '='? (STRING_LITERAL | ID) # tableOptionCompression
| KW_CONNECTION '='? STRING_LITERAL # tableOptionConnection
| (KW_DATA | KW_INDEX) KW_DIRECTORY '='? STRING_LITERAL # tableOptionDataDirectory
| KW_DELAY_KEY_WRITE '='? boolValue=('0' | '1') # tableOptionDelay
| KW_ENCRYPTION '='? STRING_LITERAL # tableOptionEncryption
| (KW_PAGE_COMPRESSED | STRING_LITERAL) '='? ('0' | '1') # tableOptionPageCompressed
| (KW_PAGE_COMPRESSION_LEVEL | STRING_LITERAL) '='? decimalLiteral # tableOptionPageCompressionLevel
| KW_ENCRYPTION_KEY_ID '='? decimalLiteral # tableOptionEncryptionKeyId
| KW_INDEX KW_DIRECTORY '='? STRING_LITERAL # tableOptionIndexDirectory
| KW_INSERT_METHOD '='? insertMethod=(KW_NO | KW_FIRST | KW_LAST) # tableOptionInsertMethod
| KW_KEY_BLOCK_SIZE '='? fileSizeLiteral # tableOptionKeyBlockSize
| KW_MAX_ROWS '='? decimalLiteral # tableOptionMaxRows
| KW_MIN_ROWS '='? decimalLiteral # tableOptionMinRows
| KW_PACK_KEYS '='? extBoolValue=('0' | '1' | KW_DEFAULT) # tableOptionPackKeys
| KW_PASSWORD '='? STRING_LITERAL # tableOptionPassword
| KW_ROW_FORMAT '='? rowFormat=(
KW_DEFAULT
| KW_DYNAMIC
| KW_FIXED
| KW_COMPRESSED
| KW_REDUNDANT
| KW_COMPACT
| ID
) # tableOptionRowFormat
| KW_START KW_TRANSACTION # tableOptionStartTransaction
| KW_SECONDARY_ENGINE_ATTRIBUTE '='? STRING_LITERAL # tableOptionSecondaryEngineAttribute
| KW_STATS_AUTO_RECALC '='? extBoolValue=(KW_DEFAULT | '0' | '1') # tableOptionRecalculation
| KW_STATS_PERSISTENT '='? extBoolValue=(KW_DEFAULT | '0' | '1') # tableOptionPersistent
| KW_STATS_SAMPLE_PAGES '='? (KW_DEFAULT | decimalLiteral) # tableOptionSamplePage
| KW_TABLESPACE tableSpaceName tableSpaceStorage? # tableOptionTableSpace
| KW_TABLE_TYPE '=' tableType # tableOptionTableType
| tableSpaceStorage # tableOptionTableSpace
| KW_TRANSACTIONAL '='? ('0' | '1') # tableOptionTransactional
| KW_UNION '='? '(' tableNames ')' # tableOptionUnion
;
tableType
: KW_MYSQL
| KW_ODBC
;
tableSpaceStorage
: KW_STORAGE (KW_DISK | KW_MEMORY | KW_DEFAULT)
;
partitionDefinitions
: KW_PARTITION KW_BY partitionFunctionDefinition (KW_PARTITIONS count=decimalLiteral)? (
KW_SUBPARTITION KW_BY subpartitionFunctionDefinition (
KW_SUBPARTITIONS subCount=decimalLiteral
)?
)? ('(' partitionDefinition (',' partitionDefinition)* ')')?
;
partitionFunctionDefinition
: KW_LINEAR? KW_HASH '(' expression ')' # partitionFunctionHash
| KW_LINEAR? KW_KEY (KW_ALGORITHM '=' algType=('1' | '2'))? '(' columnNames? ')' # partitionFunctionKey
| KW_RANGE ('(' expression ')' | KW_COLUMNS '(' columnNames ')') # partitionFunctionRange
| KW_LIST ('(' expression ')' | KW_COLUMNS '(' columnNames ')') # partitionFunctionList
;
subpartitionFunctionDefinition
: KW_LINEAR? KW_HASH '(' expression ')' # subPartitionFunctionHash
| KW_LINEAR? KW_KEY (KW_ALGORITHM '=' algType=('1' | '2'))? '(' columnNames ')' # subPartitionFunctionKey
;
partitionDefinition
: KW_PARTITION partitionName KW_VALUES KW_LESS KW_THAN '(' partitionDefinerAtom (
',' partitionDefinerAtom
)* ')' partitionOption* ('(' subPartitionDefinition (',' subPartitionDefinition)* ')')? # partitionComparison
| KW_PARTITION partitionName KW_VALUES KW_LESS KW_THAN partitionDefinerAtom partitionOption* (
'(' subPartitionDefinition (',' subPartitionDefinition)* ')'
)? # partitionComparison
| KW_PARTITION partitionName KW_VALUES KW_IN '(' partitionDefinerAtom (
',' partitionDefinerAtom
)* ')' partitionOption* ('(' subPartitionDefinition (',' subPartitionDefinition)* ')')? # partitionListAtom
| KW_PARTITION partitionName KW_VALUES KW_IN '(' partitionDefinerVector (
',' partitionDefinerVector
)* ')' partitionOption* ('(' subPartitionDefinition (',' subPartitionDefinition)* ')')? # partitionListVector
| KW_PARTITION partitionName partitionOption* (
'(' subPartitionDefinition (',' subPartitionDefinition)* ')'
)? # partitionSimple
;
partitionDefinerAtom
: constant
| expression
| KW_MAXVALUE
;
partitionDefinerVector
: '(' partitionDefinerAtom (',' partitionDefinerAtom)+ ')'
;
subPartitionDefinition
: KW_SUBPARTITION logicalName=uid partitionOption*
;
partitionOption
: KW_DEFAULT? KW_STORAGE? KW_ENGINE '='? engineName # partitionOptionEngine
| KW_COMMENT '='? comment=STRING_LITERAL # partitionOptionComment
| KW_DATA KW_DIRECTORY '='? dataDirectory=STRING_LITERAL # partitionOptionDataDirectory
| KW_INDEX KW_DIRECTORY '='? indexDirectory=STRING_LITERAL # partitionOptionIndexDirectory
| KW_MAX_ROWS '='? maxRows=decimalLiteral # partitionOptionMaxRows
| KW_MIN_ROWS '='? minRows=decimalLiteral # partitionOptionMinRows
| KW_TABLESPACE '='? tableSpaceName # partitionOptionTableSpace
| KW_NODEGROUP '='? nodeGroup=uid # partitionOptionNodeGroup
;
// Alter statements
alterDatabase
: KW_ALTER dbFormat=(KW_DATABASE | KW_SCHEMA) databaseName? createDatabaseOption+ # alterSimpleDatabase
| KW_ALTER dbFormat=(KW_DATABASE | KW_SCHEMA) databaseName KW_UPGRADE KW_DATA KW_DIRECTORY KW_NAME # alterUpgradeName
;
alterEvent
: KW_ALTER ownerStatement? KW_EVENT event_name=fullId (KW_ON KW_SCHEDULE scheduleExpression)? (
KW_ON KW_COMPLETION KW_NOT? KW_PRESERVE
)? (KW_RENAME KW_TO new_event_name=fullId)? enableType? (KW_COMMENT STRING_LITERAL)? (
KW_DO routineBody
)?
;
alterFunction
: KW_ALTER KW_FUNCTION functionName routineOption*
;
alterInstance
: KW_ALTER KW_INSTANCE KW_ROTATE KW_INNODB KW_MASTER KW_KEY
;
alterLogFileGroup
: KW_ALTER KW_LOGFILE KW_GROUP logFileGroupName=uid KW_ADD KW_UNDOFILE STRING_LITERAL (
KW_INITIAL_SIZE '='? fileSizeLiteral
)? KW_WAIT? KW_ENGINE '='? engineName
;
alterProcedure
: KW_ALTER KW_PROCEDURE proc_name=fullId routineOption*
;
alterServer
: KW_ALTER KW_SERVER serverName=uid KW_OPTIONS '(' serverOption (',' serverOption)* ')'
;
alterTable
: KW_ALTER KW_TABLE tableName (alterOption (',' alterOption)*)? (
alterPartitionSpecification alterPartitionSpecification*
)?
;
alterTableSpace
: KW_ALTER KW_UNDO? KW_TABLESPACE tableSpaceName (KW_ADD | KW_DROP) KW_DATAFILE STRING_LITERAL (
KW_INITIAL_SIZE '='? fileSizeLiteral
)? KW_WAIT? (KW_RENAME KW_TO tableSpaceNameCreate)? (KW_AUTOEXTEND_SIZE '='? fileSizeLiteral)? (
KW_SET (KW_ACTIVE | KW_INACTIVE)
)? (KW_ENCRYPTION '='? STRING_LITERAL)? // STRING_LITERAL is 'Y' or 'N'
(KW_ENGINE '='? engineName)? (KW_ENGINE_ATTRIBUTE '='? STRING_LITERAL)?
;
alterView
: KW_ALTER (KW_ALGORITHM '=' algType=(KW_UNDEFINED | KW_MERGE | KW_TEMPTABLE))? ownerStatement? (
KW_SQL KW_SECURITY secContext=(KW_DEFINER | KW_INVOKER)
)? KW_VIEW viewName ('(' columnNames ')')? KW_AS selectStatement (
KW_WITH checkOpt=(KW_CASCADED | KW_LOCAL)? KW_CHECK KW_OPTION
)?
;
alterOption
: tableOption (','? tableOption)* # alterByTableOption
| KW_ADD KW_COLUMN? columnName columnDefinition (KW_FIRST | KW_AFTER columnName)? # alterByAddColumn
| KW_ADD KW_COLUMN? '(' columnName columnDefinition (',' columnName columnDefinition)* ')' # alterByAddColumns
| KW_ADD (KW_INDEX | KW_KEY) indexName? indexType? indexColumnNames indexOption* # alterByAddIndex
| KW_ADD (KW_FULLTEXT | KW_SPATIAL) (KW_INDEX | KW_KEY)? indexName? indexColumnNames indexOption* # alterByAddSpecialIndex
| KW_ADD (KW_CONSTRAINT symbol=uid?)? KW_PRIMARY KW_KEY indexType? indexColumnNames indexOption* # alterByAddPrimaryKey
| KW_ADD (KW_CONSTRAINT symbol=uid?)? KW_UNIQUE (KW_INDEX | KW_KEY)? indexName? indexType? indexColumnNames indexOption* # alterByAddUniqueKey
| KW_ADD (KW_CONSTRAINT symbol=uid?)? KW_FOREIGN KW_KEY indexName? indexColumnNames referenceDefinition # alterByAddForeignKey
| KW_ADD checkConstraintDefinition? # alterByAddCheckTableConstraint
| KW_DROP (KW_CHECK | KW_CONSTRAINT) symbol=uid # alterByDropConstraintCheck
| KW_ALTER (KW_CHECK | KW_CONSTRAINT) symbol=uid KW_NOT? KW_ENFORCED? # alterByAlterCheckTableConstraint
| KW_ALGORITHM '='? (KW_DEFAULT | KW_INSTANT | KW_INPLACE | KW_COPY) # alterBySetAlgorithm
| KW_ALTER KW_COLUMN? columnName (
KW_SET KW_DEFAULT defaultValue
| KW_SET (KW_VISIBLE | KW_INVISIBLE)
| KW_DROP KW_DEFAULT
) # alterByAlterColumnDefault
| KW_ALTER KW_INDEX indexName (KW_VISIBLE | KW_INVISIBLE) # alterByAlterIndexVisibility
| KW_CHANGE KW_COLUMN? oldColumn=columnName newColumn=columnNameCreate columnDefinition (
KW_FIRST
| KW_AFTER columnName
)? # alterByChangeColumn
| KW_DEFAULT? KW_CHARACTER KW_SET '=' charsetName (KW_COLLATE '='? collationName)? # alterByDefaultCharset
| KW_CONVERT KW_TO (KW_CHARSET | KW_CHARACTER KW_SET) charsetName (KW_COLLATE collationName)? # alterByConvertCharset
| (KW_DISABLE | KW_ENABLE) KW_KEYS # alterKeys
| (KW_DISCARD | KW_IMPORT) KW_TABLESPACE # alterTableSpaceOption
| KW_DROP KW_COLUMN? columnName # alterByDropColumn
| KW_DROP (KW_INDEX | KW_KEY) indexName # alterByDropIndex
| KW_DROP KW_PRIMARY KW_KEY # alterByDropPrimaryKey
| KW_DROP KW_FOREIGN KW_KEY fk_symbol=uid # alterByDropForeignKey
| KW_FORCE # alterByForce
| KW_LOCK '='? lockType=(KW_DEFAULT | KW_NONE | KW_SHARED | KW_EXCLUSIVE) # alterByLock
| KW_MODIFY KW_COLUMN? columnName columnDefinition (KW_FIRST | KW_AFTER columnName)? # alterByModifyColumn
| KW_ORDER KW_BY columnNames # alterByOrder
| KW_RENAME KW_COLUMN oldColumn=columnName KW_TO newColumn=columnNameCreate # alterByRenameColumn
| KW_RENAME indexFormat=(KW_INDEX | KW_KEY) indexName KW_TO indexNameCreate # alterByRenameIndex
| KW_RENAME renameFormat=(KW_TO | KW_AS)? tableNameCreate # alterByRename
| (KW_WITHOUT | KW_WITH) KW_VALIDATION # alterByValidate
| alterPartitionSpecification # alterPartition
;
alterPartitionSpecification
: KW_ADD KW_PARTITION '(' partitionDefinition (',' partitionDefinition)* ')' # alterByAddPartition
| KW_DROP KW_PARTITION partitionNames # alterByDropPartition
| KW_DISCARD KW_PARTITION (partitionNames | KW_ALL) KW_TABLESPACE # alterByDiscardPartition
| KW_IMPORT KW_PARTITION (partitionNames | KW_ALL) KW_TABLESPACE # alterByImportPartition
| KW_TRUNCATE KW_PARTITION (partitionNames | KW_ALL) # alterByTruncatePartition
| KW_COALESCE KW_PARTITION decimalLiteral # alterByCoalescePartition
| KW_REORGANIZE KW_PARTITION partitionNames KW_INTO '(' partitionDefinition (
',' partitionDefinition
)* ')' # alterByReorganizePartition
| KW_EXCHANGE KW_PARTITION partitionName KW_WITH KW_TABLE tableName (
validationFormat=(KW_WITH | KW_WITHOUT) KW_VALIDATION
)? # alterByExchangePartition
| KW_ANALYZE KW_PARTITION (partitionNames | KW_ALL) # alterByAnalyzePartition
| KW_CHECK KW_PARTITION (partitionNames | KW_ALL) # alterByCheckPartition
| KW_OPTIMIZE KW_PARTITION (partitionNames | KW_ALL) # alterByOptimizePartition
| KW_REBUILD KW_PARTITION (partitionNames | KW_ALL) # alterByRebuildPartition
| KW_REPAIR KW_PARTITION (partitionNames | KW_ALL) # alterByRepairPartition
| KW_REMOVE KW_PARTITIONING # alterByRemovePartitioning
| KW_UPGRADE KW_PARTITIONING # alterByUpgradePartitioning
;
dropDatabase
: KW_DROP dbFormat=(KW_DATABASE | KW_SCHEMA) ifExists? databaseName
;
dropEvent
: KW_DROP KW_EVENT ifExists? event_name=fullId
;
dropIndex
: KW_DROP KW_INDEX inTimeAction=(KW_ONLINE | KW_OFFLINE)? indexName KW_ON tableName (
KW_ALGORITHM '='? algType=(KW_DEFAULT | KW_INPLACE | KW_COPY)
| KW_LOCK '='? lockType=(KW_DEFAULT | KW_NONE | KW_SHARED | KW_EXCLUSIVE)
)*
;
dropLogFileGroup
: KW_DROP KW_LOGFILE KW_GROUP logFileGroupName=uid KW_ENGINE '='? engineName
;
dropProcedure
: KW_DROP KW_PROCEDURE ifExists? sp_name=fullId
;
dropFunction
: KW_DROP KW_FUNCTION ifExists? functionName
;
dropServer
: KW_DROP KW_SERVER ifExists? serverName=uid
;
dropSpatial
: KW_DROP KW_SPATIAL KW_REFERENCE KW_SYSTEM ifExists? DECIMAL_LITERAL
;
dropTable
: KW_DROP KW_TEMPORARY? KW_TABLE ifExists? tableNames dropType=(KW_RESTRICT | KW_CASCADE)?
;
dropTableSpace
: KW_DROP KW_UNDO? KW_TABLESPACE tableSpaceName (KW_ENGINE '='? engineName)?
;
dropTrigger
: KW_DROP KW_TRIGGER ifExists? trigger_name=fullId
;
dropView
: KW_DROP KW_VIEW ifExists? viewName (',' viewName)* dropType=(KW_RESTRICT | KW_CASCADE)?
;
dropRole
: KW_DROP KW_ROLE ifExists? userOrRoleNames
;
setRole
: KW_SET KW_DEFAULT KW_ROLE (KW_NONE | KW_ALL | userOrRoleNames) KW_TO (userOrRoleName) (
',' (userOrRoleName)
)*
| KW_SET KW_ROLE roleOption
;
renameTable
: KW_RENAME KW_TABLE renameTableClause (',' renameTableClause)*
;
renameTableClause
: tableName KW_TO tableNameCreate
;
truncateTable
: KW_TRUNCATE KW_TABLE? tableName
;
callStatement
: KW_CALL sp_name=fullId ('(' (constants | expressions)? ')')?
;
deleteStatement
: singleDeleteStatement
| multipleDeleteStatement
;
doStatement
: KW_DO expressions
;
handlerStatement
: handlerOpenStatement
| handlerReadIndexStatement
| handlerReadStatement
| handlerCloseStatement
;
insertStatement
: KW_INSERT priority=(KW_LOW_PRIORITY | KW_DELAYED | KW_HIGH_PRIORITY)? KW_IGNORE? KW_INTO? tableName (
KW_PARTITION '(' partitionNames? ')'
)? (
fullColumnNames? (valuesOrValueList | selectOrTableOrValues)? asRowAlias?
| setAssignmentList
) asRowAlias? (
KW_ON KW_DUPLICATE KW_KEY KW_UPDATE duplicatedFirst=updatedElement (
',' duplicatedElements+=updatedElement
)*
)?
;
asRowAlias
: KW_AS rowAlias=uid (fullColumnNames)?
;
selectOrTableOrValues
: selectStatement
| KW_TABLE tableName
| rowValuesList
;
interSectStatement
: interSectQuery (KW_INTERSECT (KW_ALL | KW_DISTINCT)? interSectQuery)+
;
interSectQuery
: '('? querySpecification ')'?
;
loadDataStatement
: KW_LOAD KW_DATA priority=(KW_LOW_PRIORITY | KW_CONCURRENT)? KW_LOCAL? KW_INFILE filename=STRING_LITERAL violation=(
KW_REPLACE
| KW_IGNORE
)? KW_INTO KW_TABLE tableName (KW_PARTITION '(' partitionNames ')')? (
KW_CHARACTER KW_SET charset=charsetName
)? (fieldsFormat=(KW_FIELDS | KW_COLUMNS) selectFieldsInto+)? (KW_LINES selectLinesInto+)? (
KW_IGNORE decimalLiteral linesFormat=(KW_LINES | KW_ROWS)
)? ('(' assignmentField (',' assignmentField)* ')')? (
KW_SET updatedElement (',' updatedElement)*
)?
;
loadXmlStatement
: KW_LOAD KW_XML priority=(KW_LOW_PRIORITY | KW_CONCURRENT)? KW_LOCAL? KW_INFILE filename=STRING_LITERAL violation=(
KW_REPLACE
| KW_IGNORE
)? KW_INTO KW_TABLE tableName (KW_CHARACTER KW_SET charset=charsetName)? (
KW_ROWS KW_IDENTIFIED KW_BY '<'? tag=STRING_LITERAL '>'?
)? (KW_IGNORE decimalLiteral linesFormat=(KW_LINES | KW_ROWS))? (
'(' assignmentField (',' assignmentField)* ')'
)? (KW_SET updatedElement (',' updatedElement)*)?
;
parenthesizedQuery
: '(' parenthesizedQueryExpression orderByClause? limitClause? ')' orderByClause? limitClause? intoClause?
;
replaceStatement
: KW_REPLACE priority=(KW_LOW_PRIORITY | KW_DELAYED)? KW_INTO? tableName (
KW_PARTITION '(' partitionNames ')'
)? (('(' columnNames ')')? replaceStatementValuesOrSelectOrTable | setAssignmentList)
;
// TODO: Simplify the rules to fit SLL(*) Mode
selectStatement
: querySpecification unionStatement* (
KW_UNION unionType=(KW_ALL | KW_DISTINCT)? (querySpecification | queryExpression)
)? (',' lateralStatement)* orderByClause? limitClause? lockClause? intoClause? # unionAndLateralSelect
| queryExpression unionStatement* (
KW_UNION unionType=(KW_ALL | KW_DISTINCT)? queryExpression
)? orderByClause? limitClause? lockClause? # selectExpression
;
// https://dev.mysql.com/doc/refman/8.0/en/set-operations.html
setOperations
: withClause? queryExpressionBody orderByClause? limitClause? intoClause?
;
queryExpressionBody
: queryItem
| queryExpressionBody KW_UNION (KW_ALL | KW_DISTINCT)? queryItem
| queryExpressionBody KW_EXCEPT (KW_ALL | KW_DISTINCT)? queryItem
;
queryItem
: queryPrimary
| queryItem KW_INTERSECT (KW_ALL | KW_DISTINCT)? queryPrimary
;
queryPrimary
: queryBlock
| '(' queryExpressionBody orderByClause? limitClause? intoClause? ')'
;
updateStatement
: singleUpdateStatement
| multipleUpdateStatement
;
// https://dev.mysql.com/doc/refman/8.0/en/values.html
valuesStatement
: rowValuesList (KW_ORDER KW_BY indexColumnName)? (KW_LIMIT limitClauseAtom)?
;
// Detailed DML Statements
parenthesizedQueryExpression
: queryBlock ((KW_UNION | KW_INTERSECT | KW_EXCEPT) queryBlock)* orderByClause? limitClause? intoClause?
;
queryBlock
: selectStatement
| tableStatement
| valuesStatement
;
replaceStatementValuesOrSelectOrTable
: selectStatement
| KW_TABLE tableName
| valuesOrValueList
| rowValuesList
;
rowValuesList
: KW_VALUES KW_ROW expressionsWithDefaults (',' KW_ROW expressionsWithDefaults)*
;
setAssignmentList
: KW_SET setFirst=updatedElement (',' setElements+=updatedElement)*
;
updatedElement
: columnName '=' expressionOrDefault