Repository navigation
Expand file tree
/
Copy pathTrinoSql.g4
More file actions
1714 lines (1517 loc) · 58.1 KB
/
Copy pathTrinoSql.g4
File metadata and controls
1714 lines (1517 loc) · 58.1 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
/*
* Licensed 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.
*/
/**
* This file is an adaptation of trino's trino/core/trino-parser/src/main/antlr4/io/trino/sql/parser/SqlBase.g4 grammar.
* Reference: https://github.com/trinodb/trino/blob/385/core/trino-parser/src/main/antlr4/io/trino/sql/parser/SqlBase.g4
* current version 450
*/
// $antlr-format alignTrailingComments true, columnLimit 160, minEmptyLines 1, maxEmptyLinesToKeep 1, reflowComments false, useTab false
// $antlr-format allowShortRulesOnASingleLine false, allowShortBlocksOnASingleLine true, alignSemicolons hanging, alignColons hanging
// $antlr-format spaceBeforeAssignmentOperators false, keepEmptyLinesAtTheStartOfBlocks true
grammar TrinoSql;
options {
caseInsensitive= true;
superClass=SQLParserBase;
}
@parser::members {
notEntityCollecting(): boolean {
return !this.entityCollecting;
}
}
@header {
import { SQLParserBase } from '../SQLParserBase';
}
tokens {
DELIMITER
}
// Modified entrypoint
program
: statements* EOF
;
statements
: singleStatement
;
singleStatement
: statement SEMICOLON?
;
standaloneExpression
: expression SEMICOLON?
;
standalonePathSpecification
: pathSpecification SEMICOLON?
;
standaloneType
: type SEMICOLON?
;
standaloneRowPattern
: rowPattern SEMICOLON?
;
standaloneFunctionSpecification
: functionSpecification EOF
;
statement
: rootQuery # statementDefault
| KW_USE schemaRef # use
| KW_CREATE KW_CATALOG (KW_IF KW_NOT KW_EXISTS)? catalog=catalogNameCreate KW_USING connectorName=identifier (
KW_COMMENT string
)? (KW_AUTHORIZATION principal)? (KW_WITH properties)? # createCatalog
| KW_DROP KW_CATALOG (KW_IF KW_EXISTS)? catalog=catalogRef (KW_CASCADE | KW_RESTRICT)? # dropCatalog
| KW_CREATE KW_SCHEMA (KW_IF KW_NOT KW_EXISTS)? schemaNameCreate (KW_AUTHORIZATION principal)? (
KW_WITH properties
)? # createSchema
| KW_DROP KW_SCHEMA (KW_IF KW_EXISTS)? schemaRef (KW_CASCADE | KW_RESTRICT)? # dropSchema
| KW_ALTER KW_SCHEMA schemaRef KW_RENAME KW_TO schemaNameCreate # renameSchema
| KW_ALTER KW_SCHEMA schemaRef KW_SET KW_AUTHORIZATION principal # setSchemaAuthorization
| KW_CREATE (KW_OR KW_REPLACE)? KW_TABLE (KW_IF KW_NOT KW_EXISTS)? tableNameCreate columnListCreate? (
KW_COMMENT comment=string
)? (KW_WITH properties)? KW_AS (rootQuery | '(' rootQuery ')') (KW_WITH (KW_NO)? KW_DATA)? # createTableAsSelect
| KW_CREATE (KW_OR KW_REPLACE)? KW_TABLE (KW_IF KW_NOT KW_EXISTS)? tableNameCreate '(' tableElement (
',' tableElement
)* ')' (KW_COMMENT comment=string)? (KW_WITH properties)? # createTable
| KW_DROP KW_TABLE (KW_IF KW_EXISTS)? tableRef # dropTable
| KW_INSERT KW_INTO tableRef columnList? rootQuery # insertInto
| KW_DELETE KW_FROM tableRef (whereClause)? # delete
| KW_TRUNCATE KW_TABLE tableRef # truncateTable
| KW_COMMENT KW_ON KW_TABLE tableRef KW_IS (string | KW_NULL) # commentTable
| KW_COMMENT KW_ON KW_VIEW viewRef KW_IS (string | KW_NULL) # commentView
| KW_COMMENT KW_ON KW_COLUMN columnRef KW_IS (string | KW_NULL) # commentColumn
| KW_ALTER KW_TABLE (KW_IF KW_EXISTS)? from=tableRef KW_RENAME KW_TO to=tableNameCreate # renameTable
| KW_ALTER KW_TABLE (KW_IF KW_EXISTS)? tableName=tableRef KW_ADD KW_COLUMN (KW_IF KW_NOT KW_EXISTS)? column=columnDefinition # addColumn
| KW_ALTER KW_TABLE (KW_IF KW_EXISTS)? tableName=tableRef KW_RENAME KW_COLUMN (KW_IF KW_EXISTS)? from=columnRef KW_TO to=columnNameCreate # renameColumn
| KW_ALTER KW_TABLE (KW_IF KW_EXISTS)? tableName=tableRef KW_DROP KW_COLUMN (KW_IF KW_EXISTS)? column=columnRef # dropColumn
| KW_ALTER KW_TABLE (KW_IF KW_EXISTS)? tableName=tableRef KW_ALTER KW_COLUMN column=columnRef KW_SET KW_DATA KW_TYPE type # setColumnType
| KW_ALTER KW_TABLE (KW_IF KW_EXISTS)? tableName=tableRef KW_ALTER KW_COLUMN column=columnRef KW_DROP KW_NOT KW_NULL # dropNotNullConstraint
| KW_ALTER KW_TABLE tableName=tableRef KW_SET KW_AUTHORIZATION principal # setTableAuthorization
| KW_ALTER KW_TABLE tableName=tableRef KW_SET KW_PROPERTIES propertyAssignments # setTableProperties
| KW_ALTER KW_TABLE tableName=tableRef KW_EXECUTE procedureName=functionName (
'(' (callArgument (',' callArgument)*)? ')'
)? (whereClause)? # tableExecute
| KW_ANALYZE tableRef (KW_WITH properties)? # analyze
| KW_CREATE (KW_OR KW_REPLACE)? KW_MATERIALIZED KW_VIEW (KW_IF KW_NOT KW_EXISTS)? viewNameCreate (
KW_GRACE KW_PERIOD interval
)? (KW_COMMENT comment=string)? (KW_WITH properties)? KW_AS rootQuery # createMaterializedView
| KW_CREATE (KW_OR KW_REPLACE)? KW_VIEW viewNameCreate (KW_COMMENT comment=string)? (
KW_SECURITY (KW_DEFINER | KW_INVOKER)
)? (KW_WITH properties)? KW_AS rootQuery # createView
| KW_REFRESH KW_MATERIALIZED KW_VIEW viewRef # refreshMaterializedView
| KW_DROP KW_MATERIALIZED KW_VIEW (KW_IF KW_EXISTS)? viewRef # dropMaterializedView
| KW_ALTER KW_MATERIALIZED KW_VIEW (KW_IF KW_EXISTS)? from=viewRef KW_RENAME KW_TO to=viewNameCreate # renameMaterializedView
| KW_ALTER KW_MATERIALIZED KW_VIEW viewRef KW_SET KW_PROPERTIES propertyAssignments # setMaterializedViewProperties
| KW_DROP KW_VIEW (KW_IF KW_EXISTS)? viewRef # dropView
| KW_ALTER KW_VIEW from=viewRef KW_RENAME KW_TO to=viewNameCreate # renameView
| KW_ALTER KW_VIEW from=viewRef KW_SET KW_AUTHORIZATION principal # setViewAuthorization
| KW_CALL functionName '(' (callArgument (',' callArgument)*)? ')' # call
| KW_CREATE (KW_OR KW_REPLACE)? functionSpecification # createFunction
| KW_DROP KW_FUNCTION (KW_IF KW_EXISTS)? functionSignature # dropFunction
| KW_CREATE KW_ROLE name=identifier (KW_WITH KW_ADMIN grantor)? (KW_IN catalog=catalogRef)? # createRole
| KW_DROP KW_ROLE name=identifier (KW_IN catalog=catalogRef)? # dropRole
| KW_GRANT privilegeOrRole (',' privilegeOrRole)* KW_TO principal (',' principal)* (
KW_WITH KW_ADMIN KW_OPTION
)? (KW_GRANTED KW_BY grantor)? (KW_IN catalog=catalogRef)? # grantRoles
| KW_GRANT ((privilegeOrRole (',' privilegeOrRole)*) | KW_ALL KW_PRIVILEGES) KW_ON grantObject KW_TO principal (
KW_WITH KW_GRANT KW_OPTION
)? # grantPrivileges
| KW_REVOKE (KW_ADMIN KW_OPTION KW_FOR)? privilegeOrRole (',' privilegeOrRole)* KW_FROM principal (
',' principal
)* (KW_GRANTED KW_BY grantor)? (KW_IN catalog=catalogRef)? # revokeRoles
| KW_REVOKE (KW_GRANT KW_OPTION KW_FOR)? (
(privilegeOrRole (',' privilegeOrRole)*)
| KW_ALL KW_PRIVILEGES
) KW_ON grantObject KW_FROM grantee=principal # revokePrivileges
| KW_DENY (privilege (',' privilege)* | KW_ALL KW_PRIVILEGES) KW_ON grantObject KW_TO grantee=principal # deny
| KW_SET KW_ROLE (KW_ALL | KW_NONE | role=identifier) (KW_IN catalog=catalogRef)? # setRole
| KW_SHOW KW_GRANTS (KW_ON grantObject)? # showGrants
| KW_EXPLAIN ('(' explainOption (',' explainOption)* ')')? statement # explain
| KW_EXPLAIN KW_ANALYZE KW_VERBOSE? statement # explainAnalyze
| KW_SHOW KW_CREATE KW_TABLE tableRef # showCreateTable
| KW_SHOW KW_CREATE KW_SCHEMA schemaRef # showCreateSchema
| KW_SHOW KW_CREATE KW_VIEW viewRef # showCreateView
| KW_SHOW KW_CREATE KW_MATERIALIZED KW_VIEW viewRef # showCreateMaterializedView
| KW_SHOW KW_CREATE KW_FUNCTION functionName # showCreateFunction
| KW_SHOW KW_TABLES ((KW_FROM | KW_IN) schemaRef)? (
KW_LIKE pattern=string (KW_ESCAPE escape=string)?
)? # showTables
| KW_SHOW KW_SCHEMAS ((KW_FROM | KW_IN) catalogRef)? (
KW_LIKE pattern=string (KW_ESCAPE escape=string)?
)? # showSchemas
| KW_SHOW KW_CATALOGS (KW_LIKE pattern=string (KW_ESCAPE escape=string)?)? # showCatalogs
| KW_SHOW KW_COLUMNS (KW_FROM | KW_IN) tableOrViewName (
KW_LIKE pattern=string (KW_ESCAPE escape=string)?
)? # showColumns
| KW_SHOW KW_STATS KW_FOR tableOrViewName # showStats
| KW_SHOW KW_STATS KW_FOR '(' rootQuery ')' # showStatsForQuery
| KW_SHOW KW_CURRENT? KW_ROLES ((KW_FROM | KW_IN) catalogRef)? # showRoles
| KW_SHOW KW_ROLE KW_GRANTS ((KW_FROM | KW_IN) catalogRef)? # showRoleGrants
| KW_DESCRIBE tableOrViewName # showColumns
| KW_DESC tableOrViewName # showColumns
| KW_SHOW KW_FUNCTIONS ((KW_FROM | KW_IN) schemaRef)? (
KW_LIKE pattern=string (KW_ESCAPE escape=string)?
)? # showFunctions
| KW_SHOW KW_SESSION (KW_LIKE pattern=string (KW_ESCAPE escape=string)?)? # showSession
| KW_SET KW_SESSION KW_AUTHORIZATION authorizationUser # setSessionAuthorization
| KW_RESET KW_SESSION KW_AUTHORIZATION # resetSessionAuthorization
| KW_SET KW_SESSION qualifiedName EQ expression # setSession
| KW_RESET KW_SESSION qualifiedName # resetSession
| KW_START KW_TRANSACTION (transactionMode (',' transactionMode)*)? # startTransaction
| KW_COMMIT KW_WORK? # commit
| KW_ROLLBACK KW_WORK? # rollback
| KW_PREPARE identifier KW_FROM statement # prepare
| KW_DEALLOCATE KW_PREPARE identifier # deallocate
| KW_EXECUTE identifier (KW_USING expression (',' expression)*)? # execute
| KW_EXECUTE KW_IMMEDIATE string (KW_USING expression (',' expression)*)? # executeImmediate
| KW_DESCRIBE KW_INPUT identifier # describeInput
| KW_DESCRIBE KW_OUTPUT identifier # describeOutput
| KW_SET KW_PATH pathSpecification # setPath
| KW_SET KW_TIME KW_ZONE ( KW_LOCAL | expression) # setTimeZone
| KW_UPDATE tableRef KW_SET updateAssignment (',' updateAssignment)* (whereClause)? # update
| KW_MERGE KW_INTO tableRef (KW_AS? identifier)? KW_USING relation KW_ON expression mergeCase+ # merge
| KW_SHOW KW_COMMENT KW_ON KW_TABLE tableRef # showTableComment // dtstack
| KW_SHOW KW_COMMENT KW_ON KW_COLUMN columnRef # showColumnComment // dtstack
;
rootQuery
: withFunction? query
;
withFunction
: KW_WITH functionSpecification (',' functionSpecification)*
;
query
: with? queryNoWith # queryStatement
;
with
: KW_WITH KW_RECURSIVE? namedQuery (',' namedQuery)*
;
tableElement
: columnDefinition
| likeClause
;
columnDefinition
: columnNameCreate colType=type (KW_NOT KW_NULL)? (KW_COMMENT comment=string)? (KW_WITH properties)?
;
likeClause
: KW_LIKE tableRef (optionType=( KW_INCLUDING | KW_EXCLUDING) KW_PROPERTIES)?
;
properties
: '(' propertyAssignments ')'
;
propertyAssignments
: property (',' property)*
;
property
: identifier EQ propertyValue
;
propertyValue
: KW_DEFAULT # defaultPropertyValue
| expression # nonDefaultPropertyValue
;
queryNoWith
: queryTerm (KW_ORDER KW_BY sortItem (',' sortItem)*)? (
KW_OFFSET offset=rowCount (KW_ROW | KW_ROWS)?
)? (
(KW_LIMIT limit=limitRowCount)
| (
KW_FETCH (KW_FIRST | KW_NEXT) (fetchFirst=rowCount)? (KW_ROW | KW_ROWS) (
KW_ONLY
| KW_WITH KW_TIES
)
)
)?
;
limitRowCount
: KW_ALL
| rowCount
;
rowCount
: INTEGER_VALUE
| QUESTION_MARK
;
queryTerm
: queryPrimary # queryTermDefault
| left=queryTerm operator=KW_INTERSECT setQuantifier? right=queryTerm # setOperation
| left=queryTerm operator=(KW_UNION | KW_EXCEPT) setQuantifier? right=queryTerm # setOperation
;
queryPrimary
: querySpecification # queryPrimaryDefault
| KW_TABLE tableRef # table
| KW_VALUES expression (',' expression)* # inlineTable
| '(' queryNoWith ')' # subquery
;
sortItem
: (columnRef | expression) ordering=(KW_ASC | KW_DESC)? (
KW_NULLS nullOrdering=(KW_FIRST | KW_LAST)
)?
;
querySpecification
: KW_SELECT setQuantifier? selectList (KW_FROM relation (',' relation)*)? (whereClause)? (
KW_GROUP KW_BY groupBy
)? (havingClause)? (KW_WINDOW windowDefinition (',' windowDefinition)*)?
;
whereClause
: KW_WHERE where=booleanExpression
;
havingClause
: KW_HAVING having=booleanExpression
;
selectList
: selectItem (',' selectItem)*
;
groupBy
: setQuantifier? groupingElement (',' groupingElement)*
;
partitionBy
: expression (',' expression)*
;
groupingElement
: groupingSet # singleGroupingSet
| KW_ROLLUP '(' (groupingSet (',' groupingSet)*)? ')' # rollup
| KW_CUBE '(' (groupingSet (',' groupingSet)*)? ')' # cube
| KW_GROUPING KW_SETS '(' groupingSet (',' groupingSet)* ')' # multipleGroupingSets
;
groupingSet
: '(' (groupingTerm (',' groupingTerm)*)? ')'
| groupingTerm
;
groupingTerm
: columnRef
| expression
;
windowDefinition
: name=identifier KW_AS '(' windowSpecification ')'
;
windowSpecification
: (existingWindowName=identifier)? (KW_PARTITION KW_BY partitionBy)? (
KW_ORDER KW_BY sortItem (',' sortItem)*
)? windowFrame?
;
namedQuery
: name=identifier (columnAliases)? KW_AS '(' query ')'
;
setQuantifier
: KW_DISTINCT
| KW_ALL
;
selectItem
: (selectLiteralColumnName | selectExpressionColumnName) (KW_AS? alias=identifier)?
| tableAllColumns (KW_AS columnAliases)?
| selectAllWithoutTable
;
selectAllWithoutTable
: ASTERISK
;
tableAllColumns
: primaryExpression '.' ASTERISK
;
selectLiteralColumnName
: columnRef
;
selectExpressionColumnName
: expression
;
relation
: left=relation (
KW_CROSS KW_JOIN right=sampledRelation
| joinType KW_JOIN rightRelation=relation joinCriteria
| KW_NATURAL joinType KW_JOIN right=sampledRelation
) # joinRelation
| sampledRelation # relationDefault
;
joinType
: KW_INNER?
| KW_LEFT KW_OUTER?
| KW_RIGHT KW_OUTER?
| KW_FULL KW_OUTER?
;
joinCriteria
: KW_ON (joinColumnEquality | {this.notEntityCollecting()}? booleanExpression)
| KW_USING '(' identifier (',' identifier)* ')'
;
joinColumnEquality
: left=joinColumnReference EQ right=joinColumnReference
;
joinColumnReference
: identifier DOT {this.entityCollecting}? emptyColumn
| columnName
;
sampledRelation
: patternRecognition (KW_TABLESAMPLE sampleType '(' percentage=expression ')')?
;
sampleType
: KW_BERNOULLI
| KW_SYSTEM
;
trimsSpecification
: KW_LEADING
| KW_TRAILING
| KW_BOTH
;
listAggOverflowBehavior
: KW_ERROR
| KW_TRUNCATE string? listAggCountIndication
;
listAggCountIndication
: KW_WITH KW_COUNT
| KW_WITHOUT KW_COUNT
;
patternRecognition
: aliasedRelation (
KW_MATCH_RECOGNIZE '(' (KW_PARTITION KW_BY partitionBy)? (
KW_ORDER KW_BY sortItem (',' sortItem)*
)? (KW_MEASURES measureDefinition (',' measureDefinition)*)? rowsPerMatch? (
KW_AFTER KW_MATCH skipTo
)? (KW_INITIAL | KW_SEEK)? KW_PATTERN '(' rowPattern ')' (
KW_SUBSET subsetDefinition (',' subsetDefinition)*
)? KW_DEFINE variableDefinition (',' variableDefinition)* ')' (KW_AS? identifier columnAliases?)?
)?
;
measureDefinition
: expression KW_AS identifier
;
rowsPerMatch
: KW_ONE KW_ROW KW_PER KW_MATCH
| KW_ALL KW_ROWS KW_PER KW_MATCH emptyMatchHandling?
;
emptyMatchHandling
: KW_SHOW KW_EMPTY KW_MATCHES
| KW_OMIT KW_EMPTY KW_MATCHES
| KW_WITH KW_UNMATCHED KW_ROWS
;
skipTo
: 'SKIP' KW_TO KW_NEXT KW_ROW
| 'SKIP' KW_PAST KW_LAST KW_ROW
| 'SKIP' KW_TO KW_FIRST identifier
| 'SKIP' KW_TO KW_LAST identifier
| 'SKIP' KW_TO identifier
;
subsetDefinition
: name=identifier EQ '(' union+=identifier (',' union+=identifier)* ')'
;
variableDefinition
: identifier KW_AS expression
;
aliasedRelation
: relationPrimary (KW_AS? alias=identifier columnAliases?)?
;
columnListCreate
: '(' columnNameCreate (',' columnNameCreate)* ')'
;
columnList
: '(' columnRef (',' columnRef)* ')'
;
columnAliases
: '(' identifier (',' identifier)* ')'
;
relationPrimary
: tableOrViewName queryPeriod? # tableName
| relationSourceTable # expressionSourceTable
| '(' relation ')' # parenthesizedRelation
;
relationSourceTable
: '(' query ')' # subqueryRelation
| KW_UNNEST '(' expression (',' expression)* ')' (KW_WITH KW_ORDINALITY)? # unnest
| KW_LATERAL '(' query ')' # lateral
| KW_TABLE '(' tableFunctionCall ')' # tableFunctionInvocation
| KW_JSON_TABLE '(' jsonPathInvocation KW_COLUMNS '(' jsonTableColumn (',' jsonTableColumn)* ')' (
KW_PLAN '(' jsonTableSpecificPlan ')'
| KW_PLAN KW_DEFAULT '(' jsonTableDefaultPlan ')'
)? ((KW_ERROR | KW_EMPTY) KW_ON KW_ERROR)? ')' # jsonTable
;
jsonTableColumn
: identifier KW_FOR KW_ORDINALITY # ordinalityColumn
| identifier type (KW_PATH string)? (emptyBehavior=jsonValueBehavior KW_ON KW_EMPTY)? (
errorBehavior=jsonValueBehavior KW_ON KW_ERROR
)? # valueColumn
| identifier type KW_FORMAT jsonRepresentation (KW_PATH string)? (
jsonQueryWrapperBehavior KW_WRAPPER
)? ((KW_KEEP | KW_OMIT) KW_QUOTES (KW_ON KW_SCALAR KW_TEXT_STRING)?)? (
emptyBehavior=jsonQueryBehavior KW_ON KW_EMPTY
)? (errorBehavior=jsonQueryBehavior KW_ON KW_ERROR)? # queryColumn
| KW_NESTED KW_PATH? string (KW_AS identifier)? KW_COLUMNS '(' jsonTableColumn (',' jsonTableColumn)* ')' # nestedColumns
;
jsonTableSpecificPlan
: jsonTablePathName # leafPlan
| jsonTablePathName (KW_OUTER | KW_INNER) planPrimary # joinPlan
| planPrimary KW_UNION planPrimary (KW_UNION planPrimary)* # unionPlan
| planPrimary KW_CROSS planPrimary (KW_CROSS planPrimary)* # crossPlan
;
jsonTablePathName
: identifier
;
planPrimary
: jsonTablePathName
| '(' jsonTableSpecificPlan ')'
;
jsonTableDefaultPlan
: (KW_OUTER | KW_INNER) (',' (KW_UNION | KW_CROSS))?
| (KW_UNION | KW_CROSS) (',' (KW_OUTER | KW_INNER))?
;
tableFunctionCall
: functionName '(' (tableFunctionArgument (',' tableFunctionArgument)*)? (
KW_COPARTITION coPartitionTables (',' coPartitionTables)*
)? ')'
;
tableFunctionArgument
: (identifier '=>')? (
tableArgument
| descriptorArgument
| expression
) // descriptor before expression to avoid parsing descriptor as a function call
;
tableArgument
: tableArgumentRelation (KW_PARTITION KW_BY ('(' partitionBy? ')' | expression))? (
KW_PRUNE KW_WHEN KW_EMPTY
| KW_KEEP KW_WHEN KW_EMPTY
)? (KW_ORDER KW_BY ('(' sortItem (',' sortItem)* ')' | sortItem))?
;
tableArgumentRelation
: KW_TABLE '(' tableRef ')' (KW_AS? identifier columnAliases?)? # tableArgumentTable
| KW_TABLE '(' query ')' (KW_AS? identifier columnAliases?)? # tableArgumentQuery
;
descriptorArgument
: KW_DESCRIPTOR '(' descriptorField (',' descriptorField)* ')'
| KW_CAST '(' KW_NULL KW_AS KW_DESCRIPTOR ')'
;
descriptorField
: identifier type?
;
coPartitionTables
: '(' qualifiedName ',' qualifiedName (',' qualifiedName)* ')'
;
expression
: booleanExpression
;
booleanExpression
: valueExpression predicate[$valueExpression.ctx]? # predicated
| KW_NOT booleanExpression # logicalNot
| booleanExpression KW_AND booleanExpression # and
| booleanExpression KW_OR booleanExpression # or
;
// workaround for https://github.com/antlr/antlr4/issues/780
predicate[antlr.ParserRuleContext value]
: comparisonOperator right=valueExpression # comparison
| comparisonOperator comparisonQuantifier '(' query ')' # quantifiedComparison
| KW_NOT? KW_BETWEEN lower=valueExpression KW_AND upper=valueExpression # between
| KW_NOT? KW_IN '(' expression (',' expression)* ')' # inList
| KW_NOT? KW_IN '(' query ')' # inSubquery
| KW_NOT? KW_LIKE pattern=valueExpression (KW_ESCAPE escape=valueExpression)? # like
| KW_IS KW_NOT? KW_NULL # nullPredicate
| KW_IS KW_NOT? KW_DISTINCT KW_FROM right=valueExpression # distinctFrom
;
valueExpression
: primaryExpression # valueExpressionDefault
| valueExpression KW_AT timeZoneSpecifier # atTimeZone
| operator=(MINUS | PLUS) valueExpression # arithmeticUnary
| left=valueExpression operator=(ASTERISK | SLASH | PERCENT) right=valueExpression # arithmeticBinary
| left=valueExpression operator=(PLUS | MINUS) right=valueExpression # arithmeticBinary
| left=valueExpression CONCAT right=valueExpression # concatenation
;
primaryExpression
: KW_NULL # nullLiteral
| interval # intervalLiteral
| identifier string # typeConstructor
| KW_DOUBLE KW_PRECISION string # typeConstructor
| number # numericLiteral
| booleanValue # booleanLiteral
| string # stringLiteral
| BINARY_LITERAL # binaryLiteral
| QUESTION_MARK # parameter
| KW_POSITION '(' valueExpression KW_IN valueExpression ')' # position
| '(' expression (',' expression)+ ')' # rowConstructor
| KW_ROW '(' expression (',' expression)* ')' # rowConstructor
| name=KW_LISTAGG '(' setQuantifier? expression (',' string)? (
KW_ON KW_OVERFLOW listAggOverflowBehavior
)? ')' (KW_WITHIN KW_GROUP '(' KW_ORDER KW_BY sortItem (',' sortItem)* ')') filter? # listAgg
| processingMode? functionName '(' (label=identifier '.')? ASTERISK ')' filter? over? # functionCall
| processingMode? functionName '(' (setQuantifier? expression (',' expression)*)? (
KW_ORDER KW_BY sortItem (',' sortItem)*
)? ')' filter? (nullTreatment? over)? # functionCall
| identifier over # measure
| identifier '->' expression # lambda
| '(' (identifier (',' identifier)*)? ')' '->' expression # lambda
| '(' query ')' # subqueryExpression
// This is an extension to ANSI SQL, which considers KW_EXISTS to be a <boolean expression>
| KW_EXISTS '(' query ')' # exists
| KW_CASE operand=expression whenClause+ (KW_ELSE elseExpression=expression)? KW_END # simpleCase
| KW_CASE whenClause+ (KW_ELSE elseExpression=expression)? KW_END # searchedCase
| KW_CAST '(' expression KW_AS type ')' # cast
| KW_TRY_CAST '(' expression KW_AS type ')' # cast
| KW_ARRAY '[' (expression (',' expression)*)? ']' # arrayConstructor
| value=primaryExpression '[' index=valueExpression ']' # subscript
| columnName # columnReference
| base=primaryExpression '.' fieldName=identifier # dereference
| name=KW_CURRENT_DATE # currentDate
| name=KW_CURRENT_TIME ('(' precision=INTEGER_VALUE ')')? # currentTime
| name=KW_CURRENT_TIMESTAMP ('(' precision=INTEGER_VALUE ')')? # currentTimestamp
| name=KW_LOCALTIME ('(' precision=INTEGER_VALUE ')')? # localTime
| name=KW_LOCALTIMESTAMP ('(' precision=INTEGER_VALUE ')')? # localTimestamp
| name=KW_CURRENT_USER # currentUser
| name=KW_CURRENT_CATALOG # currentCatalog
| name=KW_CURRENT_SCHEMA # currentSchema
| name=KW_CURRENT_PATH # currentPath
| KW_TRIM '(' (trimsSpecification? trimChar=valueExpression? KW_FROM)? trimSource=valueExpression ')' # trim
| KW_TRIM '(' trimSource=valueExpression ',' trimChar=valueExpression ')' # trim
| KW_SUBSTRING '(' valueExpression KW_FROM valueExpression (KW_FOR valueExpression)? ')' # substring
| KW_NORMALIZE '(' valueExpression (',' normalForm)? ')' # normalize
| KW_EXTRACT '(' identifier KW_FROM valueExpression ')' # extract
| KW_COALESCE '(' expression (',' expression)* ')' # coalesce
| '(' expression ')' # parenthesizedExpression
| KW_GROUPING '(' (qualifiedName (',' qualifiedName)*)? ')' # groupingOperation
| KW_JSON_EXISTS '(' jsonPathInvocation (jsonExistsErrorBehavior KW_ON KW_ERROR)? ')' # jsonExists
| KW_JSON_VALUE '(' jsonPathInvocation (KW_RETURNING type)? (
emptyBehavior=jsonValueBehavior KW_ON KW_EMPTY
)? (errorBehavior=jsonValueBehavior KW_ON KW_ERROR)? ')' # jsonValue
| KW_JSON_QUERY '(' jsonPathInvocation (KW_RETURNING type (KW_FORMAT jsonRepresentation)?)? (
jsonQueryWrapperBehavior KW_WRAPPER
)? ((KW_KEEP | KW_OMIT) KW_QUOTES (KW_ON KW_SCALAR KW_TEXT_STRING)?)? (
emptyBehavior=jsonQueryBehavior KW_ON KW_EMPTY
)? (errorBehavior=jsonQueryBehavior KW_ON KW_ERROR)? ')' # jsonQuery
| KW_JSON_OBJECT '(' (
jsonObjectMember (',' jsonObjectMember)* (KW_NULL KW_ON KW_NULL | KW_ABSENT KW_ON KW_NULL)? (
KW_WITH KW_UNIQUE KW_KEYS?
| KW_WITHOUT KW_UNIQUE KW_KEYS?
)?
)? (KW_RETURNING type (KW_FORMAT jsonRepresentation)?)? ')' # jsonObject
| KW_JSON_ARRAY '(' (
jsonValueExpression (',' jsonValueExpression)* (KW_NULL KW_ON KW_NULL | KW_ABSENT KW_ON KW_NULL)?
)? (KW_RETURNING type (KW_FORMAT jsonRepresentation)?)? ')' # jsonArray
;
jsonPathInvocation
: jsonValueExpression ',' path=string (KW_AS pathName=identifier)? (
KW_PASSING jsonArgument (',' jsonArgument)*
)?
;
jsonValueExpression
: expression (KW_FORMAT jsonRepresentation)?
;
jsonRepresentation
: KW_JSON (KW_ENCODING (KW_UTF8 | KW_UTF16 | KW_UTF32))? // TODO add implementation-defined JSON representation option
;
jsonArgument
: jsonValueExpression KW_AS identifier
;
jsonExistsErrorBehavior
: KW_TRUE
| KW_FALSE
| KW_UNKNOWN
| KW_ERROR
;
jsonValueBehavior
: KW_ERROR
| KW_NULL
| KW_DEFAULT expression
;
jsonQueryWrapperBehavior
: KW_WITHOUT KW_ARRAY?
| KW_WITH (KW_CONDITIONAL | KW_UNCONDITIONAL)? KW_ARRAY?
;
jsonQueryBehavior
: KW_ERROR
| KW_NULL
| KW_EMPTY KW_ARRAY
| KW_EMPTY KW_OBJECT
;
jsonObjectMember
: KW_KEY? expression KW_VALUE jsonValueExpression
| expression ':' jsonValueExpression
;
processingMode
: KW_RUNNING
| KW_FINAL
;
nullTreatment
: KW_IGNORE KW_NULLS
| KW_RESPECT KW_NULLS
;
string
: STRING # basicStringLiteral
| UNICODE_STRING (KW_UESCAPE STRING)? # unicodeStringLiteral
;
timeZoneSpecifier
: KW_TIME KW_ZONE interval # timeZoneInterval
| KW_TIME KW_ZONE string # timeZoneString
;
comparisonOperator
: EQ
| NEQ
| LT
| LTE
| GT
| GTE
;
comparisonQuantifier
: KW_ALL
| KW_SOME
| KW_ANY
;
booleanValue
: KW_TRUE
| KW_FALSE
;
interval
: KW_INTERVAL sign=(PLUS | MINUS)? string from=intervalField (KW_TO to=intervalField)?
;
intervalField
: KW_YEAR
| KW_MONTH
| KW_DAY
| KW_HOUR
| KW_MINUTE
| KW_SECOND
;
normalForm
: KW_NFD
| KW_NFC
| KW_NFKD
| KW_NFKC
;
type
: KW_ROW '(' rowField (',' rowField)* ')' # rowType
| KW_INTERVAL from=intervalField (KW_TO to=intervalField)? # intervalType
| base=KW_TIMESTAMP ('(' precision= typeParameter ')')? ((KW_WITH | KW_WITHOUT) KW_TIME KW_ZONE)? # dateTimeType
| base=KW_TIME ('(' precision= typeParameter ')')? ((KW_WITH | KW_WITHOUT) KW_TIME KW_ZONE)? # timeType
| KW_DOUBLE KW_PRECISION # doublePrecisionType
| KW_ARRAY '<' type '>' # legacyArrayType
| KW_MAP '<' keyType=type ',' valueType=type '>' # legacyMapType
| type KW_ARRAY ('[' INTEGER_VALUE ']')? # arrayType
| identifier ('(' typeParameter (',' typeParameter)* ')')? # genericType
;
rowField
: type
| identifier type
;
typeParameter
: INTEGER_VALUE
| type
;
whenClause
: KW_WHEN condition=expression KW_THEN result=expression
;
filter
: KW_FILTER '(' whereClause ')'
;
mergeCase
: KW_WHEN KW_MATCHED (KW_AND condition=expression)? KW_THEN KW_UPDATE KW_SET targets+=identifier EQ values+=expression (
',' targets+=identifier EQ values+=expression
)* # mergeUpdate
| KW_WHEN KW_MATCHED (KW_AND condition=expression)? KW_THEN KW_DELETE # mergeDelete
| KW_WHEN KW_NOT KW_MATCHED (KW_AND condition=expression)? KW_THEN KW_INSERT (
'(' targets+=identifier (',' targets+=identifier)* ')'
)? KW_VALUES '(' values+=expression (',' values+=expression)* ')' # mergeInsert
;
over
: KW_OVER (windowName=identifier | '(' windowSpecification ')')
;
windowFrame
: (KW_MEASURES measureDefinition (',' measureDefinition)*)? frameExtent (KW_AFTER KW_MATCH skipTo)? (
KW_INITIAL
| KW_SEEK
)? (KW_PATTERN '(' rowPattern ')')? (KW_SUBSET subsetDefinition (',' subsetDefinition)*)? (
KW_DEFINE variableDefinition (',' variableDefinition)*
)?
;
frameExtent
: frameType=KW_RANGE start=frameBound
| frameType=KW_ROWS start=frameBound
| frameType=KW_GROUPS start=frameBound
| frameType=KW_RANGE KW_BETWEEN start=frameBound KW_AND end=frameBound
| frameType=KW_ROWS KW_BETWEEN start=frameBound KW_AND end=frameBound
| frameType=KW_GROUPS KW_BETWEEN start=frameBound KW_AND end=frameBound
;
frameBound
: KW_UNBOUNDED boundType=KW_PRECEDING # unboundedFrame
| KW_UNBOUNDED boundType=KW_FOLLOWING # unboundedFrame
| KW_CURRENT KW_ROW # currentRowBound
| expression boundType=(KW_PRECEDING | KW_FOLLOWING) # boundedFrame
;
rowPattern
: patternPrimary patternQuantifier? # quantifiedPrimary
| rowPattern rowPattern # patternConcatenation
| rowPattern '|' rowPattern # patternAlternation
;
patternPrimary
: identifier # patternVariable
| '(' ')' # emptyPattern
| KW_PERMUTE '(' rowPattern (',' rowPattern)* ')' # patternPermutation
| '(' rowPattern ')' # groupedPattern
| '^' # partitionStartAnchor
| '$' # partitionEndAnchor
| '{-' rowPattern '-}' # excludedPattern
;
patternQuantifier
: ASTERISK (reluctant=QUESTION_MARK)? # zeroOrMoreQuantifier
| PLUS (reluctant=QUESTION_MARK)? # oneOrMoreQuantifier
| QUESTION_MARK (reluctant=QUESTION_MARK)? # zeroOrOneQuantifier
| '{' exactly=INTEGER_VALUE '}' (reluctant=QUESTION_MARK)? # rangeQuantifier
| '{' (atLeast=INTEGER_VALUE)? ',' (atMost=INTEGER_VALUE)? '}' (reluctant=QUESTION_MARK)? # rangeQuantifier
;
updateAssignment
: identifier EQ expression
;
explainOption
: KW_FORMAT value=(KW_TEXT | KW_GRAPHVIZ | KW_JSON) # explainFormat
| KW_TYPE value=(KW_LOGICAL | KW_DISTRIBUTED | KW_VALIDATE | KW_IO) # explainType
;
transactionMode
: KW_ISOLATION KW_LEVEL levelOfIsolation # isolationLevel
| KW_READ accessMode=(KW_ONLY | KW_WRITE) # transactionAccessMode
;
levelOfIsolation
: KW_READ KW_UNCOMMITTED # readUncommitted
| KW_READ KW_COMMITTED # readCommitted
| KW_REPEATABLE KW_READ # repeatableRead
| KW_SERIALIZABLE # serializable
;
callArgument
: expression # positionalArgument
| identifier '=>' expression # namedArgument
;
pathElement
: identifier '.' identifier # qualifiedArgument
| identifier # unqualifiedArgument
;
pathSpecification
: pathElement (',' pathElement)*
;
functionSpecification
: KW_FUNCTION functionDeclaration returnsClause routineCharacteristic* controlStatement
;
functionDeclaration
: functionNameCreate '(' (parameterDeclaration (',' parameterDeclaration)*)? ')'
;
functionSignature
: functionName '(' (parameterDeclaration (',' parameterDeclaration)*)? ')'
;
parameterDeclaration
: identifier? type
;
returnsClause
: KW_RETURNS type
;
routineCharacteristic
: KW_LANGUAGE identifier # languageCharacteristic
| KW_NOT? KW_DETERMINISTIC # deterministicCharacteristic
| KW_RETURNS KW_NULL KW_ON KW_NULL KW_INPUT # returnsNullOnNullInputCharacteristic
| KW_CALLED KW_ON KW_NULL KW_INPUT # calledOnNullInputCharacteristic
| KW_SECURITY (KW_DEFINER | KW_INVOKER) # securityCharacteristic
| KW_COMMENT string # commentCharacteristic
;
controlStatement
: KW_RETURN valueExpression # returnStatement
| KW_SET identifier EQ expression # assignmentStatement
| KW_CASE expression caseStatementWhenClause+ elseClause? KW_END KW_CASE # simpleCaseStatement
| KW_CASE caseStatementWhenClause+ elseClause? KW_END KW_CASE # searchedCaseStatement
| KW_IF expression KW_THEN sqlStatementList elseIfClause* elseClause? KW_END KW_IF # ifStatement
| KW_ITERATE identifier # iterateStatement
| KW_LEAVE identifier # leaveStatement
| KW_BEGIN (variableDeclaration SEMICOLON)* sqlStatementList? KW_END # compoundStatement
| (label=identifier ':')? KW_LOOP sqlStatementList KW_END KW_LOOP # loopStatement
| (label=identifier ':')? KW_WHILE expression KW_DO sqlStatementList KW_END KW_WHILE # whileStatement
| (label=identifier ':')? KW_REPEAT sqlStatementList KW_UNTIL expression KW_END KW_REPEAT # repeatStatement
;
caseStatementWhenClause
: KW_WHEN expression KW_THEN sqlStatementList
;
elseIfClause
: KW_ELSEIF expression KW_THEN sqlStatementList
;
elseClause
: KW_ELSE sqlStatementList
;
variableDeclaration
: KW_DECLARE identifier (',' identifier)* type (KW_DEFAULT valueExpression)?
;
sqlStatementList
: (controlStatement SEMICOLON)+
;
privilege
: KW_CREATE
| KW_SELECT
| KW_DELETE
| KW_INSERT
| KW_UPDATE
| identifier
;
entityKind
: KW_TABLE
| KW_SCHEMA
| identifier
;
grantObject
: entityKind? qualifiedName
;
tableOrViewName
: tableRef
| viewRef
;