-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathJSqlParserCC.jjt
More file actions
12938 lines (11949 loc) · 401 KB
/
JSqlParserCC.jjt
File metadata and controls
12938 lines (11949 loc) · 401 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
/*
* #%L
* JSQLParser library
* %%
* Copyright (C) 2004 - 2021 JSQLParser
* %%
* Dual licensed under GNU LGPL 2.1 or Apache License 2.0
* #L%
*/
options {
IGNORE_CASE = true;
STATIC = false;
DEBUG_PARSER = false;
DEBUG_LOOKAHEAD = false;
DEBUG_TOKEN_MANAGER = false;
CACHE_TOKENS = false;
// FORCE_LA_CHECK = true;
UNICODE_INPUT = true;
JAVA_TEMPLATE_TYPE = "modern";
// JDK_VERSION = "1.8";
TOKEN_EXTENDS = "BaseToken";
COMMON_TOKEN_ACTION = true;
NODE_DEFAULT_VOID = true;
TRACK_TOKENS = true;
VISITOR = true;
GRAMMAR_ENCODING = "UTF-8";
KEEP_LINE_COLUMN = true;
// USER_CHAR_STREAM = false;
}
PARSER_BEGIN(CCJSqlParser)
package net.sf.jsqlparser.parser;
import java.lang.reflect.Field;
import java.lang.Integer;
import net.sf.jsqlparser.parser.feature.*;
import net.sf.jsqlparser.expression.*;
import net.sf.jsqlparser.expression.operators.arithmetic.*;
import net.sf.jsqlparser.expression.operators.conditional.*;
import net.sf.jsqlparser.expression.operators.relational.*;
import net.sf.jsqlparser.schema.*;
import net.sf.jsqlparser.statement.*;
import net.sf.jsqlparser.statement.analyze.*;
import net.sf.jsqlparser.statement.alter.*;
import net.sf.jsqlparser.statement.alter.sequence.*;
import net.sf.jsqlparser.statement.comment.*;
import net.sf.jsqlparser.statement.create.function.*;
import net.sf.jsqlparser.statement.create.index.*;
import net.sf.jsqlparser.statement.create.policy.*;
import net.sf.jsqlparser.statement.create.procedure.*;
import net.sf.jsqlparser.statement.create.schema.*;
import net.sf.jsqlparser.statement.create.synonym.*;
import net.sf.jsqlparser.statement.create.sequence.*;
import net.sf.jsqlparser.statement.create.table.*;
import net.sf.jsqlparser.statement.create.view.*;
import net.sf.jsqlparser.statement.delete.*;
import net.sf.jsqlparser.statement.drop.*;
import net.sf.jsqlparser.statement.insert.*;
import net.sf.jsqlparser.statement.execute.*;
import net.sf.jsqlparser.statement.piped.*;
import net.sf.jsqlparser.statement.select.*;
import net.sf.jsqlparser.statement.refresh.*;
import net.sf.jsqlparser.statement.show.*;
import net.sf.jsqlparser.statement.truncate.*;
import net.sf.jsqlparser.statement.update.*;
import net.sf.jsqlparser.statement.upsert.*;
import net.sf.jsqlparser.statement.merge.*;
import net.sf.jsqlparser.statement.grant.*;
import net.sf.jsqlparser.statement.imprt.*;
import net.sf.jsqlparser.statement.export.*;
import net.sf.jsqlparser.statement.lock.*;
import java.util.*;
import java.util.AbstractMap.SimpleEntry;
import net.sf.jsqlparser.statement.select.SetOperationList.SetOperationType;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The parser generated by JavaCC
*/
public class CCJSqlParser extends AbstractJSqlParser<CCJSqlParser> {
public final static Logger LOGGER = Logger.getLogger(CCJSqlParser.class.getName());
public int bracketsCounter = 0;
public int caseCounter = 0;
public boolean interrupted = false;
public CCJSqlParser withConfiguration(FeatureConfiguration configuration) {
token_source.configuration = configuration;
return this;
}
public FeatureConfiguration getConfiguration() {
return token_source.configuration;
}
public CCJSqlParser me () {
return this;
}
private void linkAST(ASTNodeAccess access, Node node) {
access.setASTNode(node);
node.jjtSetValue(access);
}
public Node getASTRoot() {
return jjtree.rootNode();
}
private static class ObjectNames {
private final List<String> names;
private final List<String> delimiters;
public ObjectNames(List<String> names, List<String> delimiters) {
this.names = names;
this.delimiters = delimiters;
}
public List<String> getNames() {
return names;
}
public List<String> getDelimiters() {
return delimiters;
}
}
private static void appendWhitespaceFromTokenGap(StringBuilder buffer, Token prev, Token curr) {
if (prev == null) return;
int lineDiff = curr.beginLine - prev.endLine;
if (lineDiff > 0) {
for (int i = 0; i < lineDiff; i++) buffer.append('\n');
for (int i = 1; i < curr.beginColumn; i++) buffer.append(' ');
} else {
int spaceCount = curr.beginColumn - prev.endColumn - 1;
for (int i = 0; i < spaceCount; i++) buffer.append(' ');
}
}
private static void appendTokenImageAndTrackDelimiter(StringBuilder buffer, Deque<Character> windowQueue,
int delimiterLength, String image, String tag) {
for (char ch : image.toCharArray()) {
buffer.append(ch);
windowQueue.addLast(ch);
if (windowQueue.size() > delimiterLength) {
windowQueue.removeFirst();
}
}
}
private static boolean endsWithDelimiter(Deque<Character> windowQueue, String delimiter) {
if (windowQueue.size() != delimiter.length()) return false;
int i = 0;
for (char ch : windowQueue) {
if (ch != delimiter.charAt(i++)) return false;
}
return true;
}
/**
* Checks whether the given token can start the operator in a RegularCondition
* (comparison operators, JSON operators, regex operators, geometry distance, etc.)
*
* Used to avoid expensive syntactic lookaheads like LOOKAHEAD(RegularCondition()).
* By the time this is called, lower-precedence operators like "-" (subtraction)
* and "||" (concatenation) have already been consumed by SimpleExpression,
* so seeing them here means they are comparison-level operators.
*/
protected boolean isComparisonOperatorAhead() {
try {
Token token = getToken(1);
if (token.image.equals("(") && getToken(2).image.equals("+")) {
// Oracle (+) — only route to RegularConditionRHS if a real
// comparison operator follows after "(" "+" ")"
return isComparisonOperator(getToken(4));
}
return isComparisonOperator(token);
} catch (Exception e) {
return false;
}
}
protected static boolean isComparisonOperator(Token token) {
if (token.image == null || token.image.isEmpty()) {
return false;
}
switch (token.image.charAt(0)) {
case '>': // >, >=
case '=': // =, =* but not => Oracle/PostgreSQL named parameter syntax
return !token.image.equals("=>");
case '~': // ~, ~*
return true;
case '<': // <, <=, <>, <@, <->, <#>, <=>, <&
return true;
case '*': return token.image.equals("*=");
case '!': return token.image.startsWith("!~") || token.image.startsWith("!=");
case '@': return token.image.equals("@@") || token.image.equals("@>");
case '?': return true; // ?, ?|, ?&
case '-': return true; // -, -#
case '|': return token.image.equals("||");
case '^': return token.image.startsWith("^=");
case '&': return token.image.equals("&&") || token.image.equals("&>");
default: return false;
}
}
protected boolean isParenthesedSelectAhead() {
if (getToken(1).kind != OPENING_BRACKET) {
return false;
}
int nextKind = getToken(2).kind;
return nextKind == K_SELECT
|| nextKind == K_WITH
|| nextKind == K_VALUES
|| nextKind == K_FROM;
}
/**
* Tokens that have dedicated branches in PrimaryExpression AFTER the Function branch.
* If isFunctionAhead() returns true for these, Function() would consume them and fail.
*/
private boolean isNonFunctionKeyword(Token t) {
switch (t.kind) {
case K_CONNECT_BY_ROOT: // CONNECT_BY_ROOT (expr)
case K_PRIOR: // PRIOR expr
case K_STRUCT: // STRUCT(...)
return true;
default:
return false;
}
}
/**
* Scans ahead through a dotted identifier chain and checks if '(' follows.
* Distinguishes function calls like func(), schema.func(), a.b.c.func()
* from column references like col, schema.col, a.b.c.col.
*
* Replaces LOOKAHEAD(16) on Function() with a targeted O(chain-length) check.
*/
protected boolean isFunctionAhead() {
int i = 1;
Token t = getToken(i);
// JDBC escape function: {fn ...} — must check for FN keyword
if (t.image.equals("{")) {
return getToken(2).kind == K_FN;
}
// Optional APPROXIMATE keyword
if (t.kind == K_APPROXIMATE) {
i++;
t = getToken(i);
}
// Exclude tokens that have their own dedicated branches
// after Function() in PrimaryExpression
if (isNonFunctionKeyword(t)) {
return false;
}
// First token must not be a literal, bracket, or EOF
if (t.kind == S_LONG || t.kind == S_DOUBLE || t.kind == S_HEX
|| t.kind == S_CHAR_LITERAL || t.kind == OPENING_BRACKET
|| t.kind == CLOSING_BRACKET || t.kind == EOF) {
return false;
}
i++;
// Walk through dotted name chain
while (true) {
t = getToken(i);
if (t.image.equals(".") || t.image.equals("..")
|| t.image.equals("...") || t.image.equals(":")) {
i++; // skip delimiter
i++; // skip next name part
} else {
break;
}
}
// Must be followed by (
if (getToken(i).kind != OPENING_BRACKET) {
return false;
}
// Exclude Oracle join syntax: column(+)
if (getToken(i + 1).image.equals("+")
&& getToken(i + 2).kind == CLOSING_BRACKET) {
return false;
}
return true;
}
private boolean isKeywordArgumentAhead() {
Token t = getToken(1);
if (t.kind == EOF || t.image.equals(")")) return false;
if (t.image.isEmpty() || !Character.isLetter(t.image.charAt(0))) return false;
// S_QUOTED_IDENTIFIER is not a valid keyword arg name.
// S_IDENTIFIER and DATA_TYPE ARE allowed — after ExpressionList has
// consumed all comma-separated arguments, a remaining identifier or
// type keyword before ')' is a keyword argument name (e.g.
// PREDICTION(expr COST MODEL USING cols),
// XMLTABLE(... COLUMNS "col" VARCHAR2(6) PATH '...')).
if (t.kind == S_QUOTED_IDENTIFIER) return false;
switch (t.kind) {
case S_LONG: case S_DOUBLE: case S_HEX: case S_CHAR_LITERAL:
case K_DISTINCT: case K_ALL: case K_UNIQUE: case K_TABLE:
case K_ORDER: case K_ON: case K_HAVING: case K_IGNORE: case K_RESPECT:
case K_SELECT: case K_FROM: case K_WHERE: case K_GROUP: case K_LIMIT:
case K_UNION: case K_EXCEPT: case K_INTERSECT: case K_MINUS:
case K_JOIN: case K_INNER: case K_LEFT: case K_RIGHT: case K_FULL: case K_CROSS:
case K_INTO: case K_SET: case K_FETCH: case K_OFFSET:
case K_OVER: case K_WITHIN: case K_FILTER: case K_WITH: case K_WITHOUT:
case K_AND: case K_OR: case K_NOT: case K_IN: case K_BETWEEN: case K_LIKE:
case K_IS: case K_EXISTS: case K_AS:
case K_CASE: case K_WHEN: case K_THEN: case K_ELSE: case K_END:
case K_NULL: case K_TRUE: case K_FALSE:
case K_RETURNING:
return false;
}
Token t2 = getToken(2);
if (t2.kind == EOF || t2.image.equals(")")) return false;
return true;
}
/**
* Scans ahead through a dotted identifier chain and checks if '*' follows.
* Identifies table.* patterns for AllTableColumns.
*/
protected boolean isAllTableColumnsAhead() {
int i = 1;
Token t = getToken(i);
// Must start with a name-like token
if (t.kind == S_LONG || t.kind == S_DOUBLE || t.kind == S_HEX
|| t.kind == S_CHAR_LITERAL || t.kind == OPENING_BRACKET
|| t.kind == CLOSING_BRACKET || t.kind == EOF) {
return false;
}
i++;
// Walk through dotted name chain
while (true) {
t = getToken(i);
if (t.image.equals(".") || t.image.equals("..")
|| t.image.equals("...")) {
i++; // skip delimiter
i++; // skip next part (could be "*")
} else {
break;
}
}
// It's AllTableColumns if the chain ended on "*"
// i.e., the last name part we skipped over was "*"
// Back up: the last token consumed was at (i-1)
return getToken(i - 1).image.equals("*");
}
/**
* Follower-based disambiguation for reserved keywords in ambiguous
* positions (implicit alias, clause boundary, after parenthesised
* expression, etc.).
*
* Checks the candidate keyword ({@code getToken(1)}) and its follower
* ({@code getToken(2)}) to decide whether the keyword is being used as
* an identifier or as SQL syntax. Returns {@code true} only for
* keywords that provably don't collide with clause syntax in the
* current follower context.
*/
private boolean isReservedKeywordSafeByFollower() {
Token next2 = getToken(2);
// If followed by . or = the keyword is a name part / property key
if (next2.image != null
&& (next2.image.equals(".") || next2.image.equals("="))) {
return true;
}
int kind = getToken(1).kind;
int nextKind = next2.kind;
switch (kind) {
// Safe as implicit identifiers (no clause collision)
case K_TABLES: case K_OPTIMIZE: case K_PROCEDURE: case K_PUBLIC:
case K_CASEWHEN: case K_IIF:
return true;
// Safe when the follower doesn't form a clause
case K_GROUP: return nextKind != K_BY;
case K_ORDER: return nextKind != K_BY && nextKind != K_SIBLINGS;
case K_CONNECT: return nextKind != K_BY;
case K_START: return nextKind != K_WITH;
case K_LEFT: return nextKind != K_JOIN && nextKind != K_OUTER
&& nextKind != K_SEMI;
case K_RIGHT: return nextKind != K_JOIN && nextKind != K_OUTER
&& nextKind != K_SEMI;
case K_ALL: return nextKind != K_JOIN;
case K_ANY: return nextKind != OPENING_BRACKET;
case K_SOME: return nextKind != OPENING_BRACKET;
case K_IN: return nextKind != OPENING_BRACKET;
case K_IF: return nextKind != OPENING_BRACKET;
case K_GROUPING: return nextKind != OPENING_BRACKET;
case K_DEFAULT: return nextKind != K_VALUES;
case K_CREATE: return nextKind != K_TABLE && nextKind != K_VIEW
&& nextKind != K_INDEX;
case K_INTERVAL: return nextKind != S_LONG && nextKind != S_DOUBLE
&& nextKind != S_CHAR_LITERAL;
case K_TOP: return nextKind != S_LONG && nextKind != S_DOUBLE
&& nextKind != OPENING_BRACKET;
case K_NEXTVAL: return nextKind != K_VALUE;
// IGNORE: blocks NULLS (IGNORE NULLS), FROM (DELETE IGNORE FROM),
// INDEX (IGNORE INDEX hint)
case K_IGNORE: return nextKind != K_NULLS && nextKind != K_FROM
&& nextKind != K_INDEX;
// GLOBAL: blocks IN (GLOBAL IN), TEMPORARY, JOIN (GLOBAL JOIN)
case K_GLOBAL: return nextKind != K_IN && nextKind != K_TEMPORARY
&& nextKind != K_JOIN;
// Structural keywords — never safe as implicit identifiers
case K_SET: case K_ON: case K_QUALIFY:
case K_LIMIT: case K_OFFSET:
return false;
// VALUE/VALUES: safe as alias when not starting VALUES(...)
case K_VALUE: case K_VALUES:
return nextKind != OPENING_BRACKET && nextKind != S_IDENTIFIER
&& nextKind != S_QUOTED_IDENTIFIER && nextKind != S_CHAR_LITERAL;
default:
return false;
}
}
/**
* Determines whether a reserved keyword token can be treated as an unquoted
* identifier in the current parser position.
*
* Called from the semantic LOOKAHEAD inside {@code RelObjectName()}.
* Uses the previous token to detect name positions (after structural
* keywords, delimiters, AS), the follower token (after . or =), and
* falls back to conservative follower-based disambiguation.
*/
private boolean isReservedKeywordAsIdentifier() {
Token prev = getToken(0);
// Guard: at the very start of parsing (e.g. parseExpression()),
// prev may be null or have null image. This is always a name /
// expression position, so accept any keyword.
if (prev == null || prev.image == null) {
return true;
}
// ── 1. After AS: explicit alias — accept any keyword ──────────
if (prev.kind == K_AS) {
return true;
}
// ── 2. After delimiters and operators: expression position ─────
// With K_FROM/K_SELECT/K_CURRENT removed from RelObjectName's
// token list, accepting all remaining keywords after these
// delimiters and operators is safe.
if (!prev.image.isEmpty()) {
switch (prev.image.charAt(0)) {
// Structural delimiters
case '.': case ',': case ':': case '(': case '=':
// Comparison and arithmetic operators
case '>': case '<': case '!': case '^':
case '+': case '-': case '*': case '/': case '%':
case '~': case '|': case '&': case '?':
return true;
}
}
// ── 3. If followed by . or = the keyword is a name/property key ──
Token next2 = getToken(2);
if (next2.image != null
&& (next2.image.equals(".") || next2.image.equals("="))) {
return true;
}
// ── 4. After TRULY STRUCTURAL keywords that can NEVER be ──────
// consumed as identifiers (i.e. they are never in our own
// keyword-as-identifier set). After these, any keyword is
// safe as an identifier.
//
// Keywords that CAN be identifiers (LEFT, LIMIT, IGNORE,
// etc.) are NOT listed here because they may appear as
// getToken(0) after being consumed as identifiers or
// modifiers, which is NOT a name position.
switch (prev.kind) {
// Boolean / conditional operators
case K_AND: case K_OR: case K_NOT: case K_XOR:
// Clause keywords
case K_SELECT: case K_FROM: case K_WHERE: case K_HAVING:
case K_INTO: case K_USING: case K_SET: case K_ON:
case K_FETCH: case K_FOR: case K_WITH:
// Comparison / expression operators
case K_BETWEEN: case K_LIKE: case K_ILIKE: case K_IS:
// Join keywords
case K_JOIN: case K_INNER: case K_OUTER: case K_FULL:
case K_CROSS: case K_NATURAL: case K_STRAIGHT: case K_SEMI:
case K_LATERAL:
// CASE/WHEN expression structure
case K_WHEN: case K_ELSE:
// Non-reserved keywords that structurally introduce expression
// positions (GROUP BY expr, ORDER BY expr, CASE WHEN x THEN expr)
case K_BY: case K_THEN:
// Modifiers
case K_DISTINCT: case K_DISTINCTROW:
// Set operators
case K_UNION: case K_EXCEPT: case K_INTERSECT: case K_MINUS:
// DDL / utility keywords (never identifiers)
case K_FOREIGN: case K_CONSTRAINT: case K_UNIQUE: case K_CHECK:
case K_FORCE:
case K_RETURNING: case K_OUTPUT: case K_IMPORT:
case K_PIVOT: case K_UNPIVOT:
case K_PRIOR: case K_WINDOW: case K_ONLY:
case K_PREFERRING: case K_PREWHERE:
case K_RETURNS: case K_EXISTS:
case K_QUALIFY: case K_CURRENT:
return true;
}
// ── 5. Conservative default: fall back to follower check ──────
return isReservedKeywordSafeByFollower();
}
/**
* Checks whether the next token(s) can plausibly start an {@code Alias}.
*
* Used as a semantic LOOKAHEAD guard at alias call-sites. Unlike
* {@link #isReservedKeywordAsIdentifier()}, this method does NOT use
* the structural-keyword whitelist (step 4), because an alias always
* follows an expression — never a structural keyword in isolation.
* Instead it goes directly to follower-based disambiguation for
* reserved keywords.
*/
private boolean isAliasAhead() {
Token t = getToken(1);
int kind = t.kind;
// AS always starts an alias
if (kind == K_AS) return true;
// String-literal alias: SELECT col 'myAlias'
if (kind == S_CHAR_LITERAL) return true;
// Base identifier tokens
if (kind == S_IDENTIFIER || kind == S_QUOTED_IDENTIFIER
|| kind == DATA_TYPE || kind == K_DATETIMELITERAL
|| kind == K_DATE_LITERAL) {
return true;
}
// Non-reserved keywords
if (kind >= MIN_NON_RESERVED_WORD && kind <= MAX_NON_RESERVED_WORD) {
return true;
}
// For reserved keywords in alias position, skip the structural-
// keyword whitelist and go directly to follower disambiguation.
// Only check keywords that are actually in RelObjectName's token
// alternatives — don't fire for brackets, operators, literals, etc.
switch (kind) {
case K_ALL: case K_ANY: case K_CASEWHEN: case K_CONNECT:
case K_CREATE: case K_DEFAULT:
case K_GLOBAL: case K_GROUP: case K_GROUPING: case K_IF:
case K_IIF: case K_IGNORE: case K_IN: case K_INTERVAL:
case K_LEFT: case K_LIMIT: case K_NEXTVAL: case K_OFFSET:
case K_ON: case K_OPTIMIZE: case K_ORDER: case K_PROCEDURE:
case K_PUBLIC: case K_QUALIFY: case K_RIGHT:
case K_SET: case K_SOME: case K_START: case K_TABLES:
case K_TOP: case K_VALUE: case K_VALUES:
return isReservedKeywordSafeByFollower();
default:
return false;
}
}
/**
* Checks if the next token can start a condition suffix
* (comparison, IN, BETWEEN, LIKE, IS NULL, etc.)
*
* Used as the entry guard for the entire optional condition-suffix block
* in Condition(), eliminating choice conflicts.
*/
protected boolean isConditionSuffixAhead() {
if (isComparisonOperatorAhead()) {
return true;
}
Token t = getToken(1);
switch (t.kind) {
// Each suffix's start token:
case K_OVERLAPS: // OVERLAPS
case K_IN: // IN
case K_GLOBAL: // GLOBAL ... IN
case K_EXCLUDES: // EXCLUDES (...)
case K_INCLUDES: // INCLUDES (...)
case K_BETWEEN: // BETWEEN
case K_MEMBER: // MEMBER OF
case K_IS: // IS [NOT] NULL / TRUE / FALSE / UNKNOWN / DISTINCT
case K_ISNULL: // ISNULL
case K_NOTNULL: // NOTNULL
case K_LIKE: // LIKE
case K_ILIKE: // ILIKE
case K_RLIKE: // RLIKE
case K_REGEXP_LIKE: // REGEXP_LIKE
case K_REGEXP: // REGEXP
case K_SIMILAR_TO: // SIMILAR TO (in LikeExpression)
case K_SIMILAR: // SIMILAR TO (in SimilarToExpression)
case K_MATCH_ANY: // MATCH_ANY
case K_MATCH_ALL: // MATCH_ALL
case K_MATCH_PHRASE: // MATCH_PHRASE
case K_MATCH_PHRASE_PREFIX: // MATCH_PHRASE_PREFIX
case K_MATCH_REGEXP: // MATCH_REGEXP
case K_NOT: // NOT IN / NOT BETWEEN / NOT LIKE / NOT ISNULL / NOT SIMILAR
return true;
// Oracle (+) before IN: col(+) IN (...)
case OPENING_BRACKET:
return getToken(2).image.equals("+");
default:
return false;
}
}
}
PARSER_END(CCJSqlParser)
TOKEN_MGR_DECLS : {
public FeatureConfiguration configuration = new FeatureConfiguration();
// Nesting depth for block comments: /* /* ... */ */
int commentNesting = 0;
// Stores the comment image up to and including the outermost */
String storedCommentImage = null;
// Identify the index of the quoting/escaping tokens
public int charLiteralIndex = -1;
public int squaredBracketOpenIndex = -1;
{
for (int i=0;i<CCJSqlParserConstants.tokenImage.length;i++) {
if ( CCJSqlParserConstants.tokenImage[i].equals("<S_CHAR_LITERAL>") ) {
charLiteralIndex = i;
break;
}
}
for (int i=0;i<CCJSqlParserConstants.tokenImage.length;i++) {
if (CCJSqlParserConstants.tokenImage[i].equals("\"[\"")) {
squaredBracketOpenIndex = i;
break;
}
}
}
// Finds first occurrence of "\\'"
public static int indexOfSequence(String s, String target) {
int len = s.length();
for (int i = 0; i < len - 1; i++) {
if (s.charAt(i) == '\\' && s.charAt(i + 1) == '\'') {
return i;
}
}
return -1;
}
// Finds last occurrence of "\\''"
public static int lastIndexOfSequence(String s, String target) {
int len = s.length();
for (int i = len - 3; i >= 0; i--) {
if (s.charAt(i) == '\\' && s.charAt(i + 1) == '\'' && s.charAt(i + 2) == '\'') {
return i;
}
}
return -1;
}
public void CommonTokenAction(Token t)
{
t.absoluteBegin = getCurrentTokenAbsolutePosition();
t.absoluteEnd = t.absoluteBegin + t.image.length();
}
public int getCurrentTokenAbsolutePosition()
{
if (input_stream instanceof SimpleCharStream)
return ((SimpleCharStream)input_stream).getAbsoluteTokenBegin();
return -1;
}
private static boolean endsWithDelimiter(Deque<Character> windowQueue, String delimiter) {
if (windowQueue.size() != delimiter.length()) {
return false;
}
int i = 0;
for (char ch : windowQueue) {
if (ch != delimiter.charAt(i++)) {
return false;
}
}
return true;
}
public void consumeDollarQuotedString(String closingQuote) {
Deque<Character> windowQueue = new ArrayDeque<Character>();
int delimiterLength = closingQuote.length();
try {
while (true) {
char ch = input_stream.readChar();
windowQueue.addLast(ch);
if (windowQueue.size() > delimiterLength) {
windowQueue.removeFirst();
}
if (endsWithDelimiter(windowQueue, closingQuote)) {
return;
}
}
} catch (java.io.IOException e) {
reportError(Math.max(closingQuote.length(), input_stream.GetImage().length()));
}
}
}
SKIP:
{
<WHITESPACE: " " | "\t" | "\r" | "\n">
}
// Sentinel: start of non-reserved keyword range (for O(1) identifier checks)
<UNREACHABLE>SKIP:
{
<MIN_NON_RESERVED_WORD: "MIN NON RESERVED WORD">
}
/**
* Non-reserved SQL keywords usable as unquoted identifiers.
* Tokens are declared inline to get consecutive kind values between
* MIN_NON_RESERVED_WORD and MAX_NON_RESERVED_WORD sentinels.
*/
String NonReservedWord() :
{ Token tk = null; }
{
(
tk=<K_ACTION: "ACTION">
| tk=<K_ACTIVE: "ACTIVE">
| tk=<K_ADD:"ADD">
| tk=<K_ADVANCE:"ADVANCE">
| tk=<K_ADVISE:"ADVISE">
| tk=<K_AGAINST:"AGAINST">
| tk=<K_AGGREGATE: "AGGREGATE">
| tk=<K_ALGORITHM: "ALGORITHM">
| tk=<K_ALIGN:"ALIGN">
| tk=<K_ALTER:"ALTER">
| tk=<K_ALWAYS:"ALWAYS">
| tk=<K_ANALYZE:"ANALYZE">
| tk=<K_APPEND_ONLY:"APPEND_ONLY">
| tk=<K_APPLY:"APPLY">
| tk=<K_APPROXIMATE:"APPROXIMATE">
| tk=<K_ARCHIVE: "ARCHIVE">
| tk=<K_ARRAY_LITERAL: "ARRAY" >
| tk=<K_ASYMMETRIC: "ASYMMETRIC">
| tk=<K_AT: "AT">
| tk=<K_ASC:"ASC">
| tk=<K_AUTHORIZATION:"AUTHORIZATION">
| tk=<K_AUTO:"AUTO">
| tk=<K_AUTO_INCREMENT:"AUTO_INCREMENT">
| tk=<K_AZURE:"AZURE">
| tk=<K_BASE64:"BASE64">
| tk=<K_BEFORE: "BEFORE">
| tk=<K_BEGIN:"BEGIN">
| tk=<K_BERNOULLI: "BERNOULLI">
| tk=<K_BINARY: "BINARY">
| tk=<K_BIT:"BIT">
| tk=<K_BLOBSTORAGE:"BLOBSTORAGE">
| tk=<K_BLOCK: "BLOCK">
| tk=<K_BOOLEAN:"BOOLEAN">
| tk=<K_BREADTH:"BREADTH">
| tk=<K_BRANCH:"BRANCH">
| tk=<K_BROWSE:"BROWSE">
| tk=<K_BY:"BY">
| tk=<K_BYTES: "BYTES">
| tk=<K_CACHE: "CACHE">
| tk=<K_BUFFERS: "BUFFERS">
| tk=<K_BYTE: "BYTE">
| tk=<K_CALL : "CALL">
| tk=<K_CASCADE: "CASCADE">
| tk=<K_CASE:"CASE">
| tk=<K_CAST: "CAST">
| tk=<K_CERTIFICATE: "CERTIFICATE">
| tk=<K_CHARACTER:"CHARACTER">
| tk=<K_CHANGE:"CHANGE">
| tk=<K_CHANGES:"CHANGES">
| tk=<K_CHECKPOINT:"CHECKPOINT">
| tk=<K_CHAR:"CHAR">
| tk=<K_CLOSE:"CLOSE">
| tk=<K_CLOUD:"CLOUD">
| tk=<K_COALESCE:"COALESCE">
| tk=<K_COLLATE:"COLLATE">
| tk=<K_COLUMN:"COLUMN">
| tk=<K_COLUMNS:"COLUMNS">
| tk=<K_COMMIT:"COMMIT">
| tk=<K_COMMENT:"COMMENT">
| tk=<K_COMMENTS:"COMMENTS">
| tk=<K_CONFLICT:"CONFLICT">
| tk=<K_CONSTRAINTS:"CONSTRAINTS">
| tk=<K_CONVERT:"CONVERT">
| tk=<K_CORRESPONDING:"CORRESPONDING">
| tk=<K_COSTS: "COSTS">
| tk=<K_COUNT: "COUNT">
| tk=<K_CREATED:"CREATED">
| tk=<K_CYCLE:"CYCLE">
| tk=<K_DATABASE:"DATABASE">
| tk=<K_DATA:"DATA">
| tk=<K_DECLARE: "DECLARE">
| tk=<K_DBA_RECYCLEBIN: "DBA_RECYCLEBIN">
| tk=<K_DEFAULTS: "DEFAULTS">
| tk=<K_DEPTH: "DEPTH">
| tk=<K_DEFERRABLE : "DEFERRABLE">
| tk=<K_DELAYED : "DELAYED">
| tk=<K_DELETE:"DELETE">
| tk=<K_DELIMIT : "DELIMIT">
| tk=<K_DELIMITER : "DELIMITER">
| tk=<K_DESC:"DESC">
| tk=<K_DESCRIBE:"DESCRIBE">
| tk=<K_DISABLE : "DISABLE">
| tk=<K_DISCARD : "DISCARD">
| tk=<K_DISCONNECT:"DISCONNECT">
| tk=<K_DIV:"DIV">
| tk=<K_DDL:"DDL">
| tk=<K_DML:"DML">
| tk=<K_DO:"DO">
| tk=<K_DOMAIN:"DOMAIN">
| tk=<K_DRIVER:"DRIVER">
| tk=<K_DROP:"DROP">
| tk=<K_DUMP:"DUMP">
| tk=<K_DUPLICATE: "DUPLICATE">
| tk=<K_ELEMENTS: "ELEMENTS">
| tk=<K_EMIT: "EMIT">
| tk=<K_ENABLE: "ENABLE">
| tk=<K_ENCODING: "ENCODING">
| tk=<K_ENCRYPTION: "ENCRYPTION">
| tk=<K_END: "END">
| tk=<K_ENFORCED: "ENFORCED">
| tk=<K_ENGINE: "ENGINE">
| tk=<K_ERROR: "ERROR">
| tk=<K_ESCAPE: "ESCAPE">
| tk=<K_EXA: "EXA">
| tk=<K_EXCHANGE: "EXCHANGE">
| tk=<K_EXCLUDE: "EXCLUDE">
| tk=<K_EXCLUDING: "EXCLUDING">
| tk=<K_EXCLUSIVE: "EXCLUSIVE">
| tk=<K_EXEC: "EXEC">
| tk=<K_EXECUTE: "EXECUTE">
| tk=<K_EXPLAIN:"EXPLAIN">
| tk=<K_EXPLICIT:"EXPLICIT">
| tk=<K_EXTENDED:"EXTENDED">
| tk=<K_EXTRACT:"EXTRACT">
| tk=<K_EXPORT:"EXPORT">
| tk=<K_ISOLATION:("UR" | "RS" | "RR" | "CS")>
| tk=<K_FILTER: "FILTER">
| tk=<K_FIRST: "FIRST">
| tk=<K_FLUSH: "FLUSH">
| tk=<K_FOLLOWING: "FOLLOWING">
| tk=<K_FORMAT:"FORMAT">
| tk=<K_FULLTEXT:"FULLTEXT">
| tk=<K_FUNCTION:"FUNCTION">
| tk=<K_GRANT:"GRANT">
| tk=<K_GROUP_CONCAT:"GROUP_CONCAT">
| tk=<K_GUARD:"GUARD">
| tk=<K_HASH:"HASH">
| tk=<K_HIGH : "HIGH">
| tk=<K_HIGH_PRIORITY : "HIGH_PRIORITY">
| tk=<K_HISTORY : "HISTORY">
| tk=<K_HOPPING:"HOPPING">
| tk=<K_IDENTIFIED:"IDENTIFIED">
| tk=<K_IDENTITY:"IDENTITY">
| tk=<K_INCLUDE:"INCLUDE">
| tk=<K_INCLUDE_NULL_VALUES:"INCLUDE_NULL_VALUES">
| tk=<K_INCLUDING:"INCLUDING">
| tk=<K_INCREMENT:"INCREMENT">
| tk=<K_INDEX: "INDEX">
| tk=<K_INFORMATION: "INFORMATION">
| tk=<K_INSERT:"INSERT">
| tk=<K_INTERLEAVE: "INTERLEAVE">
| tk=<K_INTERPRET: "INTERPRET">
| tk=<K_INVALIDATE:"INVALIDATE">
| tk=<K_INVERSE:"INVERSE">
| tk=<K_INVISIBLE:"INVISIBLE">
| tk=<K_ISNULL:"ISNULL">
| tk=<K_JDBC:"JDBC">
| tk=<K_JSON:"JSON">
| tk=<K_JSON_OBJECT: "JSON_OBJECT">
| tk=<K_JSON_OBJECTAGG: "JSON_OBJECTAGG">
| tk=<K_JSON_ARRAY: "JSON_ARRAY">
| tk=<K_JSON_ARRAYAGG: "JSON_ARRAYAGG">
| tk=<K_KEEP:"KEEP">
| tk=<K_KEY_BLOCK_SIZE: "KEY_BLOCK_SIZE">
| tk=<K_KEY:"KEY">
| tk=<K_KEYS:"KEYS">
| tk=<K_KILL:"KILL">
| tk=<K_FN:"FN">
| tk=<K_LAST: "LAST">
| tk=<K_LEADING:"LEADING">
| tk=<K_LESS:"LESS">
| tk=<K_LEVEL:"LEVEL">
| tk=<K_LOCAL:"LOCAL">
| tk=<K_LOCK:"LOCK">
| tk=<K_LOCKED:"LOCKED">
| tk=<K_LINK:"LINK">
| tk=<K_LOG:"LOG">
| tk=<K_LOOP:"LOOP">
| tk=<K_LOW : "LOW">
| tk=<K_LOW_PRIORITY : "LOW_PRIORITY">
| tk=<K_LTRIM : "LTRIM">
| tk=<K_MATCH: "MATCH">
| tk=<K_MATCH_ANY: "MATCH_ANY">
| tk=<K_MATCH_ALL: "MATCH_ALL">
| tk=<K_MATCH_PHRASE: "MATCH_PHRASE">
| tk=<K_MATCH_PHRASE_PREFIX: "MATCH_PHRASE_PREFIX">
| tk=<K_MATCH_REGEXP: "MATCH_REGEXP">
| tk=<K_MATCHED: "MATCHED">
| tk=<K_MATERIALIZED:"MATERIALIZED">
| tk=<K_MAX: "MAX">
| tk=<K_MAXVALUE: "MAXVALUE">
| tk=<K_MEMBER: "MEMBER">
| tk=<K_MERGE: "MERGE">
| tk=<K_MIN:"MIN">
| tk=<K_MINVALUE:"MINVALUE">
| tk=<K_MODE: "MODE">
| tk=<K_MODIFY: "MODIFY">
| tk=<K_MOVEMENT: "MOVEMENT">
| tk=<K_NAMES:"NAMES">
| tk=<K_NAME:"NAME">
| tk=<K_NEVER:"NEVER">
| tk=<K_NEXT:"NEXT">
| tk=<K_NEXTVAL: ( (("NEXTVAL")((" ")+("FOR"))?) | ( ("NEXT")(" ")+("VALUE") (" ")+("FOR") ) )>
| tk=<K_NO:"NO">
| tk=<K_NOCACHE:"NOCACHE">
| tk=<K_NOKEEP:"NOKEEP">
| tk=<K_NOLOCK:"NOLOCK">
| tk=<K_NOMAXVALUE:"NOMAXVALUE">
| tk=<K_NOMINVALUE:"NOMINVALUE">
| tk=<K_NONE:"NONE">
| tk=<K_NOORDER:"NOORDER">
| tk=<K_NOTHING:"NOTHING">
| tk=<K_NOTNULL:"NOTNULL">
| tk=<K_NOVALIDATE : "NOVALIDATE">
| tk=<K_NULLS: "NULLS">
| tk=<K_NOWAIT: "NOWAIT">
| tk=<K_OF:"OF">
| tk=<K_OFF:"OFF">
| tk=<K_OPEN:"OPEN">
| tk=<K_ORA: "ORA">
| tk=<K_ORDINALITY:"ORDINALITY">
| tk=<K_OVER:"OVER">
| tk=<K_OVERFLOW:"OVERFLOW">
| tk=<K_OVERLAPS:"OVERLAPS">
| tk=<K_OVERRIDING:"OVERRIDING">
| tk=<K_OVERWRITE:"OVERWRITE">
| tk=<K_PADDING:"PADDING">
| tk=<K_PARALLEL:"PARALLEL">
| tk=<K_PARENT:"PARENT">
| tk=<K_PARSER: "PARSER">
| tk=<K_PARTITION:"PARTITION">
| tk=<K_PARTITIONING:"PARTITIONING">
| tk=<K_PATH:"PATH">
| tk=<K_PERCENT:"PERCENT">
| tk=<K_PLACING:"PLACING">
| tk=<K_PLAN:"PLAN">
| tk=<K_PLUS:"PLUS">
| tk=<K_PRECEDING: "PRECEDING">
| tk=<K_PRIMARY:"PRIMARY">
| tk=<K_POLICY:"POLICY">
| tk=<K_PURGE:"PURGE">
| tk=<K_QUERY:"QUERY">
| tk=<K_QUICK : "QUICK">
| tk=<K_QUIESCE: "QUIESCE">
| tk=<K_RANGE: "RANGE">
| tk=<K_RAW: "RAW">