-
Notifications
You must be signed in to change notification settings - Fork 62
/
PartiQL.g4
855 lines (692 loc) · 25.3 KB
/
PartiQL.g4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
grammar PartiQL;
options {
tokenVocab=PartiQLTokens;
caseInsensitive = true;
}
/**
*
* TOP LEVEL
*
*/
root
: (EXPLAIN (PAREN_LEFT explainOption (COMMA explainOption)* PAREN_RIGHT)? )? statement;
statement
: dql COLON_SEMI? EOF # QueryDql
| dml COLON_SEMI? EOF # QueryDml
| ddl COLON_SEMI? EOF # QueryDdl
| execCommand COLON_SEMI? EOF # QueryExec
;
/**
*
* COMMON STRUCTURES
*
*/
explainOption
: param=IDENTIFIER value=IDENTIFIER;
asIdent
: AS symbolPrimitive;
atIdent
: AT symbolPrimitive;
byIdent
: BY symbolPrimitive;
symbolPrimitive
: ident=( IDENTIFIER | IDENTIFIER_QUOTED )
;
/**
*
* DATA QUERY LANGUAGE (DQL)
*
*/
dql
: expr;
/**
*
* EXECUTE
*
*/
// FIXME #002: This is a slight deviation from SqlParser, as the old parser allows ANY token after EXEC. Realistically,
// we probably need to determine the formal rule for this. I'm assuming we shouldn't allow any token, but I've
// left it as an expression (which allows strings). See https://github.com/partiql/partiql-lang-kotlin/issues/707
execCommand
: EXEC name=expr ( args+=expr ( COMMA args+=expr )* )?;
/**
*
* DATA DEFINITION LANGUAGE (DDL)
* Experimental, towards #36 https://github.com/partiql/partiql-docs/issues/36
* Currently, this is a small subset of SQL DDL that is likely to make sense for PartiQL as well.
*/
// <qualified name> ::= [ <schema name> <period> ] <qualified identifier>
qualifiedName : (qualifier+=symbolPrimitive PERIOD)* name=symbolPrimitive;
tableName : symbolPrimitive;
columnName : symbolPrimitive;
constraintName : symbolPrimitive;
comment : COMMENT LITERAL_STRING;
ddl
: createCommand
| dropCommand
;
createCommand
: CREATE TABLE qualifiedName ( PAREN_LEFT tableDef PAREN_RIGHT )? tableExtension* # CreateTable
| CREATE INDEX ON symbolPrimitive PAREN_LEFT pathSimple ( COMMA pathSimple )* PAREN_RIGHT # CreateIndex
;
dropCommand
: DROP TABLE qualifiedName # DropTable
| DROP INDEX target=symbolPrimitive ON on=symbolPrimitive # DropIndex
;
tableDef
: tableDefPart ( COMMA tableDefPart )*
;
tableDefPart
: columnName OPTIONAL? type columnConstraint* comment? # ColumnDeclaration
| ( CONSTRAINT constraintName )? tableConstraintDef # TableConstrDeclaration
;
tableConstraintDef
: checkConstraintDef # TableConstrCheck
| uniqueConstraintDef # TableConstrUnique
;
columnConstraint
: ( CONSTRAINT constraintName )? columnConstraintDef
;
columnConstraintDef
: NOT NULL # ColConstrNotNull
| NULL # ColConstrNull
| uniqueSpec # ColConstrUnique
| checkConstraintDef # ColConstrCheck
;
checkConstraintDef
: CHECK PAREN_LEFT searchCondition PAREN_RIGHT
;
uniqueSpec
: PRIMARY KEY # PrimaryKey
| UNIQUE # Unique
;
uniqueConstraintDef
: uniqueSpec PAREN_LEFT columnName (COMMA columnName)* PAREN_RIGHT
;
// <search condition> ::= <boolean term> | <search condition> OR <boolean term>
// we cannot do exactly that for the way expression precedence is structured in the grammar file.
// but we at least can eliminate SFW query here.
searchCondition : exprOr;
// SQL/HIVE DDL Extension, Support additional table metadatas such as partition by, tblProperties, etc.
tableExtension
: PARTITION BY partitionBy # TblExtensionPartition
| TBLPROPERTIES PAREN_LEFT keyValuePair (COMMA keyValuePair)* PAREN_RIGHT # TblExtensionTblProperties
;
// Limiting the scope to only allow String as valid value for now
keyValuePair : key=LITERAL_STRING EQ value=LITERAL_STRING;
// For now: just support a list of column name
// In the future, we might support common partition expression such as Hash(), Range(), etc.
partitionBy
: PAREN_LEFT columnName (COMMA columnName)* PAREN_RIGHT #PartitionColList
;
/**
*
* DATA MANIPULATION LANGUAGE (DML)
*
*/
dml
: updateClause dmlBaseCommand+ whereClause? returningClause? # DmlBaseWrapper
| fromClause whereClause? dmlBaseCommand+ returningClause? # DmlBaseWrapper
| deleteCommand # DmlDelete
| insertCommandReturning # DmlInsertReturning
| dmlBaseCommand # DmlBase
;
dmlBaseCommand
: insertStatement
| insertStatementLegacy
| setCommand
| replaceCommand
| removeCommand
| upsertCommand
;
pathSimple
: symbolPrimitive pathSimpleSteps*;
pathSimpleSteps
: BRACKET_LEFT key=literal BRACKET_RIGHT # PathSimpleLiteral
| BRACKET_LEFT key=symbolPrimitive BRACKET_RIGHT # PathSimpleSymbol
| PERIOD key=symbolPrimitive # PathSimpleDotSymbol
;
// Based on https://github.com/partiql/partiql-docs/blob/main/RFCs/0011-partiql-insert.md
// TODO add parsing of target attributes: https://github.com/partiql/partiql-lang-kotlin/issues/841
replaceCommand
: REPLACE INTO symbolPrimitive asIdent? value=expr;
// Based on https://github.com/partiql/partiql-docs/blob/main/RFCs/0011-partiql-insert.md
// TODO add parsing of target attributes: https://github.com/partiql/partiql-lang-kotlin/issues/841
upsertCommand
: UPSERT INTO symbolPrimitive asIdent? value=expr;
removeCommand
: REMOVE pathSimple;
// FIXME #001
// There is a bug in the old SqlParser that needed to be replicated to the PartiQLParser for the sake of ...
// ... same functionality. Using 2 returning clauses always uses the second clause. This should be fixed.
// See GH Issue: https://github.com/partiql/partiql-lang-kotlin/issues/698
// We essentially use the returning clause, because we currently support this with the SqlParser.
// See https://github.com/partiql/partiql-lang-kotlin/issues/708
insertCommandReturning
: INSERT INTO pathSimple VALUE value=expr ( AT pos=expr )? onConflictLegacy? returningClause?;
// See the Grammar at https://github.com/partiql/partiql-docs/blob/main/RFCs/0011-partiql-insert.md#2-proposed-grammar-and-semantics
insertStatement
: INSERT INTO symbolPrimitive asIdent? value=expr onConflict?
;
onConflict
: ON CONFLICT conflictTarget? conflictAction
;
insertStatementLegacy
: INSERT INTO pathSimple VALUE value=expr ( AT pos=expr )? onConflictLegacy?
;
onConflictLegacy
: ON CONFLICT WHERE expr DO NOTHING
;
/**
<conflict target> ::=
( <index target> [, <index target>]... )
| ( { <primary key> | <composite primary key> } )
| ON CONSTRAINT <constraint name>
*/
conflictTarget
: PAREN_LEFT symbolPrimitive (COMMA symbolPrimitive)* PAREN_RIGHT
| ON CONSTRAINT constraintName;
conflictAction
: DO NOTHING
| DO REPLACE doReplace
| DO UPDATE doUpdate;
/*
<do replace> ::= EXCLUDED
| SET <attr values> [, <attr values>]...
| VALUE <tuple value>
[ WHERE <condition> ]
*/
doReplace
: EXCLUDED ( WHERE condition=expr )?;
// :TODO add the rest of the grammar
/*
<do update> ::= EXCLUDED
| SET <attr values> [, <attr values>]...
| VALUE <tuple value>
[ WHERE <condition> ]
*/
doUpdate
: EXCLUDED ( WHERE condition=expr )?;
// :TODO add the rest of the grammar
updateClause
: UPDATE tableBaseReference;
setCommand
: SET setAssignment ( COMMA setAssignment )*;
setAssignment
: pathSimple EQ expr;
deleteCommand
: DELETE fromClauseSimple whereClause? returningClause?;
returningClause
: RETURNING returningColumn ( COMMA returningColumn )*;
returningColumn
: status=(MODIFIED|ALL) age=(OLD|NEW) ASTERISK
| status=(MODIFIED|ALL) age=(OLD|NEW) col=expr
;
fromClauseSimple
: FROM pathSimple asIdent? atIdent? byIdent? # FromClauseSimpleExplicit
| FROM pathSimple symbolPrimitive # FromClauseSimpleImplicit
;
whereClause
: WHERE arg=expr;
/**
*
* SELECT AND PROJECTION
*
*/
selectClause
: SELECT setQuantifierStrategy? ASTERISK # SelectAll
| SELECT setQuantifierStrategy? projectionItems # SelectItems
| SELECT setQuantifierStrategy? VALUE expr # SelectValue
| PIVOT pivot=expr AT at=expr # SelectPivot
;
projectionItems
: projectionItem ( COMMA projectionItem )* ;
projectionItem
: expr ( AS? symbolPrimitive )? ;
setQuantifierStrategy
: DISTINCT
| ALL
;
/**
* LET CLAUSE
*/
letClause
: LET letBinding ( COMMA letBinding )*;
letBinding
: expr AS symbolPrimitive;
/**
*
* ORDER BY CLAUSE
*
*/
orderByClause
: ORDER BY orderSortSpec ( COMMA orderSortSpec )*;
orderSortSpec
: expr dir=(ASC|DESC)? (NULLS nulls=(FIRST|LAST))?;
/**
*
* GROUP CLAUSE
*
*/
groupClause
: GROUP PARTIAL? BY groupKey ( COMMA groupKey )* groupAlias?;
groupAlias
: GROUP AS symbolPrimitive;
groupKey
: key=exprSelect (AS symbolPrimitive)?;
/**
*
* Window Function
* TODO: Remove from experimental once https://github.com/partiql/partiql-docs/issues/31 is resolved and a RFC is approved
*
*/
over
: OVER PAREN_LEFT windowPartitionList? windowSortSpecList? PAREN_RIGHT
;
windowPartitionList
: PARTITION BY expr (COMMA expr)*
;
windowSortSpecList
: ORDER BY orderSortSpec (COMMA orderSortSpec)*
;
/**
*
* SIMPLE CLAUSES
*
*/
havingClause
: HAVING arg=exprSelect;
excludeClause
: EXCLUDE excludeExpr (COMMA excludeExpr)*;
// Require 1 more `excludeExprSteps` (disallow `EXCLUDE a`).
// There's not a clear use case in which a user would exclude a previously introdced binding variable. If a use case
// arises, we can always change the requirement to 0 or more steps.
excludeExpr
: symbolPrimitive excludeExprSteps+;
excludeExprSteps
: PERIOD symbolPrimitive # ExcludeExprTupleAttr
| BRACKET_LEFT attr=LITERAL_STRING BRACKET_RIGHT # ExcludeExprCollectionAttr
| BRACKET_LEFT index=LITERAL_INTEGER BRACKET_RIGHT # ExcludeExprCollectionIndex
| BRACKET_LEFT ASTERISK BRACKET_RIGHT # ExcludeExprCollectionWildcard
| PERIOD ASTERISK # ExcludeExprTupleWildcard
;
fromClause
: FROM tableReference;
whereClauseSelect
: WHERE arg=exprSelect;
offsetByClause
: OFFSET arg=exprSelect;
limitClause
: LIMIT arg=exprSelect;
/**
*
* GRAPH PATTERN MATCHING LANGUAGE (GPML)
*
*/
gpmlPattern
: selector=matchSelector? matchPattern;
gpmlPatternList
: selector=matchSelector? matchPattern ( COMMA matchPattern )*;
matchPattern
: restrictor=patternRestrictor? variable=patternPathVariable? graphPart*;
graphPart
: node
| edge
| pattern
;
matchSelector
: mod=(ANY|ALL) SHORTEST # SelectorBasic
| ANY k=LITERAL_INTEGER? # SelectorAny
| SHORTEST k=LITERAL_INTEGER GROUP? # SelectorShortest
;
patternPathVariable
: symbolPrimitive EQ;
patternRestrictor // Should be TRAIL / ACYCLIC / SIMPLE
: restrictor=IDENTIFIER;
node
: PAREN_LEFT symbolPrimitive? ( COLON labelSpec )? whereClause? PAREN_RIGHT;
edge
: edgeWSpec quantifier=patternQuantifier? # EdgeWithSpec
| edgeAbbrev quantifier=patternQuantifier? # EdgeAbbreviated
;
pattern
: PAREN_LEFT restrictor=patternRestrictor? variable=patternPathVariable? graphPart+ where=whereClause? PAREN_RIGHT quantifier=patternQuantifier?
| BRACKET_LEFT restrictor=patternRestrictor? variable=patternPathVariable? graphPart+ where=whereClause? BRACKET_RIGHT quantifier=patternQuantifier?
;
patternQuantifier
: quant=( PLUS | ASTERISK )
| BRACE_LEFT lower=LITERAL_INTEGER COMMA upper=LITERAL_INTEGER? BRACE_RIGHT
;
edgeWSpec
: MINUS edgeSpec MINUS ANGLE_RIGHT # EdgeSpecRight
| TILDE edgeSpec TILDE # EdgeSpecUndirected
| ANGLE_LEFT MINUS edgeSpec MINUS # EdgeSpecLeft
| TILDE edgeSpec TILDE ANGLE_RIGHT # EdgeSpecUndirectedRight
| ANGLE_LEFT TILDE edgeSpec TILDE # EdgeSpecUndirectedLeft
| ANGLE_LEFT MINUS edgeSpec MINUS ANGLE_RIGHT # EdgeSpecBidirectional
| MINUS edgeSpec MINUS # EdgeSpecUndirectedBidirectional
;
edgeSpec
: BRACKET_LEFT symbolPrimitive? ( COLON labelSpec )? whereClause? BRACKET_RIGHT;
labelSpec
: labelSpec VERTBAR labelTerm # LabelSpecOr
| labelTerm # LabelSpecTerm
;
labelTerm
: labelTerm AMPERSAND labelFactor # LabelTermAnd
| labelFactor # LabelTermFactor
;
labelFactor
: BANG labelPrimary # LabelFactorNot
| labelPrimary # LabelFactorPrimary
;
labelPrimary
: symbolPrimitive # LabelPrimaryName
| PERCENT # LabelPrimaryWild
| PAREN_LEFT labelSpec PAREN_RIGHT # LabelPrimaryParen
;
edgeAbbrev
: TILDE
| TILDE ANGLE_RIGHT
| ANGLE_LEFT TILDE
| ANGLE_LEFT? MINUS ANGLE_RIGHT?
;
/**
*
* TABLES & JOINS
*
*/
tableReference
: lhs=tableReference joinType? CROSS JOIN rhs=joinRhs # TableCrossJoin
| lhs=tableReference COMMA rhs=joinRhs # TableCrossJoin
| lhs=tableReference joinType? JOIN rhs=joinRhs joinSpec # TableQualifiedJoin
| tableNonJoin # TableRefBase
| PAREN_LEFT tableReference PAREN_RIGHT # TableWrapped
;
tableNonJoin
: tableBaseReference
| tableUnpivot
;
tableBaseReference
: source=exprSelect symbolPrimitive # TableBaseRefSymbol
| source=exprSelect asIdent? atIdent? byIdent? # TableBaseRefClauses
| source=exprGraphMatchOne asIdent? atIdent? byIdent? # TableBaseRefMatch
;
tableUnpivot
: UNPIVOT expr asIdent? atIdent? byIdent?;
joinRhs
: tableNonJoin # JoinRhsBase
| PAREN_LEFT tableReference PAREN_RIGHT # JoinRhsTableJoined
;
joinSpec
: ON expr;
joinType
: mod=INNER
| mod=LEFT OUTER?
| mod=RIGHT OUTER?
| mod=FULL OUTER?
| mod=OUTER
;
/**
*
* EXPRESSIONS & PRECEDENCE
*
* Precedence Table (from highest to lowest precedence)
* 1. Primary Expressions: Functions, Literals, Paths, Identifiers, etc (ex: a, f(a), 1, a.b, "a")
* 2. Unary plus, minus (ex: -a, +a)
* 3. Multiplication, Division, Modulo (ex: a * b)
* 4. Addition, Subtraction (ex: a + b)
* 5. Other operators (ex: a || b, a & b)
* 6. Predicates (ex: a LIKE b, a < b, a IN b, a = b)
* 7. IS true/false. Not yet implemented in PartiQL, but defined in SQL-92. (ex: a IS TRUE)
* 8. NOT (ex: NOT a)
* 8. AND (ex: a AND b)
* 9. OR (ex: a OR b)
*
*/
expr
: exprBagOp
;
exprBagOp
: lhs=exprBagOp OUTER? EXCEPT (DISTINCT|ALL)? rhs=exprSelect # Except
| lhs=exprBagOp OUTER? UNION (DISTINCT|ALL)? rhs=exprSelect # Union
| lhs=exprBagOp OUTER? INTERSECT (DISTINCT|ALL)? rhs=exprSelect # Intersect
| exprSelect # QueryBase
;
exprSelect
: select=selectClause
exclude=excludeClause?
from=fromClause
let=letClause?
where=whereClauseSelect?
group=groupClause?
having=havingClause?
order=orderByClause?
limit=limitClause?
offset=offsetByClause? # SfwQuery
| exprOr # SfwBase
;
exprOr
: lhs=exprOr OR rhs=exprAnd # Or
| parent=exprAnd # ExprOrBase
;
exprAnd
: lhs=exprAnd op=AND rhs=exprNot # And
| parent=exprNot # ExprAndBase
;
exprNot
: <assoc=right> op=NOT rhs=exprNot # Not
| parent=exprPredicate # ExprNotBase
;
exprPredicate
: lhs=exprPredicate op=comparisonOp rhs=mathOp00 # PredicateComparison
| lhs=exprPredicate IS NOT? type # PredicateIs
| lhs=exprPredicate NOT? IN PAREN_LEFT expr PAREN_RIGHT # PredicateIn
| lhs=exprPredicate NOT? IN rhs=mathOp00 # PredicateIn
| lhs=exprPredicate NOT? LIKE rhs=mathOp00 ( ESCAPE escape=expr )? # PredicateLike
| lhs=exprPredicate NOT? BETWEEN lower=mathOp00 AND upper=mathOp00 # PredicateBetween
| parent=mathOp00 # PredicateBase
;
comparisonOp
: LT_EQ
| GT_EQ
| ANGLE_LEFT
| ANGLE_RIGHT
| EQ
| ANGLE_LEFT ANGLE_RIGHT
| BANG EQ
;
// TODO : Opreator precedence of BITWISE_AND (&) may change in the future.
// SEE: https://github.com/partiql/partiql-docs/issues/50
mathOp00
: lhs=mathOp00 op=(AMPERSAND|CONCAT) rhs=mathOp01
| parent=mathOp01
;
mathOp01
: lhs=mathOp01 op=(PLUS|MINUS) rhs=mathOp02
| parent=mathOp02
;
mathOp02
: lhs=mathOp02 op=(PERCENT|ASTERISK|SLASH_FORWARD) rhs=valueExpr
| parent=valueExpr
;
valueExpr
: sign=(PLUS|MINUS) rhs=valueExpr
| parent=exprPrimary
;
exprPrimary
: exprTerm # ExprPrimaryBase
| cast # ExprPrimaryBase
| sequenceConstructor # ExprPrimaryBase
| substring # ExprPrimaryBase
| position # ExprPrimaryBase
| overlay # ExprPrimaryBase
| canCast # ExprPrimaryBase
| canLosslessCast # ExprPrimaryBase
| extract # ExprPrimaryBase
| coalesce # ExprPrimaryBase
| dateFunction # ExprPrimaryBase
| aggregate # ExprPrimaryBase
| trimFunction # ExprPrimaryBase
| functionCall # ExprPrimaryBase
| nullIf # ExprPrimaryBase
| exprPrimary pathStep+ # ExprPrimaryPath
| exprGraphMatchMany # ExprPrimaryBase
| caseExpr # ExprPrimaryBase
| valueList # ExprPrimaryBase
| values # ExprPrimaryBase
| windowFunction # ExprPrimaryBase
;
/**
*
* PRIMARY EXPRESSIONS
*
*/
exprTerm
: PAREN_LEFT expr PAREN_RIGHT # ExprTermWrappedQuery
| CURRENT_USER # ExprTermCurrentUser
| CURRENT_DATE # ExprTermCurrentDate
| parameter # ExprTermBase
| varRefExpr # ExprTermBase
| literal # ExprTermBase
| collection # ExprTermBase
| tuple # ExprTermBase
;
nullIf
: NULLIF PAREN_LEFT expr COMMA expr PAREN_RIGHT;
coalesce
: COALESCE PAREN_LEFT expr ( COMMA expr )* PAREN_RIGHT;
caseExpr
: CASE case=expr? (WHEN whens+=expr THEN thens+=expr)+ (ELSE else=expr)? END;
values
: VALUES valueRow ( COMMA valueRow )*;
valueRow
: PAREN_LEFT expr ( COMMA expr )* PAREN_RIGHT;
valueList
: PAREN_LEFT expr ( COMMA expr )+ PAREN_RIGHT;
sequenceConstructor
: datatype=(LIST|SEXP) PAREN_LEFT (expr ( COMMA expr )* )? PAREN_RIGHT;
substring
: SUBSTRING PAREN_LEFT expr ( COMMA expr ( COMMA expr )? )? PAREN_RIGHT
| SUBSTRING PAREN_LEFT expr ( FROM expr ( FOR expr )? )? PAREN_RIGHT
;
/**
* POSITION(<str>, <str>)
* POSITION(<str> IN <str>)
*/
position
: POSITION PAREN_LEFT expr COMMA expr PAREN_RIGHT
| POSITION PAREN_LEFT expr IN expr PAREN_RIGHT
;
/**
* OVERLAY(<str>, <str>, <int> [, <int>])
* OVERLAY(<str> PLACING <str> FROM <int> [FOR <int>])
*/
overlay
: OVERLAY PAREN_LEFT expr COMMA expr COMMA expr (COMMA expr)? PAREN_RIGHT
| OVERLAY PAREN_LEFT expr PLACING expr FROM expr (FOR expr)? PAREN_RIGHT
;
aggregate
: func=COUNT PAREN_LEFT ASTERISK PAREN_RIGHT # CountAll
| func=(COUNT|MAX|MIN|SUM|AVG|EVERY|ANY|SOME) PAREN_LEFT setQuantifierStrategy? expr PAREN_RIGHT # AggregateBase
;
// TODO: Remove from experimental once https://github.com/partiql/partiql-docs/issues/31 is resolved and a RFC is approved
/**
*
* Supported Window Functions:
* 1. LAG(expr, [offset [, default]]) OVER([window_partition] window_ordering)
* 2. LEAD(expr, [offset [, default]]) OVER([window_partition] window_ordering)
*
*/
windowFunction
: func=(LAG|LEAD) PAREN_LEFT expr ( COMMA expr (COMMA expr)?)? PAREN_RIGHT over #LagLeadFunction
;
cast
: CAST PAREN_LEFT expr AS type PAREN_RIGHT;
canLosslessCast
: CAN_LOSSLESS_CAST PAREN_LEFT expr AS type PAREN_RIGHT;
canCast
: CAN_CAST PAREN_LEFT expr AS type PAREN_RIGHT;
extract
: EXTRACT PAREN_LEFT IDENTIFIER FROM rhs=expr PAREN_RIGHT;
trimFunction
: func=TRIM PAREN_LEFT ( mod=IDENTIFIER? sub=expr? FROM )? target=expr PAREN_RIGHT;
dateFunction
: func=(DATE_ADD|DATE_DIFF) PAREN_LEFT dt=IDENTIFIER COMMA expr COMMA expr PAREN_RIGHT;
// SQL-99 10.4 — <routine invocation> ::= <routine name> <SQL argument list>
functionCall
: functionName PAREN_LEFT ( expr ( COMMA expr )* )? PAREN_RIGHT
;
// SQL-99 10.4 — <routine name> ::= [ <schema name> <period> ] <qualified identifier>
functionName
: (qualifier+=symbolPrimitive PERIOD)* name=( CHAR_LENGTH | CHARACTER_LENGTH | OCTET_LENGTH | BIT_LENGTH | UPPER | LOWER | SIZE | EXISTS | COUNT | MOD ) # FunctionNameReserved
| (qualifier+=symbolPrimitive PERIOD)* name=symbolPrimitive # FunctionNameSymbol
;
pathStep
: BRACKET_LEFT key=expr BRACKET_RIGHT # PathStepIndexExpr
| BRACKET_LEFT all=ASTERISK BRACKET_RIGHT # PathStepIndexAll
| PERIOD key=symbolPrimitive # PathStepDotExpr
| PERIOD all=ASTERISK # PathStepDotAll
;
exprGraphMatchMany
: PAREN_LEFT exprPrimary MATCH gpmlPatternList PAREN_RIGHT ;
exprGraphMatchOne
: exprPrimary MATCH gpmlPattern ;
parameter
: QUESTION_MARK;
varRefExpr
: qualifier=AT_SIGN? ident=(IDENTIFIER|IDENTIFIER_QUOTED) # VariableIdentifier
| qualifier=AT_SIGN? key=nonReservedKeywords # VariableKeyword
;
nonReservedKeywords
: EXCLUDED
;
/**
*
* LITERALS & TYPES
*
*/
collection
: array
| bag
;
array
: BRACKET_LEFT ( expr ( COMMA expr )* )? BRACKET_RIGHT;
bag
: ANGLE_LEFT ANGLE_LEFT ( expr ( COMMA expr )* )? ANGLE_RIGHT ANGLE_RIGHT;
tuple
: BRACE_LEFT ( pair ( COMMA pair )* )? BRACE_RIGHT;
pair
: lhs=expr COLON rhs=expr;
literal
: NULL # LiteralNull
| MISSING # LiteralMissing
| TRUE # LiteralTrue
| FALSE # LiteralFalse
| LITERAL_STRING # LiteralString
| LITERAL_INTEGER # LiteralInteger
| LITERAL_DECIMAL # LiteralDecimal
| ION_CLOSURE # LiteralIon
| DATE LITERAL_STRING # LiteralDate
| TIME ( PAREN_LEFT LITERAL_INTEGER PAREN_RIGHT )? (WITH TIME ZONE)? LITERAL_STRING # LiteralTime
| TIMESTAMP ( PAREN_LEFT LITERAL_INTEGER PAREN_RIGHT )? (WITH TIME ZONE)? LITERAL_STRING # LiteralTimestamp
;
type
: datatype=(
NULL | BOOL | BOOLEAN | SMALLINT | INTEGER2 | INT2 | INTEGER | INT | INTEGER4 | INT4
| INTEGER8 | INT8 | BIGINT | REAL | CHAR | CHARACTER | MISSING
| STRING | SYMBOL | BLOB | CLOB | DATE | SEXP | BAG | ANY
) # TypeAtomic
| datatype=(STRUCT|TUPLE|LIST|ARRAY) # TypeComplexUnparameterized
| datatype=DOUBLE PRECISION # TypeAtomic
| datatype=(CHARACTER|CHAR|FLOAT|VARCHAR) ( PAREN_LEFT arg0=LITERAL_INTEGER PAREN_RIGHT )? # TypeArgSingle
| CHARACTER VARYING ( PAREN_LEFT arg0=LITERAL_INTEGER PAREN_RIGHT )? # TypeVarChar
| datatype=(DECIMAL|DEC|NUMERIC) ( PAREN_LEFT arg0=LITERAL_INTEGER ( COMMA arg1=LITERAL_INTEGER )? PAREN_RIGHT )? # TypeArgDouble
| datatype=(TIME|TIMESTAMP) ( PAREN_LEFT precision=LITERAL_INTEGER PAREN_RIGHT )? (WITH TIME ZONE)? # TypeTimeZone
| datatype=(STRUCT|TUPLE) (ANGLE_LEFT structField ( COMMA structField )* ANGLE_RIGHT) # TypeStruct
| datatype=(LIST|ARRAY) ANGLE_LEFT type ANGLE_RIGHT # TypeList
| symbolPrimitive # TypeCustom
;
structField
: columnName OPTIONAL? COLON type columnConstraint* comment?
;