-
Notifications
You must be signed in to change notification settings - Fork 548
/
SqlBaseParser.g4
819 lines (699 loc) · 32.6 KB
/
SqlBaseParser.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
/*
* Licensed to Crate.io GmbH ("Crate") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Crate licenses
* this file to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial agreement.
*/
parser grammar SqlBaseParser;
options { tokenVocab=SqlBaseLexer; } // use tokens from SqlBaseLexer.g4
statements
: statement (SEMICOLON statement)* SEMICOLON? EOF
;
singleStatement
: statement SEMICOLON? EOF
;
singleExpression
: expr EOF
;
statement
: query #default
| BEGIN (WORK | TRANSACTION)? (transactionMode (COMMA? transactionMode)*)? #begin
| START TRANSACTION (transactionMode (COMMA? transactionMode)*)? #startTransaction
| COMMIT (WORK | TRANSACTION)? #commit
| END (WORK | TRANSACTION)? #commit
| EXPLAIN (ANALYZE)? statement #explain
| OPTIMIZE TABLE tableWithPartitions withProperties? #optimize
| REFRESH TABLE tableWithPartitions #refreshTable
| UPDATE aliasedRelation
SET assignment (COMMA assignment)*
where?
returning? #update
| DELETE FROM aliasedRelation where? #delete
| SHOW (TRANSACTION ISOLATION LEVEL | TRANSACTION_ISOLATION) #showTransaction
| SHOW CREATE TABLE table #showCreateTable
| SHOW TABLES ((FROM | IN) qname)? (LIKE pattern=stringLiteral | where)? #showTables
| SHOW SCHEMAS (LIKE pattern=stringLiteral | where)? #showSchemas
| SHOW COLUMNS (FROM | IN) tableName=qname ((FROM | IN) schema=qname)?
(LIKE pattern=stringLiteral | where)? #showColumns
| SHOW (qname | ALL) #showSessionParameter
| alterStmt #alter
| RESET GLOBAL primaryExpression (COMMA primaryExpression)* #resetGlobal
| SET (SESSION CHARACTERISTICS AS)? TRANSACTION
transactionMode (COMMA transactionMode)* #setTransaction
| SET (SESSION | LOCAL)? SESSION AUTHORIZATION
(DEFAULT | username=stringLiteralOrIdentifier) #setSessionAuthorization
| RESET SESSION AUTHORIZATION #resetSessionAuthorization
| SET (SESSION | LOCAL)? qname
(EQ | TO) (DEFAULT | setExpr (COMMA setExpr)*) #set
| SET GLOBAL (PERSISTENT | TRANSIENT)?
setGlobalAssignment (COMMA setGlobalAssignment)* #setGlobal
| SET TIME ZONE (LOCAL | DEFAULT | stringLiteral) #setTimeZone
| KILL (ALL | jobId=parameterOrString) #kill
| INSERT INTO table
(OPEN_ROUND_BRACKET ident (COMMA ident)* CLOSE_ROUND_BRACKET)?
insertSource onConflict? returning? #insert
| RESTORE SNAPSHOT qname
(ALL | METADATA | TABLE tableWithPartitions | metatypes=idents)
withProperties? #restore
| COPY tableWithPartition
(OPEN_ROUND_BRACKET ident (COMMA ident)* CLOSE_ROUND_BRACKET)?
FROM path=expr withProperties? (RETURN SUMMARY)? #copyFrom
| COPY tableWithPartition columns? where?
TO DIRECTORY? path=expr withProperties? #copyTo
| dropStmt #drop
| GRANT (priviliges=idents | ALL PRIVILEGES?)
(ON clazz qnames)? TO users=idents #grantPrivilege
| DENY (priviliges=idents | ALL PRIVILEGES?)
(ON clazz qnames)? TO users=idents #denyPrivilege
| REVOKE (privileges=idents | ALL PRIVILEGES?)
(ON clazz qnames)? FROM users=idents #revokePrivilege
| createStmt #create
| DEALLOCATE (PREPARE)? (ALL | prepStmt=stringLiteralOrIdentifierOrQname) #deallocate
| ANALYZE #analyze
| DISCARD (ALL | PLANS | SEQUENCES | TEMPORARY | TEMP) #discard
| DECLARE ident declareCursorParams
CURSOR ((WITH | WITHOUT) HOLD)? FOR queryNoWith #declare
| FETCH (direction)? (IN | FROM)? ident #fetch
| CLOSE (ident | ALL) #close
;
dropStmt
: DROP BLOB TABLE (IF EXISTS)? table #dropBlobTable
| DROP TABLE (IF EXISTS)? table #dropTable
| DROP ALIAS qname #dropAlias
| DROP REPOSITORY ident #dropRepository
| DROP SNAPSHOT qname #dropSnapshot
| DROP FUNCTION (IF EXISTS)? name=qname
OPEN_ROUND_BRACKET (functionArgument (COMMA functionArgument)*)?
CLOSE_ROUND_BRACKET #dropFunction
| DROP USER (IF EXISTS)? name=ident #dropUser
| DROP VIEW (IF EXISTS)? names=qnames #dropView
| DROP ANALYZER name=ident #dropAnalyzer
| DROP PUBLICATION (IF EXISTS)? name=ident #dropPublication
| DROP SUBSCRIPTION (IF EXISTS)? name=ident #dropSubscription
;
alterStmt
: ALTER TABLE alterTableDefinition addColumnDefinition
(COMMA addColumnDefinition)* #addColumn
| ALTER TABLE alterTableDefinition DROP CONSTRAINT ident #dropCheckConstraint
| ALTER TABLE alterTableDefinition
(SET OPEN_ROUND_BRACKET genericProperties CLOSE_ROUND_BRACKET
| RESET (OPEN_ROUND_BRACKET ident (COMMA ident)* CLOSE_ROUND_BRACKET)?) #alterTableProperties
| ALTER BLOB TABLE alterTableDefinition
(SET OPEN_ROUND_BRACKET genericProperties CLOSE_ROUND_BRACKET
| RESET (OPEN_ROUND_BRACKET ident (COMMA ident)* CLOSE_ROUND_BRACKET)?) #alterBlobTableProperties
| ALTER (BLOB)? TABLE alterTableDefinition (OPEN | CLOSE) #alterTableOpenClose
| ALTER (BLOB)? TABLE alterTableDefinition RENAME TO qname #alterTableRename
| ALTER (BLOB)? TABLE alterTableDefinition REROUTE rerouteOption #alterTableReroute
| ALTER CLUSTER REROUTE RETRY FAILED #alterClusterRerouteRetryFailed
| ALTER CLUSTER SWAP TABLE source=qname TO target=qname withProperties? #alterClusterSwapTable
| ALTER CLUSTER DECOMMISSION node=expr #alterClusterDecommissionNode
| ALTER CLUSTER GC DANGLING ARTIFACTS #alterClusterGCDanglingArtifacts
| ALTER USER name=ident
SET OPEN_ROUND_BRACKET genericProperties CLOSE_ROUND_BRACKET #alterUser
| ALTER PUBLICATION name=ident
((ADD | SET | DROP) TABLE qname ASTERISK? (COMMA qname ASTERISK? )*) #alterPublication
| ALTER SUBSCRIPTION name=ident alterSubscriptionMode #alterSubscription
;
queryOptParens
: OPEN_ROUND_BRACKET query CLOSE_ROUND_BRACKET
| query
| OPEN_ROUND_BRACKET queryOptParens CLOSE_ROUND_BRACKET
;
query
: with? queryNoWith
;
queryNoWith
: queryTerm
(ORDER BY sortItem (COMMA sortItem)*)?
(limitClause? offsetClause? | offsetClause? limitClause?)
;
limitClause
: LIMIT (limit=parameterOrInteger | ALL)
| FETCH (FIRST | NEXT) (limit=parameterOrInteger) (ROW | ROWS) ONLY
;
offsetClause
: OFFSET offset=parameterOrInteger (ROW | ROWS)?
;
queryTerm
: querySpec #queryTermDefault
| first=querySpec operator=(INTERSECT | EXCEPT) second=querySpec #setOperation
| left=queryTerm operator=UNION setQuant? right=queryTerm #setOperation
;
setQuant
: DISTINCT
| ALL
;
sortItem
: expr ordering=(ASC | DESC)? (NULLS nullOrdering=(FIRST | LAST))?
;
querySpec
: SELECT setQuant? selectItem (COMMA selectItem)*
(FROM relation (COMMA relation)*)?
where?
(GROUP BY expr (COMMA expr)*)?
(HAVING having=booleanExpression)?
(WINDOW windows+=namedWindow (COMMA windows+=namedWindow)*)? #defaultQuerySpec
| VALUES values (COMMA values)* #valuesRelation
;
selectItem
: expr (AS? ident)? #selectSingle
| qname DOT ASTERISK #selectAll
| ASTERISK #selectAll
;
where
: WHERE condition=booleanExpression
;
returning
: RETURNING selectItem (COMMA selectItem)*
;
filter
: FILTER OPEN_ROUND_BRACKET where CLOSE_ROUND_BRACKET
;
relation
: left=relation
( CROSS JOIN right=aliasedRelation
| joinType JOIN rightRelation=relation joinCriteria
| NATURAL joinType JOIN right=aliasedRelation
) #joinRelation
| aliasedRelation #relationDefault
;
joinType
: INNER?
| LEFT OUTER?
| RIGHT OUTER?
| FULL OUTER?
;
joinCriteria
: ON booleanExpression
| USING OPEN_ROUND_BRACKET ident (COMMA ident)* CLOSE_ROUND_BRACKET
;
aliasedRelation
: relationPrimary (AS? ident aliasedColumns?)?
;
relationPrimary
: table #tableRelation
| OPEN_ROUND_BRACKET query CLOSE_ROUND_BRACKET #subqueryRelation
| OPEN_ROUND_BRACKET relation CLOSE_ROUND_BRACKET #parenthesizedRelation
;
tableWithPartition
: qname ( PARTITION OPEN_ROUND_BRACKET assignment ( COMMA assignment )* CLOSE_ROUND_BRACKET)?
;
table
: qname #tableName
| qname OPEN_ROUND_BRACKET
valueExpression? (COMMA valueExpression)* CLOSE_ROUND_BRACKET #tableFunction
;
aliasedColumns
: OPEN_ROUND_BRACKET ident (COMMA ident)* CLOSE_ROUND_BRACKET
;
with
: WITH namedQuery (COMMA namedQuery)*
;
namedQuery
: name=ident (aliasedColumns)? AS OPEN_ROUND_BRACKET query CLOSE_ROUND_BRACKET
;
expr
: booleanExpression
;
booleanExpression
: predicated #booleanDefault
| NOT booleanExpression #logicalNot
| left=booleanExpression operator=AND right=booleanExpression #logicalBinary
| left=booleanExpression operator=OR right=booleanExpression #logicalBinary
| MATCH OPEN_ROUND_BRACKET matchPredicateIdents
COMMA term=primaryExpression CLOSE_ROUND_BRACKET
(USING matchType=ident withProperties?)? #match
;
predicated
: valueExpression predicate[$valueExpression.ctx]?
;
predicate[ParserRuleContext value]
: cmpOp right=valueExpression #comparison
| cmpOp setCmpQuantifier primaryExpression #quantifiedComparison
| NOT? BETWEEN lower=valueExpression AND upper=valueExpression #between
| NOT? IN OPEN_ROUND_BRACKET expr (COMMA expr)* CLOSE_ROUND_BRACKET #inList
| NOT? IN subqueryExpression #inSubquery
| NOT? (LIKE | ILIKE) pattern=valueExpression (ESCAPE escape=valueExpression)? #like
| NOT? (LIKE | ILIKE) quant=setCmpQuantifier
OPEN_ROUND_BRACKET v=valueExpression CLOSE_ROUND_BRACKET
(ESCAPE escape=valueExpression)? #arrayLike
| IS NOT? NULL #nullPredicate
| IS NOT? DISTINCT FROM right=valueExpression #distinctFrom
;
valueExpression
: primaryExpression #valueExpressionDefault
| operator=(MINUS | PLUS) valueExpression #arithmeticUnary
| left=valueExpression operator=(ASTERISK | SLASH | PERCENT)
right=valueExpression #arithmeticBinary
| left=valueExpression operator=(PLUS | MINUS) right=valueExpression #arithmeticBinary
| left=valueExpression operator=(BITWISE_AND | BITWISE_OR | BITWISE_XOR)
right=valueExpression #bitwiseBinary
| left=valueExpression CONCAT right=valueExpression #concatenation
| dataType stringLiteral #fromStringLiteralCast
;
primaryExpression
: parameterOrLiteral #defaultParamOrLiteral
| explicitFunction #explicitFunctionDefault
| qname OPEN_ROUND_BRACKET ASTERISK CLOSE_ROUND_BRACKET filter? over? #functionCall
| ident #columnReference
| qname OPEN_ROUND_BRACKET (setQuant? expr (COMMA expr)*)? CLOSE_ROUND_BRACKET filter?
((IGNORE|RESPECT) NULLS)? over? #functionCall
| subqueryExpression #subqueryExpressionDefault
| OPEN_ROUND_BRACKET base=primaryExpression CLOSE_ROUND_BRACKET
DOT fieldName=ident #recordSubscript
| OPEN_ROUND_BRACKET expr CLOSE_ROUND_BRACKET #nestedExpression
// This is an extension to ANSI SQL, which considers EXISTS to be a <boolean expression>
| EXISTS OPEN_ROUND_BRACKET query CLOSE_ROUND_BRACKET #exists
| value=primaryExpression
OPEN_SQUARE_BRACKET index=valueExpression CLOSE_SQUARE_BRACKET #subscript
| base=primaryExpression
OPEN_SQUARE_BRACKET (from=valueExpression)? COLON
(to=valueExpression)? CLOSE_SQUARE_BRACKET #arraySlice
| ident (DOT ident)* #dereference
| primaryExpression CAST_OPERATOR dataType #doubleColonCast
| timestamp=primaryExpression AT TIME ZONE zone=primaryExpression #atTimezone
| ARRAY? EMPTY_SQUARE_BRACKET #emptyArray
;
explicitFunction
: name=CURRENT_DATE #specialDateTimeFunction
| name=CURRENT_TIME
(OPEN_ROUND_BRACKET precision=integerLiteral CLOSE_ROUND_BRACKET)? #specialDateTimeFunction
| name=CURRENT_TIMESTAMP
(OPEN_ROUND_BRACKET precision=integerLiteral CLOSE_ROUND_BRACKET)? #specialDateTimeFunction
| CURRENT_SCHEMA #currentSchema
| (CURRENT_USER | USER) #currentUser
| SESSION_USER #sessionUser
| LEFT OPEN_ROUND_BRACKET strOrColName=expr COMMA len=expr CLOSE_ROUND_BRACKET #left
| RIGHT OPEN_ROUND_BRACKET strOrColName=expr COMMA len=expr CLOSE_ROUND_BRACKET #right
| SUBSTRING OPEN_ROUND_BRACKET expr FROM expr (FOR expr)? CLOSE_ROUND_BRACKET #substring
| TRIM OPEN_ROUND_BRACKET ((trimMode=(LEADING | TRAILING | BOTH))?
(charsToTrim=expr)? FROM)? target=expr CLOSE_ROUND_BRACKET #trim
| EXTRACT OPEN_ROUND_BRACKET stringLiteralOrIdentifier FROM
expr CLOSE_ROUND_BRACKET #extract
| CAST OPEN_ROUND_BRACKET expr AS dataType CLOSE_ROUND_BRACKET #cast
| TRY_CAST OPEN_ROUND_BRACKET expr AS dataType CLOSE_ROUND_BRACKET #cast
| CASE operand=expr whenClause+ (ELSE elseExpr=expr)? END #simpleCase
| CASE whenClause+ (ELSE elseExpr=expr)? END #searchedCase
| IF OPEN_ROUND_BRACKET condition=expr COMMA trueValue=expr
(COMMA falseValue=expr)? CLOSE_ROUND_BRACKET #ifCase
| ARRAY subqueryExpression #arraySubquery
;
subqueryExpression
: OPEN_ROUND_BRACKET query CLOSE_ROUND_BRACKET
;
parameterOrLiteral
: parameterOrSimpleLiteral #simpleLiteral
| ARRAY? OPEN_SQUARE_BRACKET (expr (COMMA expr)*)?
CLOSE_SQUARE_BRACKET #arrayLiteral
| OPEN_CURLY_BRACKET (objectKeyValue (COMMA objectKeyValue)*)?
CLOSE_CURLY_BRACKET #objectLiteral
;
parameterOrSimpleLiteral
: nullLiteral
| intervalLiteral
| escapedCharsStringLiteral
| stringLiteral
| numericLiteral
| booleanLiteral
| bitString
| parameterExpr
;
parameterOrInteger
: parameterExpr #parameterExpression
| integerLiteral #intAsLiteral
| nullLiteral #nullAsLiteral
| parameterOrLiteral CAST_OPERATOR dataType #integerParamOrLiteralDoubleColonCast
| CAST OPEN_ROUND_BRACKET expr AS dataType CLOSE_ROUND_BRACKET #integerParamOrLiteralCast
| TRY_CAST OPEN_ROUND_BRACKET expr AS dataType CLOSE_ROUND_BRACKET #integerParamOrLiteralCast
;
parameterOrIdent
: parameterExpr
| ident
;
parameterOrString
: parameterExpr
| stringLiteral
;
parameterExpr
: DOLLAR integerLiteral #positionalParameter
| QUESTION #parameterPlaceholder
;
nullLiteral
: NULL
;
escapedCharsStringLiteral
: ESCAPED_STRING
;
dollarQuotedStringLiteral
: BEGIN_DOLLAR_QUOTED_STRING DOLLAR_QUOTED_STRING_BODY* END_DOLLAR_QUOTED_STRING
;
stringLiteral
: STRING
| dollarQuotedStringLiteral
;
bitString
: BIT_STRING
;
subscriptSafe
: value=subscriptSafe OPEN_SQUARE_BRACKET index=valueExpression CLOSE_SQUARE_BRACKET
| qname
;
cmpOp
: EQ | NEQ | LT | LTE | GT | GTE | LLT | REGEX_MATCH | REGEX_NO_MATCH | REGEX_MATCH_CI | REGEX_NO_MATCH_CI
;
setCmpQuantifier
: ANY | SOME | ALL
;
whenClause
: WHEN condition=expr THEN result=expr
;
namedWindow
: name=ident AS windowDefinition
;
over
: OVER windowDefinition
;
windowDefinition
: windowRef=ident
| OPEN_ROUND_BRACKET
(windowRef=ident)?
(PARTITION BY partition+=expr (COMMA partition+=expr)*)?
(ORDER BY sortItem (COMMA sortItem)*)?
windowFrame?
CLOSE_ROUND_BRACKET
;
windowFrame
: frameType=RANGE start=frameBound
| frameType=ROWS start=frameBound
| frameType=RANGE BETWEEN start=frameBound AND end=frameBound
| frameType=ROWS BETWEEN start=frameBound AND end=frameBound
;
frameBound
: UNBOUNDED boundType=PRECEDING #unboundedFrame
| UNBOUNDED boundType=FOLLOWING #unboundedFrame
| CURRENT ROW #currentRowBound
| expr boundType=(PRECEDING | FOLLOWING) #boundedFrame
;
qnames
: qname (COMMA qname)*
;
qname
: ident (DOT ident)*
;
idents
: ident (COMMA ident)*
;
ident
: unquotedIdent
| quotedIdent
;
unquotedIdent
: IDENTIFIER #unquotedIdentifier
| nonReserved #unquotedIdentifier
| DIGIT_IDENTIFIER #digitIdentifier // not supported
;
quotedIdent
: QUOTED_IDENTIFIER #quotedIdentifier
| BACKQUOTED_IDENTIFIER #backQuotedIdentifier // not supported
;
stringLiteralOrIdentifier
: ident
| stringLiteral
;
stringLiteralOrIdentifierOrQname
: ident
| qname
| stringLiteral
;
numericLiteral
: decimalLiteral
| integerLiteral
;
intervalLiteral
: INTERVAL sign=(PLUS | MINUS)? stringLiteral from=intervalField (TO to=intervalField)?
;
intervalField
: YEAR | MONTH | DAY | HOUR | MINUTE | SECOND
;
booleanLiteral
: TRUE
| FALSE
;
decimalLiteral
: DECIMAL_VALUE
;
integerLiteral
: INTEGER_VALUE
;
objectKeyValue
: key=ident EQ value=expr
;
insertSource
: query
| OPEN_ROUND_BRACKET query CLOSE_ROUND_BRACKET
;
onConflict
: ON CONFLICT conflictTarget? DO NOTHING
| ON CONFLICT conflictTarget DO UPDATE SET assignment (COMMA assignment)*
;
conflictTarget
: OPEN_ROUND_BRACKET subscriptSafe (COMMA subscriptSafe)* CLOSE_ROUND_BRACKET
;
values
: OPEN_ROUND_BRACKET expr (COMMA expr)* CLOSE_ROUND_BRACKET
;
columns
: OPEN_ROUND_BRACKET primaryExpression (COMMA primaryExpression)* CLOSE_ROUND_BRACKET
;
assignment
: primaryExpression EQ expr
;
createStmt
: CREATE TABLE (IF NOT EXISTS)? table
OPEN_ROUND_BRACKET tableElement (COMMA tableElement)* CLOSE_ROUND_BRACKET
partitionedByOrClusteredInto withProperties? #createTable
| CREATE TABLE table AS insertSource #createTableAs
| CREATE BLOB TABLE table numShards=blobClusteredInto? withProperties? #createBlobTable
| CREATE REPOSITORY name=ident TYPE type=ident withProperties? #createRepository
| CREATE SNAPSHOT qname (ALL | TABLE tableWithPartitions) withProperties? #createSnapshot
| CREATE ANALYZER name=ident (EXTENDS extendedName=ident)?
WITH? OPEN_ROUND_BRACKET analyzerElement
( COMMA analyzerElement )* CLOSE_ROUND_BRACKET #createAnalyzer
| CREATE (OR REPLACE)? FUNCTION name=qname
OPEN_ROUND_BRACKET (functionArgument (COMMA functionArgument)*)?
CLOSE_ROUND_BRACKET
RETURNS returnType=dataType
LANGUAGE language=parameterOrIdent
AS body=parameterOrString #createFunction
| CREATE USER name=ident withProperties? #createUser
| CREATE ( OR REPLACE )? VIEW name=qname AS queryOptParens #createView
| CREATE PUBLICATION name=ident
(FOR ALL TABLES | FOR TABLE qname ASTERISK? (COMMA qname ASTERISK? )*)? #createPublication
| CREATE SUBSCRIPTION name=ident CONNECTION conninfo=expr
PUBLICATION publications=idents
withProperties? #createSubscription
;
functionArgument
: (name=ident)? type=dataType
;
alterTableDefinition
: ONLY qname #tableOnly
| tableWithPartition #tableWithPartitionDefault
;
alterSubscriptionMode
: ENABLE
| DISABLE
;
partitionedByOrClusteredInto
: partitionedBy? clusteredBy?
| clusteredBy? partitionedBy?
;
partitionedBy
: PARTITIONED BY columns
;
clusteredBy
: CLUSTERED (BY OPEN_ROUND_BRACKET routing=primaryExpression CLOSE_ROUND_BRACKET)?
(INTO numShards=parameterOrInteger SHARDS)?
;
blobClusteredInto
: CLUSTERED INTO numShards=parameterOrInteger SHARDS
;
tableElement
: columnDefinition #columnDefinitionDefault
| PRIMARY_KEY columns #primaryKeyConstraint
| INDEX name=ident USING method=ident columns withProperties? #indexDefinition
| checkConstraint #tableCheckConstraint
;
columnDefinition
: ident dataType? (DEFAULT defaultExpr=expr)? ((GENERATED ALWAYS)? AS generatedExpr=expr)? columnConstraint*
;
addColumnDefinition
: ADD COLUMN? subscriptSafe dataType? ((GENERATED ALWAYS)? AS expr)? columnConstraint*
;
rerouteOption
: MOVE SHARD shardId=parameterOrInteger FROM fromNodeId=parameterOrString TO toNodeId=parameterOrString #rerouteMoveShard
| ALLOCATE REPLICA SHARD shardId=parameterOrInteger ON nodeId=parameterOrString #rerouteAllocateReplicaShard
| PROMOTE REPLICA SHARD shardId=parameterOrInteger ON nodeId=parameterOrString withProperties? #reroutePromoteReplica
| CANCEL SHARD shardId=parameterOrInteger ON nodeId=parameterOrString withProperties? #rerouteCancelShard
;
dataType
: baseDataType
(OPEN_ROUND_BRACKET integerLiteral (COMMA integerLiteral )* CLOSE_ROUND_BRACKET)? #maybeParametrizedDataType
| objectTypeDefinition #objectDataType
| ARRAY OPEN_ROUND_BRACKET dataType CLOSE_ROUND_BRACKET #arrayDataType
| dataType EMPTY_SQUARE_BRACKET #arrayDataType
;
baseDataType
: definedDataType #definedDataTypeDefault
| ident #identDataType
;
definedDataType
: DOUBLE PRECISION
| TIMESTAMP WITHOUT TIME ZONE
| TIMESTAMP WITH TIME ZONE
| TIME WITH TIME ZONE
| CHARACTER VARYING
| CHAR_SPECIAL
;
objectTypeDefinition
: OBJECT (OPEN_ROUND_BRACKET type=(DYNAMIC | STRICT | IGNORED) CLOSE_ROUND_BRACKET)?
(AS OPEN_ROUND_BRACKET columnDefinition ( COMMA columnDefinition )* CLOSE_ROUND_BRACKET)?
;
columnConstraint
: PRIMARY_KEY #columnConstraintPrimaryKey
| NOT NULL #columnConstraintNotNull
| INDEX USING method=ident withProperties? #columnIndexConstraint
| INDEX OFF #columnIndexOff
| STORAGE withProperties #columnStorageDefinition
| checkConstraint #columnCheckConstraint
;
checkConstraint
: (CONSTRAINT name=ident)? CHECK
OPEN_ROUND_BRACKET expression=booleanExpression CLOSE_ROUND_BRACKET
;
withProperties
: WITH OPEN_ROUND_BRACKET genericProperties CLOSE_ROUND_BRACKET #withGenericProperties
;
genericProperties
: genericProperty (COMMA genericProperty)*
;
genericProperty
: ident EQ expr
;
matchPredicateIdents
: matchPred=matchPredicateIdent
| OPEN_ROUND_BRACKET matchPredicateIdent (COMMA matchPredicateIdent)*
CLOSE_ROUND_BRACKET
;
matchPredicateIdent
: subscriptSafe boost=parameterOrSimpleLiteral?
;
analyzerElement
: tokenizer
| tokenFilters
| charFilters
| genericProperty
;
tokenizer
: TOKENIZER namedProperties
;
tokenFilters
: TOKEN_FILTERS OPEN_ROUND_BRACKET namedProperties (COMMA namedProperties )*
CLOSE_ROUND_BRACKET
;
charFilters
: CHAR_FILTERS OPEN_ROUND_BRACKET namedProperties (COMMA namedProperties )*
CLOSE_ROUND_BRACKET
;
namedProperties
: ident withProperties?
;
tableWithPartitions
: tableWithPartition (COMMA tableWithPartition)*
;
setGlobalAssignment
: name=primaryExpression (EQ | TO) value=expr
;
setExpr
: stringLiteral
| booleanLiteral
| numericLiteral
| ident
| on
;
on
: ON
;
clazz
: SCHEMA
| TABLE
| VIEW
;
transactionMode
: ISOLATION LEVEL isolationLevel
| (READ WRITE | READ ONLY)
| (NOT)? DEFERRABLE
;
isolationLevel
: SERIALIZABLE
| REPEATABLE READ
| READ COMMITTED
| READ UNCOMMITTED
;
direction
: NEXT
| PRIOR
| FIRST
| LAST
| ABSOLUTE integerLiteral
| RELATIVE (MINUS)? integerLiteral
| integerLiteral
| ALL
| FORWARD
| FORWARD integerLiteral
| FORWARD ALL
| BACKWARD
| BACKWARD integerLiteral
| BACKWARD ALL
;
// https://www.postgresql.org/docs/current/sql-declare.html
// The key words ASENSITIVE, BINARY, INSENSITIVE, and SCROLL can appear in any order.
declareCursorParams
: (ASENSITIVE | BINARY | INSENSITIVE | (NO)? SCROLL)*
;
nonReserved
: ALIAS | ANALYZE | ANALYZER | AT | AUTHORIZATION | BERNOULLI | BLOB | CATALOGS | CHAR_FILTERS | CHECK | CLUSTERED
| COLUMNS | COPY | CURRENT | DAY | DEALLOCATE | DISTRIBUTED | DUPLICATE | DYNAMIC | EXPLAIN
| EXTENDS | FETCH | FOLLOWING | FORMAT | FULLTEXT | FUNCTIONS | GEO_POINT | GEO_SHAPE | GLOBAL
| GRAPHVIZ | HOUR | IGNORED | IGNORE | RESPECT | ILIKE | INTERVAL | KEY | KILL | LOGICAL | LOCAL
| MATERIALIZED | MINUTE | MONTH | NEXT | OFF | ONLY | OVER | OPTIMIZE | PARTITION | PARTITIONED
| PARTITIONS | PLAIN | PRECEDING | RANGE | REFRESH | ROW | ROWS | SCHEMAS | SECOND | SESSION
| SHARDS | SHOW | STORAGE | STRICT | SYSTEM | TABLES | TABLESAMPLE | TEXT | TIME | ZONE | WITHOUT
| TIMESTAMP | TO | TOKENIZER | TOKEN_FILTERS | TYPE | VALUES | VIEW | YEAR
| REPOSITORY | SNAPSHOT | RESTORE | GENERATED | ALWAYS | BEGIN | START | COMMIT
| ISOLATION | TRANSACTION | CHARACTERISTICS | LEVEL | LANGUAGE | OPEN | CLOSE | RENAME
| PRIVILEGES | SCHEMA | PREPARE
| REROUTE | MOVE | SHARD | ALLOCATE | REPLICA | CANCEL | CLUSTER | RETRY | FAILED | FILTER
| DO | NOTHING | CONFLICT | TRANSACTION_ISOLATION | RETURN | SUMMARY
| WORK | SERIALIZABLE | REPEATABLE | COMMITTED | UNCOMMITTED | READ | WRITE | WINDOW | DEFERRABLE
| STRING_TYPE | IP | DOUBLE | FLOAT | TIMESTAMP | LONG | INT | INTEGER | SHORT | BYTE | BOOLEAN | PRECISION
| REPLACE | RETURNING | SWAP | GC | DANGLING | ARTIFACTS | DECOMMISSION | LEADING | TRAILING | BOTH | TRIM
| CURRENT_SCHEMA | PROMOTE | CHARACTER | VARYING | SUBSTRING
| DISCARD | PLANS | SEQUENCES | TEMPORARY | TEMP | METADATA
| PUBLICATION | SUBSCRIPTION | ENABLE | DISABLE | CONNECTION | DECLARE | CURSOR | HOLD | FORWARD | BACKWARD
| RELATIVE | PRIOR | ASENSITIVE | INSENSITIVE | BINARY | NO | SCROLL | ABSOLUTE
;