-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
BaseSemanticAnalyzer.java
2097 lines (1893 loc) · 78 KB
/
BaseSemanticAnalyzer.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.hadoop.hive.ql.parse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Stream;
import org.antlr.runtime.TokenRewriteStream;
import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.Tree;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.FileUtils;
import org.apache.hadoop.hive.common.TableName;
import org.apache.hadoop.hive.common.type.Date;
import org.apache.hadoop.hive.conf.Constants;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.DataConnector;
import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.Order;
import org.apache.hadoop.hive.metastore.api.SQLCheckConstraint;
import org.apache.hadoop.hive.metastore.api.SQLDefaultConstraint;
import org.apache.hadoop.hive.metastore.api.SQLForeignKey;
import org.apache.hadoop.hive.metastore.api.SQLNotNullConstraint;
import org.apache.hadoop.hive.metastore.api.SQLPrimaryKey;
import org.apache.hadoop.hive.metastore.api.SQLUniqueConstraint;
import org.apache.hadoop.hive.metastore.api.SourceTable;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.CompilationOpContext;
import org.apache.hadoop.hive.ql.Context;
import org.apache.hadoop.hive.ql.ErrorMsg;
import org.apache.hadoop.hive.ql.QueryProperties;
import org.apache.hadoop.hive.ql.QueryState;
import org.apache.hadoop.hive.ql.cache.results.CacheUsage;
import org.apache.hadoop.hive.ql.ddl.DDLDesc.DDLDescWithWriteId;
import org.apache.hadoop.hive.ql.ddl.table.constraint.ConstraintsUtils;
import org.apache.hadoop.hive.ql.exec.FetchTask;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.exec.TaskFactory;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.ql.hooks.LineageInfo;
import org.apache.hadoop.hive.ql.hooks.Entity;
import org.apache.hadoop.hive.ql.hooks.ReadEntity;
import org.apache.hadoop.hive.ql.hooks.WriteEntity;
import org.apache.hadoop.hive.ql.io.AcidUtils;
import org.apache.hadoop.hive.ql.io.IgnoreKeyTextOutputFormat;
import org.apache.hadoop.hive.ql.lib.Node;
import org.apache.hadoop.hive.ql.lockmgr.HiveTxnManager;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.metadata.HiveUtils;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.InvalidTableException;
import org.apache.hadoop.hive.ql.metadata.Partition;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.metadata.VirtualColumn;
import org.apache.hadoop.hive.ql.optimizer.listbucketingpruner.ListBucketingPrunerUtils;
import org.apache.hadoop.hive.ql.parse.type.ExprNodeTypeCheck;
import org.apache.hadoop.hive.ql.parse.type.TypeCheckCtx;
import org.apache.hadoop.hive.ql.plan.ExprNodeConstantDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
import org.apache.hadoop.hive.ql.plan.FetchWork;
import org.apache.hadoop.hive.ql.plan.FileSinkDesc;
import org.apache.hadoop.hive.ql.plan.ListBucketingCtx;
import org.apache.hadoop.hive.ql.plan.PlanUtils;
import org.apache.hadoop.hive.ql.plan.TableDesc;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hadoop.hive.ql.session.SessionState.LogHelper;
import org.apache.hadoop.hive.ql.util.DirectionUtils;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.hadoop.hive.serde2.io.DateWritableV2;
import org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters;
import org.apache.hadoop.hive.serde2.typeinfo.CharTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TimestampLocalTZTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
import org.apache.hadoop.hive.serde2.typeinfo.VarcharTypeInfo;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.security.alias.AbstractJavaKeyStoreProvider;
import org.apache.hadoop.security.alias.CredentialProvider;
import org.apache.hadoop.security.alias.CredentialProviderFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import static org.apache.hadoop.hive.conf.HiveConf.ConfVars.HIVE_LOAD_DATA_USE_NATIVE_API;
import static org.apache.hadoop.hive.ql.parse.PTFInvocationSpec.NullOrder.NULLS_FIRST;
import static org.apache.hadoop.hive.ql.parse.PTFInvocationSpec.NullOrder.NULLS_LAST;
import static org.apache.hadoop.hive.ql.parse.PTFInvocationSpec.Order.ASC;
import static org.apache.hadoop.hive.ql.parse.PTFInvocationSpec.Order.DESC;
/**
* BaseSemanticAnalyzer.
*
*/
public abstract class BaseSemanticAnalyzer {
protected static final Logger STATIC_LOG = LoggerFactory.getLogger(BaseSemanticAnalyzer.class.getName());
// Assumes one instance of this + single-threaded compilation for each query.
protected final Hive db;
protected final HiveConf conf;
protected final QueryState queryState;
protected List<Task<?>> rootTasks;
protected FetchTask fetchTask;
protected final Logger LOG;
protected final LogHelper console;
protected CompilationOpContext cContext;
protected Context ctx;
protected Map<String, String> idToTableNameMap;
protected QueryProperties queryProperties;
ParseContext pCtx = null;
//user defined functions in query
protected Set<String> userSuppliedFunctions;
/**
* A set of FileSinkOperators being written to in an ACID compliant way. We need to remember
* them here because when we build them we don't yet know the write id. We need to go
* back and set it once we actually start running the query.
* This also contains insert-only sinks.
*/
protected Set<FileSinkDesc> acidFileSinks = new HashSet<>();
// whether any ACID table or Insert-only (mm) table is involved in a query
// They both require DbTxnManager and both need to recordValidTxns when acquiring locks in Driver
protected boolean transactionalInQuery;
protected HiveTxnManager txnManager;
/**
* ReadEntities that are passed to the hooks.
*/
protected Set<ReadEntity> inputs;
/**
* List of WriteEntities that are passed to the hooks.
*/
protected Set<WriteEntity> outputs;
/**
* Lineage information for the query.
*/
protected LineageInfo linfo;
protected TableAccessInfo tableAccessInfo;
protected ColumnAccessInfo columnAccessInfo;
protected CacheUsage cacheUsage;
/**
* Columns accessed by updates
*/
protected ColumnAccessInfo updateColumnAccessInfo;
/**
* the value of set autocommit true|false
* It's an object to make sure it's {@code null} if the parsed statement is
* not 'set autocommit...'
*/
private Boolean autoCommitValue;
protected Boolean prepareQuery = false;
public Boolean getAutoCommitValue() {
return autoCommitValue;
}
public void setAutoCommitValue(Boolean autoCommit) {
autoCommitValue = autoCommit;
}
public boolean skipAuthorization() {
if (!HiveConf.getBoolVar(conf, HiveConf.ConfVars.HIVE_AUTHORIZATION_ENABLED)) {
return true;
}
SessionState ss = SessionState.get();
if (ss != null && ss.isHiveServerQuery()) {
String authUser = SessionState.getUserFromAuthenticator();
Set<String> servUsers = new HashSet<>(ss.getConf().getStringCollection(
HiveConf.ConfVars.HIVE_SERVER2_SERVICE_USERS.varname));
if (servUsers.contains(authUser)) {
console.logInfo("Skip authorization as the current user: " + authUser +
" is configured in " + HiveConf.ConfVars.HIVE_SERVER2_SERVICE_USERS.varname);
return true;
}
}
return false;
}
public String getCboInfo() {
return ctx.getCboInfo();
}
public boolean isPrepareQuery() {
return prepareQuery;
}
static final class RowFormatParams {
String fieldDelim = null;
String fieldEscape = null;
String collItemDelim = null;
String mapKeyDelim = null;
String lineDelim = null;
String nullFormat = null;
protected void analyzeRowFormat(ASTNode child) throws SemanticException {
child = (ASTNode) child.getChild(0);
int numChildRowFormat = child.getChildCount();
for (int numC = 0; numC < numChildRowFormat; numC++) {
ASTNode rowChild = (ASTNode) child.getChild(numC);
switch (rowChild.getToken().getType()) {
case HiveParser.TOK_TABLEROWFORMATFIELD:
fieldDelim = unescapeSQLString(rowChild.getChild(0)
.getText());
if (rowChild.getChildCount() >= 2) {
fieldEscape = unescapeSQLString(rowChild
.getChild(1).getText());
}
break;
case HiveParser.TOK_TABLEROWFORMATCOLLITEMS:
collItemDelim = unescapeSQLString(rowChild
.getChild(0).getText());
break;
case HiveParser.TOK_TABLEROWFORMATMAPKEYS:
mapKeyDelim = unescapeSQLString(rowChild.getChild(0)
.getText());
break;
case HiveParser.TOK_TABLEROWFORMATLINES:
lineDelim = unescapeSQLString(rowChild.getChild(0)
.getText());
if (!lineDelim.equals("\n")
&& !lineDelim.equals("10")) {
throw new SemanticException(SemanticAnalyzer.generateErrorMessage(rowChild,
ErrorMsg.LINES_TERMINATED_BY_NON_NEWLINE.getMsg()));
}
break;
case HiveParser.TOK_TABLEROWFORMATNULL:
nullFormat = unescapeSQLString(rowChild.getChild(0)
.getText());
break;
default:
throw new AssertionError("Unkown Token: " + rowChild);
}
}
}
}
public BaseSemanticAnalyzer(QueryState queryState) throws SemanticException {
this(queryState, createHiveDB(queryState.getConf()));
}
public BaseSemanticAnalyzer(QueryState queryState, Hive db) throws SemanticException {
try {
this.queryState = queryState;
this.conf = queryState.getConf();
this.db = db;
rootTasks = new ArrayList<>();
LOG = LoggerFactory.getLogger(this.getClass().getName());
console = new LogHelper(LOG);
idToTableNameMap = new HashMap<>();
inputs = new LinkedHashSet<>();
outputs = new LinkedHashSet<>();
txnManager = queryState.getTxnManager();
userSuppliedFunctions = new HashSet<>();
} catch (Exception e) {
throw new SemanticException(e);
}
}
protected static Hive createHiveDB(HiveConf conf) throws SemanticException {
try {
return Hive.get(conf);
} catch (HiveException e) {
throw new SemanticException(e);
}
}
public Map<String, String> getIdToTableNameMap() {
return idToTableNameMap;
}
public abstract void analyzeInternal(ASTNode ast) throws SemanticException;
public void init(boolean clearPartsCache) {
//no-op
}
public void initCtx(Context ctx) {
this.ctx = ctx;
}
public Context getCtx() {
return this.ctx;
}
public void analyze(ASTNode ast, Context ctx) throws SemanticException {
initCtx(ctx);
init(true);
analyzeInternal(ast);
}
public void validate() throws SemanticException {
// Implementations may choose to override this
}
public List<Task<?>> getRootTasks() {
return rootTasks;
}
/**
* @return the fetchTask
*/
public FetchTask getFetchTask() {
return fetchTask;
}
/**
* @param fetchTask
* the fetchTask to set
*/
public void setFetchTask(FetchTask fetchTask) {
this.fetchTask = fetchTask;
}
protected void reset(boolean clearPartsCache) {
rootTasks = new ArrayList<>();
}
public static String stripQuotes(String val) {
return PlanUtils.stripQuotes(val);
}
public static String charSetString(String charSetName, String charSetString)
throws SemanticException {
try {
// The character set name starts with a _, so strip that
charSetName = charSetName.substring(1);
if (charSetString.charAt(0) == '\'') {
return new String(unescapeSQLString(charSetString).getBytes(),
charSetName);
} else // hex input is also supported
{
assert charSetString.charAt(0) == '0';
assert charSetString.charAt(1) == 'x';
charSetString = charSetString.substring(2);
byte[] bArray = new byte[charSetString.length() / 2];
int j = 0;
for (int i = 0; i < charSetString.length(); i += 2) {
int val = Character.digit(charSetString.charAt(i), 16) * 16
+ Character.digit(charSetString.charAt(i + 1), 16);
if (val > 127) {
val = val - 256;
}
bArray[j++] = (byte)val;
}
return new String(bArray, charSetName);
}
} catch (UnsupportedEncodingException e) {
throw new SemanticException(e);
}
}
/**
* Get dequoted name from a table/column node.
* @param tableOrColumnNode the table or column node
* @return for table node, db.tab or tab. for column node column.
* @throws SemanticException
*/
public static String getUnescapedName(ASTNode tableOrColumnNode) throws SemanticException {
return getUnescapedName(tableOrColumnNode, null);
}
public static Map.Entry<String, String> getDbTableNamePair(ASTNode tableNameNode) throws SemanticException {
if (tableNameNode.getType() != HiveParser.TOK_TABNAME ||
(tableNameNode.getChildCount() != 1 && tableNameNode.getChildCount() != 2
&& tableNameNode.getChildCount() != 3)) {
throw new SemanticException(ASTErrorUtils.getMsg(ErrorMsg.INVALID_TABLE_NAME.getMsg(), tableNameNode));
}
if (tableNameNode.getChildCount() == 2 || tableNameNode.getChildCount() == 3) {
String dbName = unescapeIdentifier(tableNameNode.getChild(0).getText());
String tableName = unescapeIdentifier(tableNameNode.getChild(1).getText());
if (dbName.contains(".") || tableName.contains(".")) {
throw new SemanticException(ASTErrorUtils.getMsg(ErrorMsg.OBJECTNAME_CONTAINS_DOT.getMsg(), tableNameNode));
}
if (tableNameNode.getChildCount() == 3) {
String metaTable = unescapeIdentifier(tableNameNode.getChild(2).getText());
tableName = tableName + "." + metaTable;
}
return Pair.of(dbName, tableName);
} else {
String tableName = unescapeIdentifier(tableNameNode.getChild(0).getText());
if (tableName.contains(".")) {
throw new SemanticException(ASTErrorUtils.getMsg(ErrorMsg.OBJECTNAME_CONTAINS_DOT.getMsg(), tableNameNode));
}
return Pair.of(null,tableName);
}
}
public static String getUnescapedName(ASTNode tableOrColumnNode, String currentDatabase) throws SemanticException {
int tokenType = tableOrColumnNode.getToken().getType();
if (tokenType == HiveParser.TOK_TABNAME) {
// table node
Map.Entry<String,String> dbTablePair = getDbTableNamePair(tableOrColumnNode);
String tableName = dbTablePair.getValue();
String tableMetaRef = null;
if (tableName.contains(".")) {
String[] tmpNames = tableName.split("\\.");
tableName = tmpNames[0];
tableMetaRef = tmpNames[1];
}
return TableName.fromString(tableName,
null,
dbTablePair.getKey() == null ? currentDatabase : dbTablePair.getKey(),
tableMetaRef)
.getNotEmptyDbTable();
} else if (tokenType == HiveParser.StringLiteral) {
return unescapeSQLString(tableOrColumnNode.getText());
}
// column node
return unescapeIdentifier(tableOrColumnNode.getText());
}
/**
* Get the name reference of a DB table node.
* @param tabNameNode
* @return a {@link TableName}, not null. The catalog will be missing from this.
* @throws SemanticException
*/
public static TableName getQualifiedTableName(ASTNode tabNameNode) throws SemanticException {
// Ideally this would be removed, once the catalog is accessible in all use cases
return getQualifiedTableName(tabNameNode, null);
}
/**
* Get the name reference of a DB table node.
* @param tabNameNode
* @param catalogName the catalog of the DB/object
* @return a {@link TableName}, not null. The catalog will be missing from this.
* @throws SemanticException
*/
public static TableName getQualifiedTableName(ASTNode tabNameNode, String catalogName) throws SemanticException {
if (tabNameNode.getType() != HiveParser.TOK_TABNAME || (tabNameNode.getChildCount() != 1
&& tabNameNode.getChildCount() != 2 && tabNameNode.getChildCount() != 3)) {
throw new SemanticException(ASTErrorUtils.getMsg(
ErrorMsg.INVALID_TABLE_NAME.getMsg(), tabNameNode));
}
if (tabNameNode.getChildCount() == 3) {
final String dbName = unescapeIdentifier(tabNameNode.getChild(0).getText());
final String tableName = unescapeIdentifier(tabNameNode.getChild(1).getText());
final String tableMetaRef = unescapeIdentifier(tabNameNode.getChild(2).getText());
return HiveTableName.fromString(tableName, catalogName, dbName, tableMetaRef);
}
if (tabNameNode.getChildCount() == 2) {
final String dbName = unescapeIdentifier(tabNameNode.getChild(0).getText());
final String tableName = unescapeIdentifier(tabNameNode.getChild(1).getText());
if (dbName.contains(".") || tableName.contains(".")) {
throw new SemanticException(ASTErrorUtils.getMsg(
ErrorMsg.OBJECTNAME_CONTAINS_DOT.getMsg(), tabNameNode));
}
return HiveTableName.ofNullable(tableName, dbName);
}
final String tableName = unescapeIdentifier(tabNameNode.getChild(0).getText());
if (tableName.contains(".")) {
throw new SemanticException(ASTErrorUtils.getMsg(
ErrorMsg.OBJECTNAME_CONTAINS_DOT.getMsg(), tabNameNode));
}
return HiveTableName.ofNullable(tableName);
}
/**
* Get the unqualified name from a table node.
*
* This method works for table names qualified with their schema (e.g., "db.table")
* and table names without schema qualification. In both cases, it returns
* the table name without the schema.
*
* @param node the table node
* @return the table name without schema qualification
* (i.e., if name is "db.table" or "table", returns "table")
* @throws SemanticException
*/
public static String getUnescapedUnqualifiedTableName(ASTNode node) throws SemanticException {
assert node.getChildCount() <= 3;
assert node.getType() == HiveParser.TOK_TABNAME;
if (node.getChildCount() == 2 || node.getChildCount() == 3) {
node = (ASTNode) node.getChild(1);
}
String tableName = getUnescapedName(node);
if (node.getChildCount() == 3) {
tableName = tableName + "." + node.getChild(2);
}
return tableName;
}
public static String getTableAlias(ASTNode node) {
// ptf node form is: ^(TOK_PTBLFUNCTION $name $alias?
// partitionTableFunctionSource partitioningSpec? expression*)
// guranteed to have an alias here: check done in processJoin
if (node.getToken().getType() == HiveParser.TOK_PTBLFUNCTION) {
return unescapeIdentifier(node.getChild(1).getText().toLowerCase());
}
String alias = getSimpleTableNameBase(node);
return alias != null ? alias.toLowerCase() : null;
}
protected static String getSimpleTableNameBase(ASTNode n) {
switch (n.getType()) {
case HiveParser.TOK_TABREF:
int aliasIndex = findTabRefIdxs(n)[0];
if (aliasIndex != 0) {
return n.getChild(aliasIndex).getText(); //the alias
}
return getSimpleTableNameBase((ASTNode) n.getChild(0));
case HiveParser.TOK_TABNAME:
if (n.getChildCount() == 2) {
//db.table -> return table
return n.getChild(1).getText();
}
return n.getChild(0).getText();
case HiveParser.TOK_SUBQUERY:
return n.getChild(1).getText(); //the alias
default:
throw raiseWrongType("TOK_TABREF|TOK_TABNAME|TOK_SUBQUERY", n);
}
}
protected static IllegalArgumentException raiseWrongType(String expectedTokName, ASTNode n) {
return new IllegalArgumentException("Expected " + expectedTokName + "; got " + n.getType());
}
protected static int[] findTabRefIdxs(ASTNode tabref) {
assert tabref.getType() == HiveParser.TOK_TABREF;
int aliasIndex = 0;
int propsIndex = -1;
int tsampleIndex = -1;
int ssampleIndex = -1;
int asOfTimeIndex = -1;
int asOfVersionIndex = -1;
int asOfVersionFromIndex = -1;
for (int index = 1; index < tabref.getChildCount(); index++) {
ASTNode ct = (ASTNode) tabref.getChild(index);
if (ct.getToken().getType() == HiveParser.TOK_TABLEBUCKETSAMPLE) {
tsampleIndex = index;
} else if (ct.getToken().getType() == HiveParser.TOK_TABLESPLITSAMPLE) {
ssampleIndex = index;
} else if (ct.getToken().getType() == HiveParser.TOK_TABLEPROPERTIES) {
propsIndex = index;
} else if (ct.getToken().getType() == HiveParser.TOK_AS_OF_TIME) {
asOfTimeIndex = index;
} else if (ct.getToken().getType() == HiveParser.TOK_AS_OF_VERSION) {
asOfVersionIndex = index;
} else if (ct.getToken().getType() == HiveParser.TOK_FROM_VERSION) {
asOfVersionFromIndex = index;
} else {
aliasIndex = index;
}
}
return new int[] {
aliasIndex, propsIndex, tsampleIndex, ssampleIndex, asOfTimeIndex, asOfVersionIndex, asOfVersionFromIndex};
}
/**
* Remove the encapsulating "`" pair from the identifier. We allow users to
* use "`" to escape identifier for table names, column names and aliases, in
* case that coincide with Hive language keywords.
*/
public static String unescapeIdentifier(String val) {
if (val == null) {
return null;
}
if (val.charAt(0) == '`' && val.charAt(val.length() - 1) == '`') {
val = val.substring(1, val.length() - 1);
}
return val;
}
public static Map<String, String> getProps(ASTNode prop) {
// Must be deterministic order map for consistent q-test output across Java versions
Map<String, String> mapProp = new LinkedHashMap<>();
readProps(prop, mapProp);
return mapProp;
}
/**
* Converts parsed key/value properties pairs into a map.
*
* @param prop ASTNode parent of the key/value pairs
*
* @param mapProp property map which receives the mappings
*/
public static void readProps(
ASTNode prop, Map<String, String> mapProp) {
for (int propChild = 0; propChild < prop.getChildCount(); propChild++) {
String key = unescapeSQLString(prop.getChild(propChild).getChild(0)
.getText());
String value = null;
if (prop.getChild(propChild).getChild(1) != null) {
value = unescapeSQLString(prop.getChild(propChild).getChild(1).getText());
}
mapProp.put(key, value);
}
}
@SuppressWarnings("nls")
public static String unescapeSQLString(String b) {
Character enclosure = null;
// Some of the strings can be passed in as unicode. For example, the
// delimiter can be passed in as \002 - So, we first check if the
// string is a unicode number, else go back to the old behavior
StringBuilder sb = new StringBuilder(b.length());
for (int i = 0; i < b.length(); i++) {
char currentChar = b.charAt(i);
if (enclosure == null) {
if (currentChar == '\'' || b.charAt(i) == '\"') {
enclosure = currentChar;
}
// ignore all other chars outside the enclosure
continue;
}
if (enclosure.equals(currentChar)) {
enclosure = null;
continue;
}
if (currentChar == '\\' && (i + 6 < b.length()) && b.charAt(i + 1) == 'u') {
int code = 0;
int base = i + 2;
for (int j = 0; j < 4; j++) {
int digit = Character.digit(b.charAt(j + base), 16);
code = (code << 4) + digit;
}
sb.append((char)code);
i += 5;
continue;
}
if (currentChar == '\\' && (i + 4 < b.length())) {
char i1 = b.charAt(i + 1);
char i2 = b.charAt(i + 2);
char i3 = b.charAt(i + 3);
if ((i1 >= '0' && i1 <= '1') && (i2 >= '0' && i2 <= '7')
&& (i3 >= '0' && i3 <= '7')) {
byte bVal = (byte) ((i3 - '0') + ((i2 - '0') * 8) + ((i1 - '0') * 8 * 8));
byte[] bValArr = new byte[1];
bValArr[0] = bVal;
String tmp = new String(bValArr);
sb.append(tmp);
i += 3;
continue;
}
}
if (currentChar == '\\' && (i + 2 < b.length())) {
char n = b.charAt(i + 1);
switch (n) {
case '0':
sb.append("\0");
break;
case '\'':
sb.append("'");
break;
case '"':
sb.append("\"");
break;
case 'b':
sb.append("\b");
break;
case 'n':
sb.append("\n");
break;
case 'r':
sb.append("\r");
break;
case 't':
sb.append("\t");
break;
case 'Z':
sb.append("\u001A");
break;
case '\\':
sb.append("\\");
break;
// The following 2 lines are exactly what MySQL does TODO: why do we do this?
case '%':
sb.append("\\%");
break;
case '_':
sb.append("\\_");
break;
default:
sb.append(n);
}
i++;
} else {
sb.append(currentChar);
}
}
return sb.toString();
}
/**
* Escapes the string for AST; doesn't enclose it in quotes, however.
*/
public static String escapeSQLString(String b) {
// There's usually nothing to escape, so we will be optimistic.
String result = b;
for (int i = 0; i < result.length(); ++i) {
char currentChar = result.charAt(i);
if (currentChar == '\\' && ((i + 1) < result.length())) {
// TODO: do we need to handle the "this is what MySQL does" here?
char nextChar = result.charAt(i + 1);
if (nextChar == '%' || nextChar == '_') {
++i;
continue;
}
}
switch (currentChar) {
case '\0': result = spliceString(result, i, "\\0"); ++i; break;
case '\'': result = spliceString(result, i, "\\'"); ++i; break;
case '\"': result = spliceString(result, i, "\\\""); ++i; break;
case '\b': result = spliceString(result, i, "\\b"); ++i; break;
case '\n': result = spliceString(result, i, "\\n"); ++i; break;
case '\r': result = spliceString(result, i, "\\r"); ++i; break;
case '\t': result = spliceString(result, i, "\\t"); ++i; break;
case '\\': result = spliceString(result, i, "\\\\"); ++i; break;
case '\u001A': result = spliceString(result, i, "\\Z"); ++i; break;
default: {
if (currentChar < ' ') {
String hex = Integer.toHexString(currentChar);
String unicode = "\\u";
for (int j = 4; j > hex.length(); --j) {
unicode += '0';
}
unicode += hex;
result = spliceString(result, i, unicode);
i += (unicode.length() - 1);
}
break; // if not a control character, do nothing
}
}
}
return result;
}
private static String spliceString(String str, int i, String replacement) {
return spliceString(str, i, 1, replacement);
}
private static String spliceString(String str, int i, int length, String replacement) {
return str.substring(0, i) + replacement + str.substring(i + length);
}
public Set<ReadEntity> getInputs() {
return inputs;
}
public Set<WriteEntity> getOutputs() {
return outputs;
}
/**
* @return the schema for the fields which will be produced
* when the statement is executed, or null if not known
*/
public List<FieldSchema> getResultSchema() {
return null;
}
protected List<FieldSchema> getColumns(ASTNode ast) throws SemanticException {
return getColumns(ast, true, conf);
}
/**
* Get the list of FieldSchema out of the ASTNode.
*/
public static List<FieldSchema> getColumns(ASTNode ast, boolean lowerCase, Configuration conf)
throws SemanticException {
return getColumns(ast, lowerCase, null, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(),
new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), conf);
}
public static void checkColumnName(String columnName) throws SemanticException {
if (VirtualColumn.VIRTUAL_COLUMN_NAMES.contains(columnName.toUpperCase())) {
throw new SemanticException(ErrorMsg.INVALID_COLUMN_NAME.getMsg(columnName));
}
}
/**
* Get the list of FieldSchema out of the ASTNode.
* Additionally, populate the primaryKeys and foreignKeys if any.
*/
public static List<FieldSchema> getColumns(
ASTNode ast, boolean lowerCase, TokenRewriteStream tokenRewriteStream,
List<SQLPrimaryKey> primaryKeys, List<SQLForeignKey> foreignKeys,
List<SQLUniqueConstraint> uniqueConstraints, List<SQLNotNullConstraint> notNullConstraints,
List<SQLDefaultConstraint> defaultConstraints, List<SQLCheckConstraint> checkConstraints,
Configuration conf) throws SemanticException {
List<FieldSchema> colList = new ArrayList<>();
Tree parent = ast.getParent();
for (int i = 0; i < ast.getChildCount(); i++) {
FieldSchema col = new FieldSchema();
ASTNode child = (ASTNode) ast.getChild(i);
switch (child.getToken().getType()) {
case HiveParser.TOK_UNIQUE: {
final TableName tName =
getQualifiedTableName((ASTNode) parent.getChild(0), MetaStoreUtils.getDefaultCatalog(conf));
// TODO CAT - for now always use the default catalog. Eventually will want to see if
// the user specified a catalog
ConstraintsUtils.processUniqueConstraints(tName, child, uniqueConstraints);
}
break;
case HiveParser.TOK_PRIMARY_KEY: {
if (!primaryKeys.isEmpty()) {
throw new SemanticException(ErrorMsg.INVALID_CONSTRAINT
.getMsg("Cannot exist more than one primary key definition for the same table"));
}
final TableName tName = getQualifiedTableName((ASTNode) parent.getChild(0));
ConstraintsUtils.processPrimaryKeys(tName, child, primaryKeys);
}
break;
case HiveParser.TOK_FOREIGN_KEY: {
final TableName tName = getQualifiedTableName((ASTNode) parent.getChild(0));
ConstraintsUtils.processForeignKeys(tName, child, foreignKeys);
}
break;
case HiveParser.TOK_CHECK_CONSTRAINT: {
final TableName tName =
getQualifiedTableName((ASTNode) parent.getChild(0), MetaStoreUtils.getDefaultCatalog(conf));
// TODO CAT - for now always use the default catalog. Eventually will want to see if
// the user specified a catalog
ConstraintsUtils.processCheckConstraints(tName, child, null, checkConstraints, null, tokenRewriteStream);
}
break;
default:
Tree grandChild = child.getChild(0);
if (grandChild != null) {
String name = grandChild.getText();
if (lowerCase) {
name = name.toLowerCase();
}
checkColumnName(name);
// child 0 is the name of the column
col.setName(unescapeIdentifier(name));
// child 1 is the type of the column
ASTNode typeChild = (ASTNode) (child.getChild(1));
col.setType(getTypeStringFromAST(typeChild));
// child 2 is the optional comment of the column
// child 3 is the optional constraint
ASTNode constraintChild = null;
if (child.getChildCount() == 4) {
col.setComment(unescapeSQLString(child.getChild(2).getText()));
constraintChild = (ASTNode) child.getChild(3);
} else if (child.getChildCount() == 3
&& ((ASTNode) child.getChild(2)).getToken().getType() == HiveParser.StringLiteral) {
col.setComment(unescapeSQLString(child.getChild(2).getText()));
} else if (child.getChildCount() == 3) {
constraintChild = (ASTNode) child.getChild(2);
}
if (constraintChild != null) {
final TableName tName =
getQualifiedTableName((ASTNode) parent.getChild(0), MetaStoreUtils.getDefaultCatalog(conf));
// TODO CAT - for now always use the default catalog. Eventually will want to see if
// the user specified a catalog
// Process column constraint
switch (constraintChild.getToken().getType()) {
case HiveParser.TOK_CHECK_CONSTRAINT:
ConstraintsUtils.processCheckConstraints(tName, constraintChild, ImmutableList.of(col.getName()),
checkConstraints, typeChild, tokenRewriteStream);
break;
case HiveParser.TOK_DEFAULT_VALUE:
ConstraintsUtils.processDefaultConstraints(tName, constraintChild, ImmutableList.of(col.getName()),
defaultConstraints, typeChild, tokenRewriteStream);
break;
case HiveParser.TOK_NOT_NULL:
ConstraintsUtils.processNotNullConstraints(tName, constraintChild, ImmutableList.of(col.getName()),
notNullConstraints);
break;
case HiveParser.TOK_UNIQUE:
ConstraintsUtils.processUniqueConstraints(tName, constraintChild, ImmutableList.of(col.getName()),
uniqueConstraints);
break;
case HiveParser.TOK_PRIMARY_KEY:
if (!primaryKeys.isEmpty()) {
throw new SemanticException(ErrorMsg.INVALID_CONSTRAINT
.getMsg("Cannot exist more than one primary key definition for the same table"));
}
ConstraintsUtils.processPrimaryKeys(tName, constraintChild, ImmutableList.of(col.getName()), primaryKeys);
break;
case HiveParser.TOK_FOREIGN_KEY:
ConstraintsUtils.processForeignKeys(tName, constraintChild, foreignKeys);
break;
default:
throw new SemanticException(ErrorMsg.NOT_RECOGNIZED_CONSTRAINT.getMsg(
constraintChild.getToken().getText()));
}
}
}
colList.add(col);
break;
}
}
return colList;
}
public static List<String> getColumnNames(ASTNode ast) {
List<String> colList = new ArrayList<>();
int numCh = ast.getChildCount();
for (int i = 0; i < numCh; i++) {
ASTNode child = (ASTNode) ast.getChild(i);
colList.add(unescapeIdentifier(child.getText()).toLowerCase());
}
return colList;
}
protected List<Order> getColumnNamesOrder(ASTNode ast) throws SemanticException {
List<Order> colList = new ArrayList<>();
int numCh = ast.getChildCount();
for (int i = 0; i < numCh; i++) {
ASTNode child = (ASTNode) ast.getChild(i);
int directionCode = DirectionUtils.tokenToCode(child.getToken().getType());
child = (ASTNode) child.getChild(0);
if (child.getToken().getType() != HiveParser.TOK_NULLS_FIRST && directionCode == DirectionUtils.ASCENDING_CODE) {
throw new SemanticException(
"create/alter bucketed table: not supported NULLS LAST for SORTED BY in ASC order");
}
if (child.getToken().getType() != HiveParser.TOK_NULLS_LAST && directionCode == DirectionUtils.DESCENDING_CODE) {
throw new SemanticException(
"create/alter bucketed table: not supported NULLS FIRST for SORTED BY in DESC order");
}
colList.add(new Order(unescapeIdentifier(child.getChild(0).getText()).toLowerCase(), directionCode));
}
return colList;
}
public static String getTypeStringFromAST(ASTNode typeNode)
throws SemanticException {
switch (typeNode.getType()) {
case HiveParser.TOK_LIST:
return serdeConstants.LIST_TYPE_NAME + "<"
+ getTypeStringFromAST((ASTNode) typeNode.getChild(0)) + ">";
case HiveParser.TOK_MAP:
return serdeConstants.MAP_TYPE_NAME + "<"
+ getTypeStringFromAST((ASTNode) typeNode.getChild(0)) + ","
+ getTypeStringFromAST((ASTNode) typeNode.getChild(1)) + ">";
case HiveParser.TOK_STRUCT:
return getStructTypeStringFromAST(typeNode);
case HiveParser.TOK_UNIONTYPE:
return getUnionTypeStringFromAST(typeNode);
default:
return getTypeName(typeNode);
}
}