forked from apache/cassandra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Parser.g
1895 lines (1689 loc) · 73.4 KB
/
Parser.g
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 to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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.
*/
parser grammar Parser;
options {
language = Java;
}
@members {
private final List<ErrorListener> listeners = new ArrayList<ErrorListener>();
protected final List<ColumnIdentifier> bindVariables = new ArrayList<ColumnIdentifier>();
public static final Set<String> reservedTypeNames = new HashSet<String>()
{{
add("byte");
add("complex");
add("enum");
add("date");
add("interval");
add("macaddr");
add("bitstring");
}};
public AbstractMarker.Raw newBindVariables(ColumnIdentifier name)
{
AbstractMarker.Raw marker = new AbstractMarker.Raw(bindVariables.size());
bindVariables.add(name);
return marker;
}
public AbstractMarker.INRaw newINBindVariables(ColumnIdentifier name)
{
AbstractMarker.INRaw marker = new AbstractMarker.INRaw(bindVariables.size());
bindVariables.add(name);
return marker;
}
public Tuples.Raw newTupleBindVariables(ColumnIdentifier name)
{
Tuples.Raw marker = new Tuples.Raw(bindVariables.size());
bindVariables.add(name);
return marker;
}
public Tuples.INRaw newTupleINBindVariables(ColumnIdentifier name)
{
Tuples.INRaw marker = new Tuples.INRaw(bindVariables.size());
bindVariables.add(name);
return marker;
}
public Json.Marker newJsonBindVariables(ColumnIdentifier name)
{
Json.Marker marker = new Json.Marker(bindVariables.size());
bindVariables.add(name);
return marker;
}
public void addErrorListener(ErrorListener listener)
{
this.listeners.add(listener);
}
public void removeErrorListener(ErrorListener listener)
{
this.listeners.remove(listener);
}
public void displayRecognitionError(String[] tokenNames, RecognitionException e)
{
for (int i = 0, m = listeners.size(); i < m; i++)
listeners.get(i).syntaxError(this, tokenNames, e);
}
protected void addRecognitionError(String msg)
{
for (int i = 0, m = listeners.size(); i < m; i++)
listeners.get(i).syntaxError(this, msg);
}
public Map<String, String> convertPropertyMap(Maps.Literal map)
{
if (map == null || map.entries == null || map.entries.isEmpty())
return Collections.<String, String>emptyMap();
Map<String, String> res = new HashMap<>(map.entries.size());
for (Pair<Term.Raw, Term.Raw> entry : map.entries)
{
// Because the parser tries to be smart and recover on error (to
// allow displaying more than one error I suppose), we have null
// entries in there. Just skip those, a proper error will be thrown in the end.
if (entry.left == null || entry.right == null)
break;
if (!(entry.left instanceof Constants.Literal))
{
String msg = "Invalid property name: " + entry.left;
if (entry.left instanceof AbstractMarker.Raw)
msg += " (bind variables are not supported in DDL queries)";
addRecognitionError(msg);
break;
}
if (!(entry.right instanceof Constants.Literal))
{
String msg = "Invalid property value: " + entry.right + " for property: " + entry.left;
if (entry.right instanceof AbstractMarker.Raw)
msg += " (bind variables are not supported in DDL queries)";
addRecognitionError(msg);
break;
}
if (res.put(((Constants.Literal)entry.left).getRawText(), ((Constants.Literal)entry.right).getRawText()) != null)
{
addRecognitionError(String.format("Multiple definition for property " + ((Constants.Literal)entry.left).getRawText()));
}
}
return res;
}
public void addRawUpdate(List<Pair<ColumnIdentifier, Operation.RawUpdate>> operations, ColumnIdentifier key, Operation.RawUpdate update)
{
for (Pair<ColumnIdentifier, Operation.RawUpdate> p : operations)
{
if (p.left.equals(key) && !p.right.isCompatibleWith(update))
addRecognitionError("Multiple incompatible setting of column " + key);
}
operations.add(Pair.create(key, update));
}
public Set<Permission> filterPermissions(Set<Permission> permissions, IResource resource)
{
if (resource == null)
return Collections.emptySet();
Set<Permission> filtered = new HashSet<>(permissions);
filtered.retainAll(resource.applicablePermissions());
if (filtered.isEmpty())
addRecognitionError("Resource type " + resource.getClass().getSimpleName() +
" does not support any of the requested permissions");
return filtered;
}
public String canonicalizeObjectName(String s, boolean enforcePattern)
{
// these two conditions are here because technically they are valid
// ObjectNames, but we want to restrict their use without adding unnecessary
// work to JMXResource construction as that also happens on hotter code paths
if ("".equals(s))
addRecognitionError("Empty JMX object name supplied");
if ("*:*".equals(s))
addRecognitionError("Please use ALL MBEANS instead of wildcard pattern");
try
{
javax.management.ObjectName objectName = javax.management.ObjectName.getInstance(s);
if (enforcePattern && !objectName.isPattern())
addRecognitionError("Plural form used, but non-pattern JMX object name specified (" + s + ")");
return objectName.getCanonicalName();
}
catch (javax.management.MalformedObjectNameException e)
{
addRecognitionError(s + " is not a valid JMX object name");
return s;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Recovery methods are overridden to avoid wasting work on recovering from errors when the result will be
// ignored anyway.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Override
protected Object recoverFromMismatchedToken(IntStream input, int ttype, BitSet follow) throws RecognitionException
{
throw new MismatchedTokenException(ttype, input);
}
@Override
public void recover(IntStream input, RecognitionException re)
{
// Do nothing.
}
}
/** STATEMENTS **/
cqlStatement returns [CQLStatement.Raw stmt]
@after{ if (stmt != null) stmt.setBindVariables(bindVariables); }
: st1= selectStatement { $stmt = st1; }
| st2= insertStatement { $stmt = st2; }
| st3= updateStatement { $stmt = st3; }
| st4= batchStatement { $stmt = st4; }
| st5= deleteStatement { $stmt = st5; }
| st6= useStatement { $stmt = st6; }
| st7= truncateStatement { $stmt = st7; }
| st8= createKeyspaceStatement { $stmt = st8; }
| st9= createTableStatement { $stmt = st9; }
| st10=createIndexStatement { $stmt = st10; }
| st11=dropKeyspaceStatement { $stmt = st11; }
| st12=dropTableStatement { $stmt = st12; }
| st13=dropIndexStatement { $stmt = st13; }
| st14=alterTableStatement { $stmt = st14; }
| st15=alterKeyspaceStatement { $stmt = st15; }
| st16=grantPermissionsStatement { $stmt = st16; }
| st17=revokePermissionsStatement { $stmt = st17; }
| st18=listPermissionsStatement { $stmt = st18; }
| st19=createUserStatement { $stmt = st19; }
| st20=alterUserStatement { $stmt = st20; }
| st21=dropUserStatement { $stmt = st21; }
| st22=listUsersStatement { $stmt = st22; }
| st23=createTriggerStatement { $stmt = st23; }
| st24=dropTriggerStatement { $stmt = st24; }
| st25=createTypeStatement { $stmt = st25; }
| st26=alterTypeStatement { $stmt = st26; }
| st27=dropTypeStatement { $stmt = st27; }
| st28=createFunctionStatement { $stmt = st28; }
| st29=dropFunctionStatement { $stmt = st29; }
| st30=createAggregateStatement { $stmt = st30; }
| st31=dropAggregateStatement { $stmt = st31; }
| st32=createRoleStatement { $stmt = st32; }
| st33=alterRoleStatement { $stmt = st33; }
| st34=dropRoleStatement { $stmt = st34; }
| st35=listRolesStatement { $stmt = st35; }
| st36=grantRoleStatement { $stmt = st36; }
| st37=revokeRoleStatement { $stmt = st37; }
| st38=createMaterializedViewStatement { $stmt = st38; }
| st39=dropMaterializedViewStatement { $stmt = st39; }
| st40=alterMaterializedViewStatement { $stmt = st40; }
| st41=describeStatement { $stmt = st41; }
;
/*
* USE <KEYSPACE>;
*/
useStatement returns [UseStatement stmt]
: K_USE ks=keyspaceName { $stmt = new UseStatement(ks); }
;
/**
* SELECT <expression>
* FROM <CF>
* WHERE KEY = "key1" AND COL > 1 AND COL < 100
* LIMIT <NUMBER>;
*/
selectStatement returns [SelectStatement.RawStatement expr]
@init {
Term.Raw limit = null;
Term.Raw perPartitionLimit = null;
Map<ColumnIdentifier, Boolean> orderings = new LinkedHashMap<>();
List<ColumnIdentifier> groups = new ArrayList<>();
boolean allowFiltering = false;
boolean isJson = false;
}
: K_SELECT
// json is a valid column name. By consequence, we need to resolve the ambiguity for "json - json"
( (K_JSON selectClause)=> K_JSON { isJson = true; } )? sclause=selectClause
K_FROM cf=columnFamilyName
( K_WHERE wclause=whereClause )?
( K_GROUP K_BY groupByClause[groups] ( ',' groupByClause[groups] )* )?
( K_ORDER K_BY orderByClause[orderings] ( ',' orderByClause[orderings] )* )?
( K_PER K_PARTITION K_LIMIT rows=intValue { perPartitionLimit = rows; } )?
( K_LIMIT rows=intValue { limit = rows; } )?
( K_ALLOW K_FILTERING { allowFiltering = true; } )?
{
SelectStatement.Parameters params = new SelectStatement.Parameters(orderings,
groups,
$sclause.isDistinct,
allowFiltering,
isJson);
WhereClause where = wclause == null ? WhereClause.empty() : wclause.build();
$expr = new SelectStatement.RawStatement(cf, params, $sclause.selectors, where, limit, perPartitionLimit);
}
;
selectClause returns [boolean isDistinct, List<RawSelector> selectors]
@init{ $isDistinct = false; }
// distinct is a valid column name. By consequence, we need to resolve the ambiguity for "distinct - distinct"
: (K_DISTINCT selectors)=> K_DISTINCT s=selectors { $isDistinct = true; $selectors = s; }
| s=selectors { $selectors = s; }
;
selectors returns [List<RawSelector> expr]
: t1=selector { $expr = new ArrayList<RawSelector>(); $expr.add(t1); } (',' tN=selector { $expr.add(tN); })*
| '\*' { $expr = Collections.<RawSelector>emptyList();}
;
selector returns [RawSelector s]
@init{ ColumnIdentifier alias = null; }
: us=unaliasedSelector (K_AS c=noncol_ident { alias = c; })? { $s = new RawSelector(us, alias); }
;
unaliasedSelector returns [Selectable.Raw s]
: a=selectionAddition {$s = a;}
;
selectionAddition returns [Selectable.Raw s]
: l=selectionMultiplication {$s = l;}
( '+' r=selectionMultiplication {$s = Selectable.WithFunction.Raw.newOperation('+', $s, r);}
| '-' r=selectionMultiplication {$s = Selectable.WithFunction.Raw.newOperation('-', $s, r);}
)*
;
selectionMultiplication returns [Selectable.Raw s]
: l=selectionGroup {$s = l;}
( '\*' r=selectionGroup {$s = Selectable.WithFunction.Raw.newOperation('*', $s, r);}
| '/' r=selectionGroup {$s = Selectable.WithFunction.Raw.newOperation('/', $s, r);}
| '%' r=selectionGroup {$s = Selectable.WithFunction.Raw.newOperation('\%', $s, r);}
)*
;
selectionGroup returns [Selectable.Raw s]
: (selectionGroupWithField)=> f=selectionGroupWithField { $s=f; }
| g=selectionGroupWithoutField { $s=g; }
| '-' g=selectionGroup {$s = Selectable.WithFunction.Raw.newNegation(g);}
;
selectionGroupWithField returns [Selectable.Raw s]
: g=selectionGroupWithoutField m=selectorModifier[g] {$s = m;}
;
selectorModifier[Selectable.Raw receiver] returns [Selectable.Raw s]
: f=fieldSelectorModifier[receiver] m=selectorModifier[f] { $s = m; }
| '[' ss=collectionSubSelection[receiver] ']' m=selectorModifier[ss] { $s = m; }
| { $s = receiver; }
;
fieldSelectorModifier[Selectable.Raw receiver] returns [Selectable.Raw s]
: '.' fi=fident { $s = new Selectable.WithFieldSelection.Raw(receiver, fi); }
;
collectionSubSelection [Selectable.Raw receiver] returns [Selectable.Raw s]
@init { boolean isSlice=false; }
: ( t1=term ( { isSlice=true; } RANGE (t2=term)? )?
| RANGE { isSlice=true; } t2=term
) {
$s = isSlice
? new Selectable.WithSliceSelection.Raw(receiver, t1, t2)
: new Selectable.WithElementSelection.Raw(receiver, t1);
}
;
selectionGroupWithoutField returns [Selectable.Raw s]
@init { Selectable.Raw tmp = null; }
@after { $s = tmp; }
: sn=simpleUnaliasedSelector { tmp=sn; }
| (selectionTypeHint)=> h=selectionTypeHint { tmp=h; }
| t=selectionTupleOrNestedSelector { tmp=t; }
| l=selectionList { tmp=l; }
| m=selectionMapOrSet { tmp=m; }
// UDTs are equivalent to maps from the syntax point of view, so the final decision will be done in Selectable.WithMapOrUdt
;
selectionTypeHint returns [Selectable.Raw s]
: '(' ct=comparatorType ')' a=selectionGroupWithoutField { $s = new Selectable.WithTypeHint.Raw(ct, a); }
;
selectionList returns [Selectable.Raw s]
@init { List<Selectable.Raw> l = new ArrayList<>(); }
@after { $s = new Selectable.WithList.Raw(l); }
: '[' ( t1=unaliasedSelector { l.add(t1); } ( ',' tn=unaliasedSelector { l.add(tn); } )* )? ']'
;
selectionMapOrSet returns [Selectable.Raw s]
: '{' t1=unaliasedSelector ( m=selectionMap[t1] { $s = m; } | st=selectionSet[t1] { $s = st; }) '}'
| '{' '}' { $s = new Selectable.WithSet.Raw(Collections.emptyList());}
;
selectionMap [Selectable.Raw k1] returns [Selectable.Raw s]
@init { List<Pair<Selectable.Raw, Selectable.Raw>> m = new ArrayList<>(); }
@after { $s = new Selectable.WithMapOrUdt.Raw(m); }
: ':' v1=unaliasedSelector { m.add(Pair.create(k1, v1)); } ( ',' kn=unaliasedSelector ':' vn=unaliasedSelector { m.add(Pair.create(kn, vn)); } )*
;
selectionSet [Selectable.Raw t1] returns [Selectable.Raw s]
@init { List<Selectable.Raw> l = new ArrayList<>(); l.add(t1); }
@after { $s = new Selectable.WithSet.Raw(l); }
: ( ',' tn=unaliasedSelector { l.add(tn); } )*
;
selectionTupleOrNestedSelector returns [Selectable.Raw s]
@init { List<Selectable.Raw> l = new ArrayList<>(); }
@after { $s = new Selectable.BetweenParenthesesOrWithTuple.Raw(l); }
: '(' t1=unaliasedSelector { l.add(t1); } (',' tn=unaliasedSelector { l.add(tn); } )* ')'
;
/*
* A single selection. The core of it is selecting a column, but we also allow any term and function, as well as
* sub-element selection for UDT.
*/
simpleUnaliasedSelector returns [Selectable.Raw s]
: c=sident { $s = c; }
| l=selectionLiteral { $s = new Selectable.WithTerm.Raw(l); }
| f=selectionFunction { $s = f; }
;
selectionFunction returns [Selectable.Raw s]
: K_COUNT '(' '\*' ')' { $s = Selectable.WithFunction.Raw.newCountRowsFunction(); }
| K_WRITETIME '(' c=sident ')' { $s = new Selectable.WritetimeOrTTL.Raw(c, true); }
| K_TTL '(' c=sident ')' { $s = new Selectable.WritetimeOrTTL.Raw(c, false); }
| K_CAST '(' sn=unaliasedSelector K_AS t=native_type ')' {$s = new Selectable.WithCast.Raw(sn, t);}
| f=functionName args=selectionFunctionArgs { $s = new Selectable.WithFunction.Raw(f, args); }
;
selectionLiteral returns [Term.Raw value]
: c=constant { $value = c; }
| K_NULL { $value = Constants.NULL_LITERAL; }
| ':' id=noncol_ident { $value = newBindVariables(id); }
| QMARK { $value = newBindVariables(null); }
;
selectionFunctionArgs returns [List<Selectable.Raw> a]
@init{ $a = new ArrayList<>(); }
: '(' (s1=unaliasedSelector { $a.add(s1); }
( ',' sn=unaliasedSelector { $a.add(sn); } )*)?
')'
;
sident returns [Selectable.RawIdentifier id]
: t=IDENT { $id = Selectable.RawIdentifier.forUnquoted($t.text); }
| t=QUOTED_NAME { $id = Selectable.RawIdentifier.forQuoted($t.text); }
| k=unreserved_keyword { $id = Selectable.RawIdentifier.forUnquoted(k); }
;
whereClause returns [WhereClause.Builder clause]
@init{ $clause = new WhereClause.Builder(); }
: relationOrExpression[$clause] (K_AND relationOrExpression[$clause])*
;
relationOrExpression [WhereClause.Builder clause]
: relation[$clause]
| customIndexExpression[$clause]
;
customIndexExpression [WhereClause.Builder clause]
@init{QualifiedName name = new QualifiedName();}
: 'expr(' idxName[name] ',' t=term ')' { clause.add(new CustomIndexExpression(name, t));}
;
orderByClause[Map<ColumnIdentifier, Boolean> orderings]
@init{
boolean reversed = false;
}
: c=cident (K_ASC | K_DESC { reversed = true; })? { orderings.put(c, reversed); }
;
groupByClause[List<ColumnIdentifier> groups]
: c=cident { groups.add(c); }
;
/**
* INSERT INTO <CF> (<column>, <column>, <column>, ...)
* VALUES (<value>, <value>, <value>, ...)
* USING TIMESTAMP <long>;
*
*/
insertStatement returns [ModificationStatement.Parsed expr]
: K_INSERT K_INTO cf=columnFamilyName
( st1=normalInsertStatement[cf] { $expr = st1; }
| K_JSON st2=jsonInsertStatement[cf] { $expr = st2; })
;
normalInsertStatement [QualifiedName qn] returns [UpdateStatement.ParsedInsert expr]
@init {
Attributes.Raw attrs = new Attributes.Raw();
List<ColumnIdentifier> columnNames = new ArrayList<>();
List<Term.Raw> values = new ArrayList<>();
boolean ifNotExists = false;
}
: '(' c1=cident { columnNames.add(c1); } ( ',' cn=cident { columnNames.add(cn); } )* ')'
K_VALUES
'(' v1=term { values.add(v1); } ( ',' vn=term { values.add(vn); } )* ')'
( K_IF K_NOT K_EXISTS { ifNotExists = true; } )?
( usingClause[attrs] )?
{
$expr = new UpdateStatement.ParsedInsert(qn, attrs, columnNames, values, ifNotExists);
}
;
jsonInsertStatement [QualifiedName qn] returns [UpdateStatement.ParsedInsertJson expr]
@init {
Attributes.Raw attrs = new Attributes.Raw();
boolean ifNotExists = false;
boolean defaultUnset = false;
}
: val=jsonValue
( K_DEFAULT ( K_NULL | ( { defaultUnset = true; } K_UNSET) ) )?
( K_IF K_NOT K_EXISTS { ifNotExists = true; } )?
( usingClause[attrs] )?
{
$expr = new UpdateStatement.ParsedInsertJson(qn, attrs, val, defaultUnset, ifNotExists);
}
;
jsonValue returns [Json.Raw value]
: s=STRING_LITERAL { $value = new Json.Literal($s.text); }
| ':' id=noncol_ident { $value = newJsonBindVariables(id); }
| QMARK { $value = newJsonBindVariables(null); }
;
usingClause[Attributes.Raw attrs]
: K_USING usingClauseObjective[attrs] ( K_AND usingClauseObjective[attrs] )*
;
usingClauseObjective[Attributes.Raw attrs]
: K_TIMESTAMP ts=intValue { attrs.timestamp = ts; }
| K_TTL t=intValue { attrs.timeToLive = t; }
;
/**
* UPDATE <CF>
* USING TIMESTAMP <long>
* SET name1 = value1, name2 = value2
* WHERE key = value;
* [IF (EXISTS | name = value, ...)];
*/
updateStatement returns [UpdateStatement.ParsedUpdate expr]
@init {
Attributes.Raw attrs = new Attributes.Raw();
List<Pair<ColumnIdentifier, Operation.RawUpdate>> operations = new ArrayList<>();
boolean ifExists = false;
}
: K_UPDATE cf=columnFamilyName
( usingClause[attrs] )?
K_SET columnOperation[operations] (',' columnOperation[operations])*
K_WHERE wclause=whereClause
( K_IF ( K_EXISTS { ifExists = true; } | conditions=updateConditions ))?
{
$expr = new UpdateStatement.ParsedUpdate(cf,
attrs,
operations,
wclause.build(),
conditions == null ? Collections.<Pair<ColumnIdentifier, ColumnCondition.Raw>>emptyList() : conditions,
ifExists);
}
;
updateConditions returns [List<Pair<ColumnIdentifier, ColumnCondition.Raw>> conditions]
@init { conditions = new ArrayList<Pair<ColumnIdentifier, ColumnCondition.Raw>>(); }
: columnCondition[conditions] ( K_AND columnCondition[conditions] )*
;
/**
* DELETE name1, name2
* FROM <CF>
* USING TIMESTAMP <long>
* WHERE KEY = keyname
[IF (EXISTS | name = value, ...)];
*/
deleteStatement returns [DeleteStatement.Parsed expr]
@init {
Attributes.Raw attrs = new Attributes.Raw();
List<Operation.RawDeletion> columnDeletions = Collections.emptyList();
boolean ifExists = false;
}
: K_DELETE ( dels=deleteSelection { columnDeletions = dels; } )?
K_FROM cf=columnFamilyName
( usingClauseDelete[attrs] )?
K_WHERE wclause=whereClause
( K_IF ( K_EXISTS { ifExists = true; } | conditions=updateConditions ))?
{
$expr = new DeleteStatement.Parsed(cf,
attrs,
columnDeletions,
wclause.build(),
conditions == null ? Collections.<Pair<ColumnIdentifier, ColumnCondition.Raw>>emptyList() : conditions,
ifExists);
}
;
deleteSelection returns [List<Operation.RawDeletion> operations]
: { $operations = new ArrayList<Operation.RawDeletion>(); }
t1=deleteOp { $operations.add(t1); }
(',' tN=deleteOp { $operations.add(tN); })*
;
deleteOp returns [Operation.RawDeletion op]
: c=cident { $op = new Operation.ColumnDeletion(c); }
| c=cident '[' t=term ']' { $op = new Operation.ElementDeletion(c, t); }
| c=cident '.' field=fident { $op = new Operation.FieldDeletion(c, field); }
;
usingClauseDelete[Attributes.Raw attrs]
: K_USING K_TIMESTAMP ts=intValue { attrs.timestamp = ts; }
;
/**
* BEGIN BATCH
* UPDATE <CF> SET name1 = value1 WHERE KEY = keyname1;
* UPDATE <CF> SET name2 = value2 WHERE KEY = keyname2;
* UPDATE <CF> SET name3 = value3 WHERE KEY = keyname3;
* ...
* APPLY BATCH
*
* OR
*
* BEGIN BATCH
* INSERT INTO <CF> (KEY, <name>) VALUES ('<key>', '<value>');
* INSERT INTO <CF> (KEY, <name>) VALUES ('<key>', '<value>');
* ...
* APPLY BATCH
*
* OR
*
* BEGIN BATCH
* DELETE name1, name2 FROM <CF> WHERE key = <key>
* DELETE name3, name4 FROM <CF> WHERE key = <key>
* ...
* APPLY BATCH
*/
batchStatement returns [BatchStatement.Parsed expr]
@init {
BatchStatement.Type type = BatchStatement.Type.LOGGED;
List<ModificationStatement.Parsed> statements = new ArrayList<ModificationStatement.Parsed>();
Attributes.Raw attrs = new Attributes.Raw();
}
: K_BEGIN
( K_UNLOGGED { type = BatchStatement.Type.UNLOGGED; } | K_COUNTER { type = BatchStatement.Type.COUNTER; } )?
K_BATCH ( usingClause[attrs] )?
( s=batchStatementObjective ';'? { statements.add(s); } )*
K_APPLY K_BATCH
{
$expr = new BatchStatement.Parsed(type, attrs, statements);
}
;
batchStatementObjective returns [ModificationStatement.Parsed statement]
: i=insertStatement { $statement = i; }
| u=updateStatement { $statement = u; }
| d=deleteStatement { $statement = d; }
;
createAggregateStatement returns [CreateAggregateStatement.Raw stmt]
@init {
boolean orReplace = false;
boolean ifNotExists = false;
List<CQL3Type.Raw> argTypes = new ArrayList<>();
}
: K_CREATE (K_OR K_REPLACE { orReplace = true; })?
K_AGGREGATE
(K_IF K_NOT K_EXISTS { ifNotExists = true; })?
fn=functionName
'('
(
v=comparatorType { argTypes.add(v); }
( ',' v=comparatorType { argTypes.add(v); } )*
)?
')'
K_SFUNC sfunc = allowedFunctionName
K_STYPE stype = comparatorType
(
K_FINALFUNC ffunc = allowedFunctionName
)?
(
K_INITCOND ival = term
)?
{ $stmt = new CreateAggregateStatement.Raw(fn, argTypes, stype, sfunc, ffunc, ival, orReplace, ifNotExists); }
;
dropAggregateStatement returns [DropAggregateStatement.Raw stmt]
@init {
boolean ifExists = false;
List<CQL3Type.Raw> argTypes = new ArrayList<>();
boolean argsSpecified = false;
}
: K_DROP K_AGGREGATE
(K_IF K_EXISTS { ifExists = true; } )?
fn=functionName
(
'('
(
v=comparatorType { argTypes.add(v); }
( ',' v=comparatorType { argTypes.add(v); } )*
)?
')'
{ argsSpecified = true; }
)?
{ $stmt = new DropAggregateStatement.Raw(fn, argTypes, argsSpecified, ifExists); }
;
createFunctionStatement returns [CreateFunctionStatement.Raw stmt]
@init {
boolean orReplace = false;
boolean ifNotExists = false;
List<ColumnIdentifier> argNames = new ArrayList<>();
List<CQL3Type.Raw> argTypes = new ArrayList<>();
boolean calledOnNullInput = false;
}
: K_CREATE (K_OR K_REPLACE { orReplace = true; })?
K_FUNCTION
(K_IF K_NOT K_EXISTS { ifNotExists = true; })?
fn=functionName
'('
(
k=noncol_ident v=comparatorType { argNames.add(k); argTypes.add(v); }
( ',' k=noncol_ident v=comparatorType { argNames.add(k); argTypes.add(v); } )*
)?
')'
( (K_RETURNS K_NULL) | (K_CALLED { calledOnNullInput=true; })) K_ON K_NULL K_INPUT
K_RETURNS returnType = comparatorType
K_LANGUAGE language = IDENT
K_AS body = STRING_LITERAL
{ $stmt = new CreateFunctionStatement.Raw(
fn, argNames, argTypes, returnType, calledOnNullInput, $language.text.toLowerCase(), $body.text, orReplace, ifNotExists);
}
;
dropFunctionStatement returns [DropFunctionStatement.Raw stmt]
@init {
boolean ifExists = false;
List<CQL3Type.Raw> argTypes = new ArrayList<>();
boolean argsSpecified = false;
}
: K_DROP K_FUNCTION
(K_IF K_EXISTS { ifExists = true; } )?
fn=functionName
(
'('
(
v=comparatorType { argTypes.add(v); }
( ',' v=comparatorType { argTypes.add(v); } )*
)?
')'
{ argsSpecified = true; }
)?
{ $stmt = new DropFunctionStatement.Raw(fn, argTypes, argsSpecified, ifExists); }
;
/**
* CREATE KEYSPACE [IF NOT EXISTS] <KEYSPACE> WITH attr1 = value1 AND attr2 = value2;
*/
createKeyspaceStatement returns [CreateKeyspaceStatement.Raw stmt]
@init {
KeyspaceAttributes attrs = new KeyspaceAttributes();
boolean ifNotExists = false;
}
: K_CREATE K_KEYSPACE (K_IF K_NOT K_EXISTS { ifNotExists = true; } )? ks=keyspaceName
K_WITH properties[attrs] { $stmt = new CreateKeyspaceStatement.Raw(ks, attrs, ifNotExists); }
;
/**
* CREATE TABLE [IF NOT EXISTS] <CF> (
* <name1> <type>,
* <name2> <type>,
* <name3> <type>
* ) WITH <property> = <value> AND ...;
*/
createTableStatement returns [CreateTableStatement.Raw stmt]
@init { boolean ifNotExists = false; }
: K_CREATE K_COLUMNFAMILY (K_IF K_NOT K_EXISTS { ifNotExists = true; } )?
cf=columnFamilyName { $stmt = new CreateTableStatement.Raw(cf, ifNotExists); }
tableDefinition[stmt]
;
tableDefinition[CreateTableStatement.Raw stmt]
: '(' tableColumns[stmt] ( ',' tableColumns[stmt]? )* ')'
( K_WITH tableProperty[stmt] ( K_AND tableProperty[stmt] )*)?
;
tableColumns[CreateTableStatement.Raw stmt]
@init { boolean isStatic = false; }
: k=ident v=comparatorType (K_STATIC { isStatic = true; })? { $stmt.addColumn(k, v, isStatic); }
(K_PRIMARY K_KEY { $stmt.setPartitionKeyColumn(k); })?
| K_PRIMARY K_KEY '(' tablePartitionKey[stmt] (',' c=ident { $stmt.markClusteringColumn(c); } )* ')'
;
tablePartitionKey[CreateTableStatement.Raw stmt]
@init {List<ColumnIdentifier> l = new ArrayList<ColumnIdentifier>();}
@after{ $stmt.setPartitionKeyColumns(l); }
: k1=ident { l.add(k1);}
| '(' k1=ident { l.add(k1); } ( ',' kn=ident { l.add(kn); } )* ')'
;
tableProperty[CreateTableStatement.Raw stmt]
: property[stmt.attrs]
| K_COMPACT K_STORAGE { throw new SyntaxException("COMPACT STORAGE tables are not allowed starting with version 4.0"); }
| K_CLUSTERING K_ORDER K_BY '(' tableClusteringOrder[stmt] (',' tableClusteringOrder[stmt])* ')'
;
tableClusteringOrder[CreateTableStatement.Raw stmt]
@init{ boolean ascending = true; }
: k=ident (K_ASC | K_DESC { ascending = false; } ) { $stmt.extendClusteringOrder(k, ascending); }
;
/**
* CREATE TYPE foo (
* <name1> <type1>,
* <name2> <type2>,
* ....
* )
*/
createTypeStatement returns [CreateTypeStatement.Raw stmt]
@init { boolean ifNotExists = false; }
: K_CREATE K_TYPE (K_IF K_NOT K_EXISTS { ifNotExists = true; } )?
tn=userTypeName { $stmt = new CreateTypeStatement.Raw(tn, ifNotExists); }
'(' typeColumns[stmt] ( ',' typeColumns[stmt]? )* ')'
;
typeColumns[CreateTypeStatement.Raw stmt]
: k=fident v=comparatorType { $stmt.addField(k, v); }
;
/**
* CREATE INDEX [IF NOT EXISTS] [indexName] ON <columnFamily> (<columnName>);
* CREATE CUSTOM INDEX [IF NOT EXISTS] [indexName] ON <columnFamily> (<columnName>) USING <indexClass>;
*/
createIndexStatement returns [CreateIndexStatement.Raw stmt]
@init {
IndexAttributes props = new IndexAttributes();
boolean ifNotExists = false;
QualifiedName name = new QualifiedName();
List<IndexTarget.Raw> targets = new ArrayList<>();
}
: K_CREATE (K_CUSTOM { props.isCustom = true; })? K_INDEX (K_IF K_NOT K_EXISTS { ifNotExists = true; } )?
(idxName[name])? K_ON cf=columnFamilyName '(' (indexIdent[targets] (',' indexIdent[targets])*)? ')'
(K_USING cls=STRING_LITERAL { props.customClass = $cls.text; })?
(K_WITH properties[props])?
{ $stmt = new CreateIndexStatement.Raw(cf, name, targets, props, ifNotExists); }
;
indexIdent [List<IndexTarget.Raw> targets]
: c=cident { $targets.add(IndexTarget.Raw.simpleIndexOn(c)); }
| K_VALUES '(' c=cident ')' { $targets.add(IndexTarget.Raw.valuesOf(c)); }
| K_KEYS '(' c=cident ')' { $targets.add(IndexTarget.Raw.keysOf(c)); }
| K_ENTRIES '(' c=cident ')' { $targets.add(IndexTarget.Raw.keysAndValuesOf(c)); }
| K_FULL '(' c=cident ')' { $targets.add(IndexTarget.Raw.fullCollection(c)); }
;
/**
* CREATE MATERIALIZED VIEW <viewName> AS
* SELECT <columns>
* FROM <CF>
* WHERE <pkColumns> IS NOT NULL
* PRIMARY KEY (<pkColumns>)
* WITH <property> = <value> AND ...;
*/
createMaterializedViewStatement returns [CreateViewStatement.Raw stmt]
@init {
boolean ifNotExists = false;
}
: K_CREATE K_MATERIALIZED K_VIEW (K_IF K_NOT K_EXISTS { ifNotExists = true; })? cf=columnFamilyName K_AS
K_SELECT sclause=selectors K_FROM basecf=columnFamilyName
(K_WHERE wclause=whereClause)?
{
WhereClause where = wclause == null ? WhereClause.empty() : wclause.build();
$stmt = new CreateViewStatement.Raw(basecf, cf, sclause, where, ifNotExists);
}
viewPrimaryKey[stmt]
( K_WITH viewProperty[stmt] ( K_AND viewProperty[stmt] )*)?
;
viewPrimaryKey[CreateViewStatement.Raw stmt]
: K_PRIMARY K_KEY '(' viewPartitionKey[stmt] (',' c=ident { $stmt.markClusteringColumn(c); } )* ')'
;
viewPartitionKey[CreateViewStatement.Raw stmt]
@init {List<ColumnIdentifier> l = new ArrayList<ColumnIdentifier>();}
@after{ $stmt.setPartitionKeyColumns(l); }
: k1=ident { l.add(k1);}
| '(' k1=ident { l.add(k1); } ( ',' kn=ident { l.add(kn); } )* ')'
;
viewProperty[CreateViewStatement.Raw stmt]
: property[stmt.attrs]
| K_COMPACT K_STORAGE { throw new SyntaxException("COMPACT STORAGE tables are not allowed starting with version 4.0"); }
| K_CLUSTERING K_ORDER K_BY '(' viewClusteringOrder[stmt] (',' viewClusteringOrder[stmt])* ')'
;
viewClusteringOrder[CreateViewStatement.Raw stmt]
@init{ boolean ascending = true; }
: k=ident (K_ASC | K_DESC { ascending = false; } ) { $stmt.extendClusteringOrder(k, ascending); }
;
/**
* CREATE TRIGGER triggerName ON columnFamily USING 'triggerClass';
*/
createTriggerStatement returns [CreateTriggerStatement.Raw stmt]
@init {
boolean ifNotExists = false;
}
: K_CREATE K_TRIGGER (K_IF K_NOT K_EXISTS { ifNotExists = true; } )? (name=ident)
K_ON cf=columnFamilyName K_USING cls=STRING_LITERAL
{ $stmt = new CreateTriggerStatement.Raw(cf, name.toString(), $cls.text, ifNotExists); }
;
/**
* DROP TRIGGER [IF EXISTS] triggerName ON columnFamily;
*/
dropTriggerStatement returns [DropTriggerStatement.Raw stmt]
@init { boolean ifExists = false; }
: K_DROP K_TRIGGER (K_IF K_EXISTS { ifExists = true; } )? (name=ident) K_ON cf=columnFamilyName
{ $stmt = new DropTriggerStatement.Raw(cf, name.toString(), ifExists); }
;
/**
* ALTER KEYSPACE <KS> WITH <property> = <value>;
*/
alterKeyspaceStatement returns [AlterKeyspaceStatement.Raw stmt]
@init { KeyspaceAttributes attrs = new KeyspaceAttributes(); }
: K_ALTER K_KEYSPACE ks=keyspaceName
K_WITH properties[attrs] { $stmt = new AlterKeyspaceStatement.Raw(ks, attrs); }
;
/**
* ALTER TABLE <table> ALTER <column> TYPE <newtype>;
* ALTER TABLE <table> ADD <column> <newtype>; | ALTER TABLE <table> ADD (<column> <newtype>,<column1> <newtype1>..... <column n> <newtype n>)
* ALTER TABLE <table> DROP <column>; | ALTER TABLE <table> DROP ( <column>,<column1>.....<column n>)
* ALTER TABLE <table> RENAME <column> TO <column>;
* ALTER TABLE <table> WITH <property> = <value>;
*/
alterTableStatement returns [AlterTableStatement.Raw stmt]
: K_ALTER K_COLUMNFAMILY cf=columnFamilyName { $stmt = new AlterTableStatement.Raw(cf); }
(
K_ALTER id=cident K_TYPE v=comparatorType { $stmt.alter(id, v); }
| K_ADD ( id=ident v=comparatorType b=isStaticColumn { $stmt.add(id, v, b); }
| ('(' id1=ident v1=comparatorType b1=isStaticColumn { $stmt.add(id1, v1, b1); }
( ',' idn=ident vn=comparatorType bn=isStaticColumn { $stmt.add(idn, vn, bn); } )* ')') )
| K_DROP ( id=ident { $stmt.drop(id); }
| ('(' id1=ident { $stmt.drop(id1); }
( ',' idn=ident { $stmt.drop(idn); } )* ')') )
( K_USING K_TIMESTAMP t=INTEGER { $stmt.timestamp(Long.parseLong(Constants.Literal.integer($t.text).getText())); } )?
| K_RENAME id1=ident K_TO toId1=ident { $stmt.rename(id1, toId1); }
( K_AND idn=ident K_TO toIdn=ident { $stmt.rename(idn, toIdn); } )*
| K_WITH properties[$stmt.attrs] { $stmt.attrs(); }
)
;
isStaticColumn returns [boolean isStaticColumn]
@init { boolean isStatic = false; }
: (K_STATIC { isStatic=true; })? { $isStaticColumn = isStatic; }
;
alterMaterializedViewStatement returns [AlterViewStatement.Raw stmt]
@init {
TableAttributes attrs = new TableAttributes();
}
: K_ALTER K_MATERIALIZED K_VIEW name=columnFamilyName
K_WITH properties[attrs]
{
$stmt = new AlterViewStatement.Raw(name, attrs);
}
;
/**
* ALTER TYPE <name> ALTER <field> TYPE <newtype>;
* ALTER TYPE <name> ADD <field> <newtype>;
* ALTER TYPE <name> RENAME <field> TO <newtype> AND ...;
*/
alterTypeStatement returns [AlterTypeStatement.Raw stmt]
: K_ALTER K_TYPE name=userTypeName { $stmt = new AlterTypeStatement.Raw(name); }
(
K_ALTER f=fident K_TYPE v=comparatorType { $stmt.alter(f, v); }
| K_ADD f=fident v=comparatorType { $stmt.add(f, v); }
| K_RENAME f1=fident K_TO toF1=fident { $stmt.rename(f1, toF1); }
( K_AND fn=fident K_TO toFn=fident { $stmt.rename(fn, toFn); } )*
)
;
/**
* DROP KEYSPACE [IF EXISTS] <KSP>;
*/
dropKeyspaceStatement returns [DropKeyspaceStatement.Raw stmt]
@init { boolean ifExists = false; }
: K_DROP K_KEYSPACE (K_IF K_EXISTS { ifExists = true; } )? ks=keyspaceName { $stmt = new DropKeyspaceStatement.Raw(ks, ifExists); }
;
/**
* DROP TABLE [IF EXISTS] <table>;
*/
dropTableStatement returns [DropTableStatement.Raw stmt]
@init { boolean ifExists = false; }