Repository navigation
Expand file tree
/
Copy pathSqlTableReference.java
More file actions
1224 lines (1141 loc) · 44.3 KB
/
Copy pathSqlTableReference.java
File metadata and controls
1224 lines (1141 loc) · 44.3 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
package com.github.magnusp.libsql.jdbc;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/**
* Resolves the origin table of each result column in a SQLite statement.
*
* <p>Resolved shapes:
*
* <ul>
* <li>simple queries, including {@code SELECT *} and schema-qualified names
* <li>column aliases, including aliases over joined, subquery, and view columns
* <li>joins, including comma joins and explicit {@code JOIN} clauses
* <li>subqueries in the FROM clause, scalar subqueries, and common table expressions
* <li>the leftmost branch of a compound SELECT
* <li>{@code INSERT}, {@code UPDATE}, and {@code DELETE} with {@code RETURNING}
* <li>views, which resolve to the base table that supplies each column
* </ul>
*
* <p>Expressions, literals, and other shapes whose origin SQLite does not expose as a direct
* column reference do not resolve. Callers report the JDBC empty table name and unknown
* nullability for those columns.
*/
final class SqlTableReference {
record TableRef(String schema, String table) {}
interface Schema {
TableDefinition definition(TableRef table) throws SQLException;
}
record TableDefinition(String sql, List<String> columns) {}
record Resolution(List<String> labels, List<TableRef> tables) {
static final Resolution EMPTY = new Resolution(List.of(), List.of());
TableRef table(int index) {
return index >= 0 && index < tables.size() ? tables.get(index) : null;
}
}
private enum Type {
WORD,
IDENT,
SYMBOL
}
private record Token(Type type, String text, int depth) {}
private record ColumnRef(List<String> parts) {
String column() {
return parts.get(parts.size() - 1);
}
String qualifier() {
return parts.size() >= 2 ? parts.get(parts.size() - 2) : null;
}
}
private record Source(
String qualifier,
List<String> columns,
List<TableRef> tables,
boolean knownColumns,
TableRef baseTable) {
TableRef origin(String column) {
for (int i = 0; i < columns.size(); i++) {
if (columns.get(i).equalsIgnoreCase(column)) {
return tables.get(i);
}
}
return null;
}
boolean hasColumn(String column) {
for (String candidate : columns) {
if (candidate.equalsIgnoreCase(column)) {
return true;
}
}
return false;
}
boolean matchesQualifier(String qualifier) {
return this.qualifier != null && this.qualifier.equalsIgnoreCase(qualifier);
}
}
private record SourceList(List<Source> sources, int next) {}
/**
* The sources of a FROM clause together with the column list {@code *} expands to. The star
* list drops the right-side duplicate of a USING or NATURAL join column, as SQLite does.
*/
private record FromClause(List<Source> sources, List<String> starLabels, List<TableRef> starTables) {
static FromClause of(List<Source> sources) {
List<String> labels = new ArrayList<>();
List<TableRef> tables = new ArrayList<>();
for (Source source : sources) {
appendStarColumns(source, false, labels, tables);
}
return new FromClause(sources, labels, tables);
}
}
private static final Pattern UNQUOTED_IDENTIFIER = Pattern.compile("[A-Za-z_][A-Za-z0-9_$]*");
private static final Set<String> FROM_END = Set.of(
"WHERE", "GROUP", "HAVING", "ORDER", "LIMIT", "OFFSET", "WINDOW", "RETURNING",
"UNION", "INTERSECT", "EXCEPT");
private static final Set<String> JOIN_START =
Set.of("JOIN", "INNER", "LEFT", "RIGHT", "FULL", "CROSS", "NATURAL", "OUTER");
private static final Set<String> SET_OPERATORS = Set.of("UNION", "INTERSECT", "EXCEPT");
private static final Set<String> NOT_AN_ALIAS = Set.of(
"AS", "ON", "USING", "INDEXED", "NOT", "COLLATE", "IS", "LIKE", "GLOB", "REGEXP",
"MATCH", "ESCAPE", "BETWEEN", "IN", "CASE", "WHEN", "THEN", "ELSE", "END", "CAST",
"EXISTS", "AND", "OR", "NULL");
private SqlTableReference() {}
static Resolution resolve(String sql, Schema schema) throws SQLException {
if (sql == null || sql.isBlank()) {
return null;
}
List<Token> tokens = tokenize(sql);
if (tokens == null) {
return null;
}
return new Parser(tokens, schema, new HashSet<>())
.parseStatement(0, tokens.size(), 0, new HashMap<>());
}
/**
* Resolves column origins and discards the resolution when the parser expansion does not match
* the result width. The protocol column list is authoritative for width, and a shifted
* expansion would attribute every later column to the wrong table.
*/
static Resolution resolve(String sql, Schema schema, int columnCount) throws SQLException {
Resolution resolution = resolve(sql, schema);
if (resolution == null || resolution.labels().size() != columnCount) {
return null;
}
return resolution;
}
private static final class Parser {
private final List<Token> tokens;
private final Schema schema;
private final Set<String> resolvingViews;
private Parser(List<Token> tokens, Schema schema, Set<String> resolvingViews) {
this.tokens = tokens;
this.schema = schema;
this.resolvingViews = resolvingViews;
}
private Resolution parseStatement(int start, int end, int depth, Map<String, Source> scope)
throws SQLException {
int index = skipSymbols(start, end, depth, ";");
while (end > index && isSymbolAt(end - 1, ";", depth)) {
end--;
}
if (index >= end) {
return null;
}
String keyword = wordAt(index, depth);
if (keyword == null) {
return null;
}
return switch (keyword) {
case "WITH" -> parseWith(index, end, depth, scope);
case "SELECT" -> parseSelect(index, end, depth, scope);
case "INSERT", "REPLACE", "UPDATE", "DELETE" -> parseReturning(index, end, depth, scope);
default -> null;
};
}
private Resolution parseWith(int start, int end, int depth, Map<String, Source> scope)
throws SQLException {
Map<String, Source> ctes = new HashMap<>(scope);
int index = start + 1;
if (isWordAt(index, depth, "RECURSIVE")) {
index++;
}
while (index < end) {
String name = identifier(index);
if (name == null) {
return null;
}
index++;
List<String> columns = null;
if (isSymbolAt(index, "(", depth)) {
int close = matchingParen(index);
if (close < 0 || close >= end) {
return null;
}
columns = identifiers(index + 1, close, depth + 1);
index = close + 1;
}
if (!isWordAt(index, depth, "AS")) {
return null;
}
index++;
if (isWordAt(index, depth, "NOT")) {
index += 2;
} else if (isWordAt(index, depth, "MATERIALIZED")) {
index++;
}
if (!isSymbolAt(index, "(", depth)) {
return null;
}
int close = matchingParen(index);
if (close < 0 || close >= end) {
return null;
}
Resolution resolution = parseStatement(index + 1, close, depth + 1, ctes);
if (resolution != null) {
ctes.put(
name.toLowerCase(Locale.ROOT),
new Source(
name,
columns != null && columns.size() == resolution.labels().size()
? columns
: resolution.labels(),
resolution.tables(),
true,
null));
}
index = close + 1;
if (isSymbolAt(index, ",", depth)) {
index++;
continue;
}
break;
}
if (index >= end) {
return null;
}
return parseStatement(index, end, depth, ctes);
}
private Resolution parseSelect(int start, int end, int depth, Map<String, Source> scope)
throws SQLException {
int index = start + 1;
while (isWordAt(index, depth, "ALL") || isWordAt(index, depth, "DISTINCT")) {
index++;
}
int setOperator = indexOfAnyWord(index, end, depth, SET_OPERATORS);
int selectEnd = setOperator >= 0 ? setOperator : end;
int fromIndex = indexOfWord(index, selectEnd, depth, "FROM");
int listEnd = fromIndex >= 0 ? fromIndex : selectEnd;
FromClause from = FromClause.of(List.of());
if (fromIndex >= 0) {
int fromEnd = indexOfAnyWord(fromIndex + 1, selectEnd, depth, FROM_END);
if (fromEnd < 0) {
fromEnd = selectEnd;
}
FromClause parsed = parseSources(fromIndex + 1, fromEnd, depth, scope);
if (parsed == null || parsed.sources().isEmpty()) {
return null;
}
from = parsed;
}
return parseSelectItems(index, listEnd, depth, from, scope);
}
private FromClause parseSources(int start, int end, int depth, Map<String, Source> scope)
throws SQLException {
List<Source> sources = new ArrayList<>();
List<String> starLabels = new ArrayList<>();
List<TableRef> starTables = new ArrayList<>();
boolean natural = false;
int index = start;
while (index < end) {
SourceList parsed = parseSource(index, end, depth, scope);
if (parsed == null) {
return null;
}
int starStart = starLabels.size();
for (Source source : parsed.sources()) {
sources.add(source);
appendStarColumns(source, natural, starLabels, starTables);
}
index = parsed.next();
index = skipIndexModifiers(index, end, depth);
if (isWordAt(index, depth, "USING")) {
dropStarColumns(usingColumns(index, end, depth), starStart, starLabels, starTables);
}
index = skipJoinCondition(index, end, depth);
if (isSymbolAt(index, ",", depth)) {
natural = false;
index++;
continue;
}
if (index < end && isJoinStart(index, end, depth)) {
natural = isWordAt(index, depth, "NATURAL");
index = skipToJoin(index, end, depth);
if (index < 0) {
break;
}
index++;
continue;
}
break;
}
return new FromClause(sources, starLabels, starTables);
}
private SourceList parseSource(int start, int end, int depth, Map<String, Source> scope)
throws SQLException {
int index = start;
if (isSymbolAt(index, "(", depth)) {
int close = matchingParen(index);
if (close < 0 || close >= end) {
return null;
}
int innerDepth = depth + 1;
String innerKeyword = wordAt(index + 1, innerDepth);
if ("SELECT".equals(innerKeyword) || "WITH".equals(innerKeyword)) {
Resolution inner = parseStatement(index + 1, close, innerDepth, scope);
index = close + 1;
String alias = null;
if (isWordAt(index, depth, "AS")) {
index++;
alias = identifier(index);
if (alias == null) {
return null;
}
index++;
} else if (isAlias(index, depth)) {
alias = identifier(index);
index++;
}
List<String> aliasColumns = null;
if (isSymbolAt(index, "(", depth)) {
int columnsEnd = matchingParen(index);
if (columnsEnd < 0 || columnsEnd >= end) {
return null;
}
aliasColumns = identifiers(index + 1, columnsEnd, depth + 1);
index = columnsEnd + 1;
}
if (inner == null) {
inner = Resolution.EMPTY;
}
List<String> labels = aliasColumns != null && aliasColumns.size() == inner.labels().size()
? aliasColumns
: inner.labels();
return new SourceList(
List.of(new Source(alias, labels, inner.tables(), true, null)), index);
}
FromClause grouped = parseSources(index + 1, close, innerDepth, scope);
if (grouped == null) {
return null;
}
index = close + 1;
String alias = null;
if (isWordAt(index, depth, "AS")) {
index++;
alias = identifier(index);
if (alias == null) {
return null;
}
index++;
} else if (isAlias(index, depth)) {
alias = identifier(index);
index++;
}
if (alias == null) {
return new SourceList(grouped.sources(), index);
}
return new SourceList(
List.of(new Source(alias, grouped.starLabels(), grouped.starTables(), true, null)),
index);
}
String first = identifier(index);
if (first == null) {
return null;
}
index++;
String schemaName = null;
if (isSymbolAt(index, ".", depth)) {
index++;
String second = identifier(index);
if (second == null) {
return null;
}
index++;
if (isSymbolAt(index, ".", depth)) {
return null;
}
schemaName = first;
first = second;
}
String alias = null;
if (isWordAt(index, depth, "AS")) {
index++;
alias = identifier(index);
if (alias == null) {
return null;
}
index++;
} else if (isAlias(index, depth)) {
alias = identifier(index);
index++;
}
TableRef reference = new TableRef(schemaName, first);
String qualifier = alias != null ? alias : first;
if (schemaName == null) {
Source cte = scope.get(first.toLowerCase(Locale.ROOT));
if (cte != null) {
return new SourceList(
List.of(new Source(
qualifier,
cte.columns(),
cte.tables(),
cte.knownColumns(),
cte.baseTable())),
index);
}
}
TableDefinition definition = schema.definition(reference);
if (definition == null) {
return new SourceList(
List.of(new Source(qualifier, List.of(), List.of(), false, reference)), index);
}
if (isViewDefinition(definition.sql())) {
Resolution view = resolveView(reference, definition, depth, scope);
if (view == null) {
return new SourceList(
List.of(new Source(
qualifier,
definition.columns(),
Collections.nCopies(definition.columns().size(), null),
true,
null)),
index);
}
return new SourceList(
List.of(new Source(qualifier, view.labels(), view.tables(), true, null)), index);
}
List<String> columns = definition.columns() != null ? definition.columns() : List.of();
return new SourceList(
List.of(new Source(
qualifier,
columns,
Collections.nCopies(columns.size(), reference),
true,
reference)),
index);
}
private Resolution resolveView(
TableRef reference, TableDefinition definition, int depth, Map<String, Source> scope)
throws SQLException {
String key = (reference.schema() != null ? reference.schema() + "." : "")
+ reference.table().toLowerCase(Locale.ROOT);
if (!resolvingViews.add(key)) {
return null;
}
try {
List<Token> viewTokens = tokenize(definition.sql());
if (viewTokens == null) {
return null;
}
int as = indexOfWordIn(viewTokens, 0, viewTokens.size(), 0, "AS");
if (as < 0) {
return null;
}
List<String> explicit = null;
for (int i = 0; i < as; i++) {
Token token = viewTokens.get(i);
if (token.depth() == 0 && isSymbol(token, "(")) {
int close = matchingParenIn(viewTokens, i);
if (close < 0) {
return null;
}
explicit = identifiersIn(viewTokens, i + 1, close, 1);
break;
}
}
Resolution inner = new Parser(viewTokens, schema, resolvingViews)
.parseStatement(as + 1, viewTokens.size(), 0, new HashMap<>(scope));
if (inner == null) {
return null;
}
if (explicit != null && explicit.size() == inner.labels().size()) {
return new Resolution(explicit, inner.tables());
}
return inner;
} finally {
resolvingViews.remove(key);
}
}
private Resolution parseReturning(int start, int end, int depth, Map<String, Source> scope)
throws SQLException {
int returning = indexOfWord(start, end, depth, "RETURNING");
if (returning < 0) {
return null;
}
TableRef target = targetTable(start, returning, depth);
if (target == null) {
return null;
}
TableDefinition definition = schema.definition(target);
Source source;
if (definition == null) {
source = new Source(target.table(), List.of(), List.of(), false, target);
} else if (isViewDefinition(definition.sql())) {
List<String> columns = definition.columns();
source = new Source(
target.table(), columns, Collections.nCopies(columns.size(), null), true, null);
} else {
List<String> columns = definition.columns() != null ? definition.columns() : List.of();
source = new Source(
target.table(),
columns,
Collections.nCopies(columns.size(), target),
true,
target);
}
return parseSelectItems(returning + 1, end, depth, FromClause.of(List.of(source)), scope);
}
private TableRef targetTable(int start, int end, int depth) {
String keyword = wordAt(start, depth);
if (keyword == null) {
return null;
}
int index;
switch (keyword) {
case "INSERT", "REPLACE" -> {
index = indexOfWord(start, end, depth, "INTO");
if (index < 0) {
return null;
}
index++;
}
case "UPDATE" -> {
index = start + 1;
if (isWordAt(index, depth, "OR")) {
index += 2;
}
}
case "DELETE" -> {
index = indexOfWord(start, end, depth, "FROM");
if (index < 0) {
return null;
}
index++;
}
default -> {
return null;
}
}
String first = identifier(index);
if (first == null) {
return null;
}
index++;
String schemaName = null;
if (isSymbolAt(index, ".", depth)) {
index++;
String second = identifier(index);
if (second == null) {
return null;
}
schemaName = first;
first = second;
}
return new TableRef(schemaName, first);
}
private Resolution parseSelectItems(
int start, int end, int depth, FromClause from, Map<String, Source> scope)
throws SQLException {
List<String> labels = new ArrayList<>();
List<TableRef> tables = new ArrayList<>();
int index = start;
while (index < end) {
int comma = indexOfSymbol(index, end, depth, ",");
int itemEnd = comma < 0 ? end : comma;
parseItem(index, itemEnd, depth, from, scope, labels, tables);
if (comma < 0) {
break;
}
index = comma + 1;
}
return new Resolution(labels, tables);
}
private void parseItem(
int start,
int end,
int depth,
FromClause from,
Map<String, Source> scope,
List<String> labels,
List<TableRef> tables)
throws SQLException {
if (start >= end) {
labels.add("");
tables.add(null);
return;
}
String alias = null;
int expressionEnd = end;
int as = indexOfWord(start, end, depth, "AS");
if (as >= 0 && as + 1 < end) {
String candidate = identifier(as + 1);
if (candidate != null) {
alias = candidate;
expressionEnd = as;
}
} else {
int implicit = implicitAlias(start, end, depth);
if (implicit >= 0) {
alias = identifier(implicit);
expressionEnd = implicit;
}
}
if (expressionEnd <= start) {
labels.add(alias != null ? alias : "");
tables.add(null);
return;
}
if (expressionEnd - start == 1 && isSymbol(tokens.get(start), "*")) {
labels.addAll(from.starLabels());
tables.addAll(from.starTables());
return;
}
ColumnRef qualifiedStar = qualifiedStar(start, expressionEnd);
if (qualifiedStar != null) {
Source source = findSource(
qualifiedStar.parts().get(qualifiedStar.parts().size() - 1), from.sources());
if (source != null && source.knownColumns()) {
labels.addAll(source.columns());
tables.addAll(source.tables());
}
return;
}
ColumnRef column = simpleColumn(start, expressionEnd);
if (column != null) {
labels.add(alias != null ? alias : column.column());
tables.add(resolveColumn(column, from.sources()));
return;
}
if (isSymbol(tokens.get(start), "(") && matchingParen(start) == expressionEnd - 1) {
int innerDepth = depth + 1;
String innerKeyword = wordAt(start + 1, innerDepth);
if ("SELECT".equals(innerKeyword) || "WITH".equals(innerKeyword)) {
Resolution inner = parseStatement(start + 1, expressionEnd - 1, innerDepth, scope);
if (inner != null && inner.tables().size() == 1) {
labels.add(alias != null ? alias : inner.labels().get(0));
tables.add(inner.tables().get(0));
return;
}
}
}
labels.add(alias != null ? alias : expressionLabel(start, expressionEnd));
tables.add(null);
}
private TableRef resolveColumn(ColumnRef column, List<Source> sources) {
String qualifier = column.qualifier();
if (qualifier != null) {
Source source = findSource(qualifier, sources);
if (source == null) {
return null;
}
TableRef origin = source.origin(column.column());
if (origin != null) {
return origin;
}
return source.knownColumns() ? null : source.baseTable();
}
TableRef match = null;
int matches = 0;
for (Source source : sources) {
if (source.hasColumn(column.column())) {
matches++;
match = source.origin(column.column());
}
}
if (matches == 1) {
return match;
}
if (matches > 1) {
return null;
}
if (sources.size() == 1 && !sources.get(0).knownColumns()) {
return sources.get(0).baseTable();
}
return null;
}
private Source findSource(String qualifier, List<Source> sources) {
for (Source source : sources) {
if (source.matchesQualifier(qualifier)) {
return source;
}
}
return null;
}
private int implicitAlias(int start, int end, int depth) {
if (end - start < 2) {
return -1;
}
Token last = tokens.get(end - 1);
if (identifierOf(last) == null) {
return -1;
}
Token previous = tokens.get(end - 2);
if (isSymbol(previous, ".") || isSymbol(previous, "(") || isSymbol(previous, ",")) {
return -1;
}
if (previous.type() == Type.SYMBOL) {
return -1;
}
if (previous.type() == Type.WORD && NOT_AN_ALIAS.contains(upper(previous.text()))) {
return -1;
}
return end - 1;
}
private ColumnRef simpleColumn(int start, int end) {
List<String> parts = new ArrayList<>();
int index = start;
String first = identifier(index);
if (first == null) {
return null;
}
parts.add(first);
index++;
while (index < end) {
if (!isSymbol(tokens.get(index), ".")) {
return null;
}
index++;
if (index >= end) {
return null;
}
String part = identifier(index);
if (part == null) {
return null;
}
parts.add(part);
index++;
}
return parts.size() <= 3 ? new ColumnRef(parts) : null;
}
private ColumnRef qualifiedStar(int start, int end) {
if (end - start < 3 || !isSymbol(tokens.get(end - 1), "*")) {
return null;
}
List<String> parts = new ArrayList<>();
int index = start;
while (index < end - 1) {
String part = identifier(index);
if (part == null) {
return null;
}
parts.add(part);
index++;
if (index == end - 1) {
break;
}
if (!isSymbol(tokens.get(index), ".")) {
return null;
}
index++;
}
if (index != end - 1 || !isSymbol(tokens.get(end - 2), ".")) {
return null;
}
if (parts.size() < 1 || parts.size() > 2) {
return null;
}
return new ColumnRef(parts);
}
private String expressionLabel(int start, int end) {
StringBuilder label = new StringBuilder();
for (int i = start; i < end; i++) {
label.append(tokens.get(i).text());
}
return label.toString();
}
private int skipIndexModifiers(int start, int end, int depth) {
int index = start;
while (index < end) {
if (isWordAt(index, depth, "INDEXED")) {
index += 3;
continue;
}
if (isWordAt(index, depth, "NOT") && isWordAt(index + 1, depth, "INDEXED")) {
index += 3;
continue;
}
break;
}
return index;
}
private int skipJoinCondition(int start, int end, int depth) {
if (!isWordAt(start, depth, "ON") && !isWordAt(start, depth, "USING")) {
return start;
}
int index = start + 1;
while (index < end) {
if (tokens.get(index).depth() == depth) {
if (isSymbol(tokens.get(index), ",") || isJoinStart(index, end, depth)) {
break;
}
}
index++;
}
return index;
}
private boolean isJoinStart(int index, int end, int depth) {
if (index >= end) {
return false;
}
Token token = tokens.get(index);
return token.depth() == depth
&& token.type() == Type.WORD
&& JOIN_START.contains(upper(token.text()));
}
private int skipToJoin(int start, int end, int depth) {
for (int index = start; index < end; index++) {
if (isWordAt(index, depth, "JOIN")) {
return index;
}
}
return -1;
}
private boolean isAlias(int index, int depth) {
if (index >= tokens.size()) {
return false;
}
Token token = tokens.get(index);
if (token.depth() != depth || identifierOf(token) == null) {
return false;
}
if (token.type() == Type.WORD) {
String keyword = upper(token.text());
return !FROM_END.contains(keyword)
&& !JOIN_START.contains(keyword)
&& !NOT_AN_ALIAS.contains(keyword);
}
return true;
}
private List<String> usingColumns(int start, int end, int depth) {
if (!isSymbolAt(start + 1, "(", depth)) {
return List.of();
}
int close = matchingParen(start + 1);
if (close < 0 || close > end) {
return List.of();
}
return identifiers(start + 2, close, depth + 1);
}
private List<String> identifiers(int start, int end, int depth) {
List<String> identifiers = new ArrayList<>();
int index = start;
while (index < end) {
String identifier = identifier(index);
if (identifier == null || tokens.get(index).depth() != depth) {
return List.of();
}
identifiers.add(identifier);
index++;
if (index < end) {
if (!isSymbol(tokens.get(index), ",")) {
return List.of();
}
index++;
}
}
return identifiers;
}
private int skipSymbols(int start, int end, int depth, String symbol) {
int index = start;
while (index < end && isSymbolAt(index, symbol, depth)) {
index++;
}
return index;
}
private int indexOfWord(int start, int end, int depth, String word) {
for (int index = start; index < end; index++) {
if (isWordAt(index, depth, word)) {
return index;
}
}
return -1;
}
private int indexOfAnyWord(int start, int end, int depth, Set<String> words) {
for (int index = start; index < end; index++) {
Token token = tokens.get(index);
if (token.depth() == depth && token.type() == Type.WORD && words.contains(upper(token.text()))) {
return index;
}
}
return -1;
}
private int indexOfSymbol(int start, int end, int depth, String symbol) {
for (int index = start; index < end; index++) {
if (isSymbolAt(index, symbol, depth)) {
return index;
}
}
return -1;
}
private boolean isWordAt(int index, int depth, String word) {
if (index < 0 || index >= tokens.size()) {
return false;
}
Token token = tokens.get(index);
return token.depth() == depth && token.type() == Type.WORD && upper(token.text()).equals(word);
}
private boolean isSymbolAt(int index, String symbol, int depth) {
if (index < 0 || index >= tokens.size()) {
return false;
}
Token token = tokens.get(index);
return token.depth() == depth && isSymbol(token, symbol);
}
private String wordAt(int index, int depth) {
if (index < 0 || index >= tokens.size()) {
return null;
}
Token token = tokens.get(index);
return token.depth() == depth && token.type() == Type.WORD ? upper(token.text()) : null;
}
private String identifier(int index) {
if (index < 0 || index >= tokens.size()) {
return null;
}
return identifierOf(tokens.get(index));
}
private int matchingParen(int open) {
return matchingParenIn(tokens, open);
}
}
private static int matchingParenIn(List<Token> tokens, int open) {
if (open < 0 || open >= tokens.size()) {
return -1;
}
int depth = tokens.get(open).depth();
for (int index = open + 1; index < tokens.size(); index++) {
Token token = tokens.get(index);
if (token.depth() == depth && isSymbol(token, ")")) {
return index;
}
}
return -1;
}
private static int indexOfWordIn(List<Token> tokens, int start, int end, int depth, String word) {