/
SqlValidatorImpl.java
7291 lines (6646 loc) · 251 KB
/
SqlValidatorImpl.java
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.
*/
package org.apache.calcite.sql.validate;
import org.apache.calcite.linq4j.Ord;
import org.apache.calcite.linq4j.function.Functions;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.prepare.Prepare;
import org.apache.calcite.rel.type.DynamicRecordType;
import org.apache.calcite.rel.type.RelCrossType;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.rel.type.RelDataTypeField;
import org.apache.calcite.rel.type.RelDataTypeSystem;
import org.apache.calcite.rel.type.RelRecordType;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.rex.RexPatternFieldRef;
import org.apache.calcite.rex.RexVisitor;
import org.apache.calcite.runtime.CalciteContextException;
import org.apache.calcite.runtime.CalciteException;
import org.apache.calcite.runtime.Feature;
import org.apache.calcite.runtime.Resources;
import org.apache.calcite.schema.ColumnStrategy;
import org.apache.calcite.schema.Table;
import org.apache.calcite.schema.impl.ModifiableViewTable;
import org.apache.calcite.sql.JoinConditionType;
import org.apache.calcite.sql.JoinType;
import org.apache.calcite.sql.SqlAccessEnum;
import org.apache.calcite.sql.SqlAccessType;
import org.apache.calcite.sql.SqlAggFunction;
import org.apache.calcite.sql.SqlBasicCall;
import org.apache.calcite.sql.SqlCall;
import org.apache.calcite.sql.SqlCallBinding;
import org.apache.calcite.sql.SqlDataTypeSpec;
import org.apache.calcite.sql.SqlDelete;
import org.apache.calcite.sql.SqlDynamicParam;
import org.apache.calcite.sql.SqlExplain;
import org.apache.calcite.sql.SqlFunction;
import org.apache.calcite.sql.SqlFunctionCategory;
import org.apache.calcite.sql.SqlIdentifier;
import org.apache.calcite.sql.SqlInsert;
import org.apache.calcite.sql.SqlIntervalLiteral;
import org.apache.calcite.sql.SqlIntervalQualifier;
import org.apache.calcite.sql.SqlJoin;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.SqlLiteral;
import org.apache.calcite.sql.SqlMatchRecognize;
import org.apache.calcite.sql.SqlMerge;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.SqlNodeList;
import org.apache.calcite.sql.SqlOperator;
import org.apache.calcite.sql.SqlOperatorTable;
import org.apache.calcite.sql.SqlOrderBy;
import org.apache.calcite.sql.SqlPivot;
import org.apache.calcite.sql.SqlSampleSpec;
import org.apache.calcite.sql.SqlSelect;
import org.apache.calcite.sql.SqlSelectKeyword;
import org.apache.calcite.sql.SqlSnapshot;
import org.apache.calcite.sql.SqlSyntax;
import org.apache.calcite.sql.SqlTableFunction;
import org.apache.calcite.sql.SqlUnpivot;
import org.apache.calcite.sql.SqlUnresolvedFunction;
import org.apache.calcite.sql.SqlUpdate;
import org.apache.calcite.sql.SqlUtil;
import org.apache.calcite.sql.SqlWindow;
import org.apache.calcite.sql.SqlWindowTableFunction;
import org.apache.calcite.sql.SqlWith;
import org.apache.calcite.sql.SqlWithItem;
import org.apache.calcite.sql.TableCharacteristic;
import org.apache.calcite.sql.fun.SqlCase;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.sql.type.AssignableOperandTypeChecker;
import org.apache.calcite.sql.type.OperandTypes;
import org.apache.calcite.sql.type.ReturnTypes;
import org.apache.calcite.sql.type.SqlOperandTypeChecker;
import org.apache.calcite.sql.type.SqlOperandTypeInference;
import org.apache.calcite.sql.type.SqlTypeCoercionRule;
import org.apache.calcite.sql.type.SqlTypeFamily;
import org.apache.calcite.sql.type.SqlTypeName;
import org.apache.calcite.sql.type.SqlTypeUtil;
import org.apache.calcite.sql.util.IdPair;
import org.apache.calcite.sql.util.SqlBasicVisitor;
import org.apache.calcite.sql.util.SqlShuttle;
import org.apache.calcite.sql.util.SqlVisitor;
import org.apache.calcite.sql.validate.implicit.TypeCoercion;
import org.apache.calcite.util.BitString;
import org.apache.calcite.util.Bug;
import org.apache.calcite.util.ImmutableBitSet;
import org.apache.calcite.util.ImmutableIntList;
import org.apache.calcite.util.ImmutableNullableList;
import org.apache.calcite.util.Litmus;
import org.apache.calcite.util.Optionality;
import org.apache.calcite.util.Pair;
import org.apache.calcite.util.Static;
import org.apache.calcite.util.Util;
import org.apache.calcite.util.trace.CalciteTrace;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.apiguardian.api.API;
import org.checkerframework.checker.nullness.qual.KeyFor;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.checker.nullness.qual.PolyNull;
import org.checkerframework.dataflow.qual.Pure;
import org.slf4j.Logger;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.AbstractList;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import static org.apache.calcite.linq4j.Nullness.castNonNull;
import static org.apache.calcite.sql.SqlUtil.stripAs;
import static org.apache.calcite.sql.type.NonNullableAccessors.getCharset;
import static org.apache.calcite.sql.type.NonNullableAccessors.getCollation;
import static org.apache.calcite.sql.validate.SqlNonNullableAccessors.getCondition;
import static org.apache.calcite.sql.validate.SqlNonNullableAccessors.getTable;
import static org.apache.calcite.util.Static.RESOURCE;
import static java.util.Objects.requireNonNull;
/**
* Default implementation of {@link SqlValidator}.
*/
public class SqlValidatorImpl implements SqlValidatorWithHints {
//~ Static fields/initializers ---------------------------------------------
public static final Logger TRACER = CalciteTrace.PARSER_LOGGER;
/**
* Alias generated for the source table when rewriting UPDATE to MERGE.
*/
public static final String UPDATE_SRC_ALIAS = "SYS$SRC";
/**
* Alias generated for the target table when rewriting UPDATE to MERGE if no
* alias was specified by the user.
*/
public static final String UPDATE_TGT_ALIAS = "SYS$TGT";
/**
* Alias prefix generated for source columns when rewriting UPDATE to MERGE.
*/
public static final String UPDATE_ANON_PREFIX = "SYS$ANON";
//~ Instance fields --------------------------------------------------------
private final SqlOperatorTable opTab;
final SqlValidatorCatalogReader catalogReader;
/**
* Maps {@link SqlParserPos} strings to the {@link SqlIdentifier} identifier
* objects at these positions.
*/
protected final Map<String, IdInfo> idPositions = new HashMap<>();
/**
* Maps {@link SqlNode query node} objects to the {@link SqlValidatorScope}
* scope created from them.
*/
protected final IdentityHashMap<SqlNode, SqlValidatorScope> scopes =
new IdentityHashMap<>();
/**
* Maps a {@link SqlSelect} and a clause to the scope used by that clause.
*/
private final Map<IdPair<SqlSelect, Clause>, SqlValidatorScope>
clauseScopes = new HashMap<>();
/**
* The name-resolution scope of a LATERAL TABLE clause.
*/
private @Nullable TableScope tableScope = null;
/**
* Maps a {@link SqlNode node} to the
* {@link SqlValidatorNamespace namespace} which describes what columns they
* contain.
*/
protected final IdentityHashMap<SqlNode, SqlValidatorNamespace> namespaces =
new IdentityHashMap<>();
/**
* Set of select expressions used as cursor definitions. In standard SQL,
* only the top-level SELECT is a cursor; Calcite extends this with
* cursors as inputs to table functions.
*/
private final Set<SqlNode> cursorSet = Sets.newIdentityHashSet();
/**
* Stack of objects that maintain information about function calls. A stack
* is needed to handle nested function calls. The function call currently
* being validated is at the top of the stack.
*/
protected final Deque<FunctionParamInfo> functionCallStack =
new ArrayDeque<>();
private int nextGeneratedId;
protected final RelDataTypeFactory typeFactory;
protected final RelDataType unknownType;
private final RelDataType booleanType;
/**
* Map of derived RelDataType for each node. This is an IdentityHashMap
* since in some cases (such as null literals) we need to discriminate by
* instance.
*/
private final IdentityHashMap<SqlNode, RelDataType> nodeToTypeMap =
new IdentityHashMap<>();
/** Provides the data for {@link #getValidatedOperandTypes(SqlCall)}. */
public final IdentityHashMap<SqlCall, List<RelDataType>> callToOperandTypesMap =
new IdentityHashMap<>();
private final AggFinder aggFinder;
private final AggFinder aggOrOverFinder;
private final AggFinder aggOrOverOrGroupFinder;
private final AggFinder groupFinder;
private final AggFinder overFinder;
private Config config;
private final Map<SqlNode, SqlNode> originalExprs = new HashMap<>();
private @Nullable SqlNode top;
// TODO jvs 11-Dec-2008: make this local to performUnconditionalRewrites
// if it's OK to expand the signature of that method.
private boolean validatingSqlMerge;
private boolean inWindow; // Allow nested aggregates
private final SqlValidatorImpl.ValidationErrorFunction validationErrorFunction =
new SqlValidatorImpl.ValidationErrorFunction();
// TypeCoercion instance used for implicit type coercion.
private TypeCoercion typeCoercion;
//~ Constructors -----------------------------------------------------------
/**
* Creates a validator.
*
* @param opTab Operator table
* @param catalogReader Catalog reader
* @param typeFactory Type factory
* @param config Config
*/
protected SqlValidatorImpl(
SqlOperatorTable opTab,
SqlValidatorCatalogReader catalogReader,
RelDataTypeFactory typeFactory,
Config config) {
this.opTab = requireNonNull(opTab, "opTab");
this.catalogReader = requireNonNull(catalogReader, "catalogReader");
this.typeFactory = requireNonNull(typeFactory, "typeFactory");
this.config = requireNonNull(config, "config");
// It is assumed that unknown type is nullable by default
unknownType = typeFactory.createTypeWithNullability(typeFactory.createUnknownType(), true);
booleanType = typeFactory.createSqlType(SqlTypeName.BOOLEAN);
final SqlNameMatcher nameMatcher = catalogReader.nameMatcher();
aggFinder = new AggFinder(opTab, false, true, false, null, nameMatcher);
aggOrOverFinder =
new AggFinder(opTab, true, true, false, null, nameMatcher);
overFinder = new AggFinder(opTab, true, false, false, aggOrOverFinder,
nameMatcher);
groupFinder = new AggFinder(opTab, false, false, true, null, nameMatcher);
aggOrOverOrGroupFinder = new AggFinder(opTab, true, true, true, null,
nameMatcher);
@SuppressWarnings("argument.type.incompatible")
TypeCoercion typeCoercion = config.typeCoercionFactory().create(typeFactory, this);
this.typeCoercion = typeCoercion;
if (config.typeCoercionRules() != null) {
SqlTypeCoercionRule.THREAD_PROVIDERS.set(config.typeCoercionRules());
}
}
//~ Methods ----------------------------------------------------------------
public SqlConformance getConformance() {
return config.conformance();
}
@Pure
@Override public SqlValidatorCatalogReader getCatalogReader() {
return catalogReader;
}
@Pure
@Override public SqlOperatorTable getOperatorTable() {
return opTab;
}
@Pure
@Override public RelDataTypeFactory getTypeFactory() {
return typeFactory;
}
@Override public RelDataType getUnknownType() {
return unknownType;
}
@Override public SqlNodeList expandStar(
SqlNodeList selectList,
SqlSelect select,
boolean includeSystemVars) {
final List<SqlNode> list = new ArrayList<>();
final List<Map.Entry<String, RelDataType>> types = new ArrayList<>();
for (int i = 0; i < selectList.size(); i++) {
final SqlNode selectItem = selectList.get(i);
final RelDataType originalType = getValidatedNodeTypeIfKnown(selectItem);
expandSelectItem(
selectItem,
select,
Util.first(originalType, unknownType),
list,
catalogReader.nameMatcher().createSet(),
types,
includeSystemVars);
}
getRawSelectScopeNonNull(select).setExpandedSelectList(list);
return new SqlNodeList(list, SqlParserPos.ZERO);
}
// implement SqlValidator
@Override public void declareCursor(SqlSelect select, SqlValidatorScope parentScope) {
cursorSet.add(select);
// add the cursor to a map that maps the cursor to its select based on
// the position of the cursor relative to other cursors in that call
FunctionParamInfo funcParamInfo = requireNonNull(functionCallStack.peek(), "functionCall");
Map<Integer, SqlSelect> cursorMap = funcParamInfo.cursorPosToSelectMap;
int numCursors = cursorMap.size();
cursorMap.put(numCursors, select);
// create a namespace associated with the result of the select
// that is the argument to the cursor constructor; register it
// with a scope corresponding to the cursor
SelectScope cursorScope = new SelectScope(parentScope, null, select);
clauseScopes.put(IdPair.of(select, Clause.CURSOR), cursorScope);
final SelectNamespace selectNs = createSelectNamespace(select, select);
String alias = deriveAlias(select, nextGeneratedId++);
registerNamespace(cursorScope, alias, selectNs, false);
}
// implement SqlValidator
@Override public void pushFunctionCall() {
FunctionParamInfo funcInfo = new FunctionParamInfo();
functionCallStack.push(funcInfo);
}
// implement SqlValidator
@Override public void popFunctionCall() {
functionCallStack.pop();
}
// implement SqlValidator
@Override public @Nullable String getParentCursor(String columnListParamName) {
FunctionParamInfo funcParamInfo = requireNonNull(functionCallStack.peek(), "functionCall");
Map<String, String> parentCursorMap =
funcParamInfo.columnListParamToParentCursorMap;
return parentCursorMap.get(columnListParamName);
}
/**
* If <code>selectItem</code> is "*" or "TABLE.*", expands it and returns
* true; otherwise writes the unexpanded item.
*
* @param selectItem Select-list item
* @param select Containing select clause
* @param selectItems List that expanded items are written to
* @param aliases Set of aliases
* @param fields List of field names and types, in alias order
* @param includeSystemVars If true include system vars in lists
* @return Whether the node was expanded
*/
private boolean expandSelectItem(
final SqlNode selectItem,
SqlSelect select,
RelDataType targetType,
List<SqlNode> selectItems,
Set<String> aliases,
List<Map.Entry<String, RelDataType>> fields,
final boolean includeSystemVars) {
final SelectScope scope = (SelectScope) getWhereScope(select);
if (expandStar(selectItems, aliases, fields, includeSystemVars, scope,
selectItem)) {
return true;
}
// Expand the select item: fully-qualify columns, and convert
// parentheses-free functions such as LOCALTIME into explicit function
// calls.
SqlNode expanded = expandSelectExpr(selectItem, scope, select);
final String alias =
deriveAliasNonNull(
selectItem,
aliases.size());
// If expansion has altered the natural alias, supply an explicit 'AS'.
final SqlValidatorScope selectScope = getSelectScope(select);
if (expanded != selectItem) {
String newAlias =
deriveAliasNonNull(
expanded,
aliases.size());
if (!Objects.equals(newAlias, alias)) {
expanded =
SqlStdOperatorTable.AS.createCall(
selectItem.getParserPosition(),
expanded,
new SqlIdentifier(alias, SqlParserPos.ZERO));
deriveTypeImpl(selectScope, expanded);
}
}
selectItems.add(expanded);
aliases.add(alias);
if (expanded != null) {
inferUnknownTypes(targetType, scope, expanded);
}
RelDataType type = deriveType(selectScope, expanded);
// Re-derive SELECT ITEM's data type that may be nullable in AggregatingSelectScope when it
// appears in advanced grouping elements such as CUBE, ROLLUP , GROUPING SETS.
// For example, SELECT CASE WHEN c = 1 THEN '1' ELSE '23' END AS x FROM t GROUP BY CUBE(x),
// the 'x' should be nullable even if x's literal values are not null.
if (selectScope instanceof AggregatingSelectScope) {
type = requireNonNull(selectScope.nullifyType(stripAs(expanded), type));
}
setValidatedNodeType(expanded, type);
fields.add(Pair.of(alias, type));
return false;
}
private static SqlNode expandExprFromJoin(SqlJoin join, SqlIdentifier identifier,
@Nullable SelectScope scope) {
if (join.getConditionType() != JoinConditionType.USING) {
return identifier;
}
for (String name
: SqlIdentifier.simpleNames((SqlNodeList) getCondition(join))) {
if (identifier.getSimple().equals(name)) {
final List<SqlNode> qualifiedNode = new ArrayList<>();
for (ScopeChild child : requireNonNull(scope, "scope").children) {
if (child.namespace.getRowType()
.getFieldNames().indexOf(name) >= 0) {
final SqlIdentifier exp =
new SqlIdentifier(
ImmutableList.of(child.name, name),
identifier.getParserPosition());
qualifiedNode.add(exp);
}
}
assert qualifiedNode.size() == 2;
final SqlNode finalNode =
SqlStdOperatorTable.AS.createCall(SqlParserPos.ZERO,
SqlStdOperatorTable.COALESCE.createCall(SqlParserPos.ZERO,
qualifiedNode.get(0),
qualifiedNode.get(1)),
new SqlIdentifier(name, SqlParserPos.ZERO));
return finalNode;
}
}
// Only need to try to expand the expr from the left input of join
// since it is always left-deep join.
final SqlNode node = join.getLeft();
if (node instanceof SqlJoin) {
return expandExprFromJoin((SqlJoin) node, identifier, scope);
} else {
return identifier;
}
}
/** Returns the set of field names in the join condition specified by USING
* or implicitly by NATURAL, de-duplicated and in order. */
public @Nullable List<String> usingNames(SqlJoin join) {
switch (join.getConditionType()) {
case USING:
SqlNodeList condition = (SqlNodeList) getCondition(join);
List<String> simpleNames = SqlIdentifier.simpleNames(condition);
return catalogReader.nameMatcher().distinctCopy(simpleNames);
case NONE:
if (join.isNatural()) {
return deriveNaturalJoinColumnList(join);
}
return null;
default:
return null;
}
}
private List<String> deriveNaturalJoinColumnList(SqlJoin join) {
return SqlValidatorUtil.deriveNaturalJoinColumnList(
catalogReader.nameMatcher(),
getNamespaceOrThrow(join.getLeft()).getRowType(),
getNamespaceOrThrow(join.getRight()).getRowType());
}
private static SqlNode expandCommonColumn(SqlSelect sqlSelect,
SqlNode selectItem, @Nullable SelectScope scope, SqlValidatorImpl validator) {
if (!(selectItem instanceof SqlIdentifier)) {
return selectItem;
}
final SqlNode from = sqlSelect.getFrom();
if (!(from instanceof SqlJoin)) {
return selectItem;
}
final SqlIdentifier identifier = (SqlIdentifier) selectItem;
if (!identifier.isSimple()) {
if (!validator.config().conformance().allowQualifyingCommonColumn()) {
validateQualifiedCommonColumn((SqlJoin) from, identifier, scope, validator);
}
return selectItem;
}
return expandExprFromJoin((SqlJoin) from, identifier, scope);
}
private static void validateQualifiedCommonColumn(SqlJoin join,
SqlIdentifier identifier, @Nullable SelectScope scope, SqlValidatorImpl validator) {
List<String> names = validator.usingNames(join);
if (names == null) {
// Not USING or NATURAL.
return;
}
requireNonNull(scope, "scope");
// First we should make sure that the first component is the table name.
// Then check whether the qualified identifier contains common column.
for (ScopeChild child : scope.children) {
if (Objects.equals(child.name, identifier.getComponent(0).toString())) {
if (names.contains(identifier.getComponent(1).toString())) {
throw validator.newValidationError(identifier,
RESOURCE.disallowsQualifyingCommonColumn(identifier.toString()));
}
}
}
// Only need to try to validate the expr from the left input of join
// since it is always left-deep join.
final SqlNode node = join.getLeft();
if (node instanceof SqlJoin) {
validateQualifiedCommonColumn((SqlJoin) node, identifier, scope, validator);
}
}
private boolean expandStar(List<SqlNode> selectItems, Set<String> aliases,
List<Map.Entry<String, RelDataType>> fields, boolean includeSystemVars,
SelectScope scope, SqlNode node) {
if (!(node instanceof SqlIdentifier)) {
return false;
}
final SqlIdentifier identifier = (SqlIdentifier) node;
if (!identifier.isStar()) {
return false;
}
final SqlParserPos startPosition = identifier.getParserPosition();
switch (identifier.names.size()) {
case 1:
boolean hasDynamicStruct = false;
for (ScopeChild child : scope.children) {
final int before = fields.size();
if (child.namespace.getRowType().isDynamicStruct()) {
hasDynamicStruct = true;
// don't expand star if the underneath table is dynamic.
// Treat this star as a special field in validation/conversion and
// wait until execution time to expand this star.
final SqlNode exp =
new SqlIdentifier(
ImmutableList.of(child.name,
DynamicRecordType.DYNAMIC_STAR_PREFIX),
startPosition);
addToSelectList(
selectItems,
aliases,
fields,
exp,
scope,
includeSystemVars);
} else {
final SqlNode from = SqlNonNullableAccessors.getNode(child);
final SqlValidatorNamespace fromNs = getNamespaceOrThrow(from, scope);
final RelDataType rowType = fromNs.getRowType();
for (RelDataTypeField field : rowType.getFieldList()) {
String columnName = field.getName();
// TODO: do real implicit collation here
final SqlIdentifier exp =
new SqlIdentifier(
ImmutableList.of(child.name, columnName),
startPosition);
// Don't add expanded rolled up columns
if (!isRolledUpColumn(exp, scope)) {
addOrExpandField(
selectItems,
aliases,
fields,
includeSystemVars,
scope,
exp,
field);
}
}
}
if (child.nullable) {
for (int i = before; i < fields.size(); i++) {
final Map.Entry<String, RelDataType> entry = fields.get(i);
final RelDataType type = entry.getValue();
if (!type.isNullable()) {
fields.set(i,
Pair.of(entry.getKey(),
typeFactory.createTypeWithNullability(type, true)));
}
}
}
}
// If NATURAL JOIN or USING is present, move key fields to the front of
// the list, per standard SQL. Disabled if there are dynamic fields.
if (!hasDynamicStruct || Bug.CALCITE_2400_FIXED) {
SqlNode from = requireNonNull(scope.getNode().getFrom(),
() -> "getFrom for " + scope.getNode());
new Permute(from, 0).permute(selectItems, fields);
}
return true;
default:
final SqlIdentifier prefixId = identifier.skipLast(1);
final SqlValidatorScope.ResolvedImpl resolved =
new SqlValidatorScope.ResolvedImpl();
final SqlNameMatcher nameMatcher =
scope.validator.catalogReader.nameMatcher();
scope.resolve(prefixId.names, nameMatcher, true, resolved);
if (resolved.count() == 0) {
// e.g. "select s.t.* from e"
// or "select r.* from e"
throw newValidationError(prefixId,
RESOURCE.unknownIdentifier(prefixId.toString()));
}
final RelDataType rowType = resolved.only().rowType();
if (rowType.isDynamicStruct()) {
// don't expand star if the underneath table is dynamic.
addToSelectList(
selectItems,
aliases,
fields,
prefixId.plus(DynamicRecordType.DYNAMIC_STAR_PREFIX, startPosition),
scope,
includeSystemVars);
} else if (rowType.isStruct()) {
for (RelDataTypeField field : rowType.getFieldList()) {
String columnName = field.getName();
// TODO: do real implicit collation here
addOrExpandField(
selectItems,
aliases,
fields,
includeSystemVars,
scope,
prefixId.plus(columnName, startPosition),
field);
}
} else {
throw newValidationError(prefixId, RESOURCE.starRequiresRecordType());
}
return true;
}
}
private SqlNode maybeCast(SqlNode node, RelDataType currentType,
RelDataType desiredType) {
return SqlTypeUtil.equalSansNullability(typeFactory, currentType, desiredType)
? node
: SqlStdOperatorTable.CAST.createCall(SqlParserPos.ZERO,
node, SqlTypeUtil.convertTypeToSpec(desiredType));
}
private boolean addOrExpandField(List<SqlNode> selectItems, Set<String> aliases,
List<Map.Entry<String, RelDataType>> fields, boolean includeSystemVars,
SelectScope scope, SqlIdentifier id, RelDataTypeField field) {
switch (field.getType().getStructKind()) {
case PEEK_FIELDS:
case PEEK_FIELDS_DEFAULT:
final SqlNode starExp = id.plusStar();
expandStar(
selectItems,
aliases,
fields,
includeSystemVars,
scope,
starExp);
return true;
default:
addToSelectList(
selectItems,
aliases,
fields,
id,
scope,
includeSystemVars);
}
return false;
}
@Override public SqlNode validate(SqlNode topNode) {
SqlValidatorScope scope = new EmptyScope(this);
scope = new CatalogScope(scope, ImmutableList.of("CATALOG"));
final SqlNode topNode2 = validateScopedExpression(topNode, scope);
final RelDataType type = getValidatedNodeType(topNode2);
Util.discard(type);
return topNode2;
}
@Override public List<SqlMoniker> lookupHints(SqlNode topNode, SqlParserPos pos) {
SqlValidatorScope scope = new EmptyScope(this);
SqlNode outermostNode = performUnconditionalRewrites(topNode, false);
cursorSet.add(outermostNode);
if (outermostNode.isA(SqlKind.TOP_LEVEL)) {
registerQuery(
scope,
null,
outermostNode,
outermostNode,
null,
false);
}
final SqlValidatorNamespace ns = getNamespace(outermostNode);
if (ns == null) {
throw new AssertionError("Not a query: " + outermostNode);
}
Collection<SqlMoniker> hintList = Sets.newTreeSet(SqlMoniker.COMPARATOR);
lookupSelectHints(ns, pos, hintList);
return ImmutableList.copyOf(hintList);
}
@Override public @Nullable SqlMoniker lookupQualifiedName(SqlNode topNode, SqlParserPos pos) {
final String posString = pos.toString();
IdInfo info = idPositions.get(posString);
if (info != null) {
final SqlQualified qualified = info.scope.fullyQualify(info.id);
return new SqlIdentifierMoniker(qualified.identifier);
} else {
return null;
}
}
/**
* Looks up completion hints for a syntactically correct select SQL that has
* been parsed into an expression tree.
*
* @param select the Select node of the parsed expression tree
* @param pos indicates the position in the sql statement we want to get
* completion hints for
* @param hintList list of {@link SqlMoniker} (sql identifiers) that can
* fill in at the indicated position
*/
void lookupSelectHints(
SqlSelect select,
SqlParserPos pos,
Collection<SqlMoniker> hintList) {
IdInfo info = idPositions.get(pos.toString());
if ((info == null) || (info.scope == null)) {
SqlNode fromNode = select.getFrom();
final SqlValidatorScope fromScope = getFromScope(select);
lookupFromHints(fromNode, fromScope, pos, hintList);
} else {
lookupNameCompletionHints(info.scope, info.id.names,
info.id.getParserPosition(), hintList);
}
}
private void lookupSelectHints(
SqlValidatorNamespace ns,
SqlParserPos pos,
Collection<SqlMoniker> hintList) {
final SqlNode node = ns.getNode();
if (node instanceof SqlSelect) {
lookupSelectHints((SqlSelect) node, pos, hintList);
}
}
private void lookupFromHints(
@Nullable SqlNode node,
@Nullable SqlValidatorScope scope,
SqlParserPos pos,
Collection<SqlMoniker> hintList) {
if (node == null) {
// This can happen in cases like "select * _suggest_", so from clause is absent
return;
}
final SqlValidatorNamespace ns = getNamespaceOrThrow(node);
if (ns.isWrapperFor(IdentifierNamespace.class)) {
IdentifierNamespace idNs = ns.unwrap(IdentifierNamespace.class);
final SqlIdentifier id = idNs.getId();
for (int i = 0; i < id.names.size(); i++) {
if (pos.toString().equals(
id.getComponent(i).getParserPosition().toString())) {
final List<SqlMoniker> objNames = new ArrayList<>();
SqlValidatorUtil.getSchemaObjectMonikers(
getCatalogReader(),
id.names.subList(0, i + 1),
objNames);
for (SqlMoniker objName : objNames) {
if (objName.getType() != SqlMonikerType.FUNCTION) {
hintList.add(objName);
}
}
return;
}
}
}
switch (node.getKind()) {
case JOIN:
lookupJoinHints((SqlJoin) node, scope, pos, hintList);
break;
default:
lookupSelectHints(ns, pos, hintList);
break;
}
}
private void lookupJoinHints(
SqlJoin join,
@Nullable SqlValidatorScope scope,
SqlParserPos pos,
Collection<SqlMoniker> hintList) {
SqlNode left = join.getLeft();
SqlNode right = join.getRight();
SqlNode condition = join.getCondition();
lookupFromHints(left, scope, pos, hintList);
if (hintList.size() > 0) {
return;
}
lookupFromHints(right, scope, pos, hintList);
if (hintList.size() > 0) {
return;
}
final JoinConditionType conditionType = join.getConditionType();
switch (conditionType) {
case ON:
requireNonNull(condition, () -> "join.getCondition() for " + join)
.findValidOptions(this,
getScopeOrThrow(join),
pos, hintList);
return;
default:
// No suggestions.
// Not supporting hints for other types such as 'Using' yet.
}
}
/**
* Populates a list of all the valid alternatives for an identifier.
*
* @param scope Validation scope
* @param names Components of the identifier
* @param pos position
* @param hintList a list of valid options
*/
public final void lookupNameCompletionHints(
SqlValidatorScope scope,
List<String> names,
SqlParserPos pos,
Collection<SqlMoniker> hintList) {
// Remove the last part of name - it is a dummy
List<String> subNames = Util.skipLast(names);
if (subNames.size() > 0) {
// If there's a prefix, resolve it to a namespace.
SqlValidatorNamespace ns = null;
for (String name : subNames) {
if (ns == null) {
final SqlValidatorScope.ResolvedImpl resolved =
new SqlValidatorScope.ResolvedImpl();
final SqlNameMatcher nameMatcher = catalogReader.nameMatcher();
scope.resolve(ImmutableList.of(name), nameMatcher, false, resolved);
if (resolved.count() == 1) {
ns = resolved.only().namespace;
}
} else {
ns = ns.lookupChild(name);
}
if (ns == null) {
break;
}
}
if (ns != null) {
RelDataType rowType = ns.getRowType();
if (rowType.isStruct()) {
for (RelDataTypeField field : rowType.getFieldList()) {
hintList.add(
new SqlMonikerImpl(
field.getName(),
SqlMonikerType.COLUMN));
}
}
}
// builtin function names are valid completion hints when the
// identifier has only 1 name part
findAllValidFunctionNames(names, this, hintList, pos);
} else {
// No prefix; use the children of the current scope (that is,
// the aliases in the FROM clause)
scope.findAliases(hintList);
// If there's only one alias, add all child columns
SelectScope selectScope =
SqlValidatorUtil.getEnclosingSelectScope(scope);
if ((selectScope != null)
&& (selectScope.getChildren().size() == 1)) {
RelDataType rowType =
selectScope.getChildren().get(0).getRowType();
for (RelDataTypeField field : rowType.getFieldList()) {
hintList.add(
new SqlMonikerImpl(
field.getName(),
SqlMonikerType.COLUMN));
}
}
}
findAllValidUdfNames(names, this, hintList);
}
private static void findAllValidUdfNames(
List<String> names,
SqlValidator validator,
Collection<SqlMoniker> result) {
final List<SqlMoniker> objNames = new ArrayList<>();
SqlValidatorUtil.getSchemaObjectMonikers(
validator.getCatalogReader(),
names,
objNames);
for (SqlMoniker objName : objNames) {
if (objName.getType() == SqlMonikerType.FUNCTION) {
result.add(objName);
}
}
}
private static void findAllValidFunctionNames(
List<String> names,
SqlValidator validator,
Collection<SqlMoniker> result,
SqlParserPos pos) {
// a function name can only be 1 part
if (names.size() > 1) {