forked from apache/doris
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoad.java
More file actions
1596 lines (1444 loc) · 66.1 KB
/
Copy pathLoad.java
File metadata and controls
1596 lines (1444 loc) · 66.1 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
// 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.doris.load;
import org.apache.doris.alter.SchemaChangeHandler;
import org.apache.doris.analysis.Analyzer;
import org.apache.doris.analysis.BinaryPredicate;
import org.apache.doris.analysis.CastExpr;
import org.apache.doris.analysis.DataDescription;
import org.apache.doris.analysis.Expr;
import org.apache.doris.analysis.ExprSubstitutionMap;
import org.apache.doris.analysis.FunctionCallExpr;
import org.apache.doris.analysis.FunctionName;
import org.apache.doris.analysis.FunctionParams;
import org.apache.doris.analysis.ImportColumnDesc;
import org.apache.doris.analysis.IsNullPredicate;
import org.apache.doris.analysis.NullLiteral;
import org.apache.doris.analysis.SlotDescriptor;
import org.apache.doris.analysis.SlotRef;
import org.apache.doris.analysis.StringLiteral;
import org.apache.doris.analysis.TupleDescriptor;
import org.apache.doris.catalog.Column;
import org.apache.doris.catalog.Database;
import org.apache.doris.catalog.Env;
import org.apache.doris.catalog.MaterializedIndex;
import org.apache.doris.catalog.OlapTable;
import org.apache.doris.catalog.Partition;
import org.apache.doris.catalog.PrimitiveType;
import org.apache.doris.catalog.Replica;
import org.apache.doris.catalog.ScalarType;
import org.apache.doris.catalog.Table;
import org.apache.doris.catalog.TableIf.TableType;
import org.apache.doris.catalog.Tablet;
import org.apache.doris.catalog.TabletInvertedIndex;
import org.apache.doris.catalog.TabletMeta;
import org.apache.doris.catalog.Type;
import org.apache.doris.common.AnalysisException;
import org.apache.doris.common.CaseSensibility;
import org.apache.doris.common.Config;
import org.apache.doris.common.DdlException;
import org.apache.doris.common.FeConstants;
import org.apache.doris.common.LabelAlreadyUsedException;
import org.apache.doris.common.LoadException;
import org.apache.doris.common.MetaNotFoundException;
import org.apache.doris.common.Pair;
import org.apache.doris.common.PatternMatcher;
import org.apache.doris.common.PatternMatcherWrapper;
import org.apache.doris.common.UserException;
import org.apache.doris.common.util.ListComparator;
import org.apache.doris.common.util.TimeUtils;
import org.apache.doris.load.LoadJob.JobState;
import org.apache.doris.mysql.privilege.PrivPredicate;
import org.apache.doris.persist.ReplicaPersistInfo;
import org.apache.doris.qe.ConnectContext;
import org.apache.doris.task.LoadTaskInfo;
import org.apache.doris.thrift.TEtlState;
import org.apache.doris.thrift.TFileFormatType;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.gson.Gson;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Load {
private static final Logger LOG = LogManager.getLogger(Load.class);
public static final String VERSION = "v1";
// valid state change map
private static final Map<JobState, Set<JobState>> STATE_CHANGE_MAP = Maps.newHashMap();
// system dpp config
public static DppConfig dppDefaultConfig = null;
public static Map<String, DppConfig> clusterToDppConfig = Maps.newHashMap();
// load job meta
private Map<Long, LoadJob> idToLoadJob; // loadJobId to loadJob
private Map<Long, List<LoadJob>> dbToLoadJobs; // db to loadJob list
private Map<Long, Map<String, List<LoadJob>>> dbLabelToLoadJobs; // db label to loadJob list
private Map<Long, LoadJob> idToPendingLoadJob; // loadJobId to pending loadJob
private Map<Long, LoadJob> idToEtlLoadJob; // loadJobId to etl loadJob
private Map<Long, LoadJob> idToLoadingLoadJob; // loadJobId to loading loadJob
private Map<Long, LoadJob> idToQuorumFinishedLoadJob; // loadJobId to quorum finished loadJob
private Set<Long> loadingPartitionIds; // loading partition id set
// dbId -> set of (label, timestamp)
private Map<Long, Map<String, Long>> dbToMiniLabels; // db to mini uncommitted label
// lock for load job
// lock is private and must use after db lock
private ReentrantReadWriteLock lock;
static {
Set<JobState> pendingDestStates = Sets.newHashSet();
pendingDestStates.add(JobState.ETL);
pendingDestStates.add(JobState.CANCELLED);
STATE_CHANGE_MAP.put(JobState.PENDING, pendingDestStates);
Set<JobState> etlDestStates = Sets.newHashSet();
etlDestStates.add(JobState.LOADING);
etlDestStates.add(JobState.CANCELLED);
STATE_CHANGE_MAP.put(JobState.ETL, etlDestStates);
Set<JobState> loadingDestStates = Sets.newHashSet();
loadingDestStates.add(JobState.FINISHED);
loadingDestStates.add(JobState.QUORUM_FINISHED);
loadingDestStates.add(JobState.CANCELLED);
STATE_CHANGE_MAP.put(JobState.LOADING, loadingDestStates);
Set<JobState> quorumFinishedDestStates = Sets.newHashSet();
quorumFinishedDestStates.add(JobState.FINISHED);
STATE_CHANGE_MAP.put(JobState.QUORUM_FINISHED, quorumFinishedDestStates);
// system dpp config
Gson gson = new Gson();
try {
Map<String, String> defaultConfig =
(HashMap<String, String>) gson.fromJson(Config.dpp_default_config_str, HashMap.class);
dppDefaultConfig = DppConfig.create(defaultConfig);
Map<String, Map<String, String>> clusterToConfig =
(HashMap<String, Map<String, String>>) gson.fromJson(Config.dpp_config_str, HashMap.class);
for (Entry<String, Map<String, String>> entry : clusterToConfig.entrySet()) {
String cluster = entry.getKey();
DppConfig dppConfig = dppDefaultConfig.getCopiedDppConfig();
dppConfig.update(DppConfig.create(entry.getValue()));
dppConfig.check();
clusterToDppConfig.put(cluster, dppConfig);
}
if (!clusterToDppConfig.containsKey(Config.dpp_default_cluster)) {
throw new LoadException("Default cluster not exist");
}
} catch (Throwable e) {
LOG.error("dpp default config ill-formed", e);
System.exit(-1);
}
}
public Load() {
idToLoadJob = Maps.newHashMap();
dbToLoadJobs = Maps.newHashMap();
dbLabelToLoadJobs = Maps.newHashMap();
idToPendingLoadJob = Maps.newLinkedHashMap();
idToEtlLoadJob = Maps.newLinkedHashMap();
idToLoadingLoadJob = Maps.newLinkedHashMap();
idToQuorumFinishedLoadJob = Maps.newLinkedHashMap();
loadingPartitionIds = Sets.newHashSet();
dbToMiniLabels = Maps.newHashMap();
lock = new ReentrantReadWriteLock(true);
}
public void readLock() {
lock.readLock().lock();
}
public void readUnlock() {
lock.readLock().unlock();
}
private void writeLock() {
lock.writeLock().lock();
}
private void writeUnlock() {
lock.writeLock().unlock();
}
/**
* When doing schema change, there may have some 'shadow' columns, with prefix '__doris_shadow_' in
* their names. These columns are invisible to user, but we need to generate data for these columns.
* So we add column mappings for these column.
* eg1:
* base schema is (A, B, C), and B is under schema change, so there will be a shadow column: '__doris_shadow_B'
* So the final column mapping should looks like: (A, B, C, __doris_shadow_B = substitute(B));
*/
public static List<ImportColumnDesc> getSchemaChangeShadowColumnDesc(Table tbl, Map<String, Expr> columnExprMap) {
List<ImportColumnDesc> shadowColumnDescs = Lists.newArrayList();
for (Column column : tbl.getFullSchema()) {
if (!column.isNameWithPrefix(SchemaChangeHandler.SHADOW_NAME_PREFIX)) {
continue;
}
String originCol = column.getNameWithoutPrefix(SchemaChangeHandler.SHADOW_NAME_PREFIX);
if (columnExprMap.containsKey(originCol)) {
Expr mappingExpr = columnExprMap.get(originCol);
if (mappingExpr != null) {
/*
* eg:
* (A, C) SET (B = func(xx))
* ->
* (A, C) SET (B = func(xx), __doris_shadow_B = func(xx))
*/
ImportColumnDesc importColumnDesc = new ImportColumnDesc(column.getName(), mappingExpr);
shadowColumnDescs.add(importColumnDesc);
} else {
/*
* eg:
* (A, B, C)
* ->
* (A, B, C) SET (__doris_shadow_B = B)
*/
SlotRef slot = new SlotRef(null, originCol);
slot.setType(column.getType());
ImportColumnDesc importColumnDesc = new ImportColumnDesc(column.getName(), slot);
shadowColumnDescs.add(importColumnDesc);
}
} else {
/*
* There is a case that if user does not specify the related origin column, eg:
* COLUMNS (A, C), and B is not specified, but B is being modified
* so there is a shadow column '__doris_shadow_B'.
* We can not just add a mapping function "__doris_shadow_B = substitute(B)",
* because Doris can not find column B.
* In this case, __doris_shadow_B can use its default value, so no need to add it to column mapping
*/
// do nothing
}
}
return shadowColumnDescs;
}
/*
* used for spark load job
* not init slot desc and analyze exprs
*/
public static void initColumns(Table tbl, List<ImportColumnDesc> columnExprs,
Map<String, Pair<String, List<String>>> columnToHadoopFunction) throws UserException {
initColumns(tbl, columnExprs, columnToHadoopFunction, null, null, null, null, null, null, null, false, false);
}
/*
* This function should be used for broker load v2 and stream load.
* And it must be called in same db lock when planing.
*/
public static void initColumns(Table tbl, LoadTaskInfo.ImportColumnDescs columnDescs,
Map<String, Pair<String, List<String>>> columnToHadoopFunction, Map<String, Expr> exprsByName,
Analyzer analyzer, TupleDescriptor srcTupleDesc, Map<String, SlotDescriptor> slotDescByName,
List<Integer> srcSlotIds, TFileFormatType formatType, List<String> hiddenColumns, boolean isPartialUpdate)
throws UserException {
rewriteColumns(columnDescs);
initColumns(tbl, columnDescs.descs, columnToHadoopFunction, exprsByName, analyzer, srcTupleDesc, slotDescByName,
srcSlotIds, formatType, hiddenColumns, true, isPartialUpdate);
}
/*
* This function will do followings:
* 1. fill the column exprs if user does not specify any column or column mapping.
* 2. For not specified columns, check if they have default value or they are auto-increment columns.
* 3. Add any shadow columns if have.
* 4. validate hadoop functions
* 5. init slot descs and expr map for load plan
*/
private static void initColumns(Table tbl, List<ImportColumnDesc> columnExprs,
Map<String, Pair<String, List<String>>> columnToHadoopFunction, Map<String, Expr> exprsByName,
Analyzer analyzer, TupleDescriptor srcTupleDesc, Map<String, SlotDescriptor> slotDescByName,
List<Integer> srcSlotIds, TFileFormatType formatType, List<String> hiddenColumns,
boolean needInitSlotAndAnalyzeExprs, boolean isPartialUpdate) throws UserException {
// We make a copy of the columnExprs so that our subsequent changes
// to the columnExprs will not affect the original columnExprs.
// skip the mapping columns not exist in schema
// eg: the origin column list is:
// (k1, k2, tmpk3 = k1 + k2, k3 = tmpk3)
// after calling rewriteColumns(), it will become
// (k1, k2, tmpk3 = k1 + k2, k3 = k1 + k2)
// so "tmpk3 = k1 + k2" is not needed anymore, we can skip it.
List<ImportColumnDesc> copiedColumnExprs = new ArrayList<>();
for (ImportColumnDesc importColumnDesc : columnExprs) {
String mappingColumnName = importColumnDesc.getColumnName();
if (importColumnDesc.isColumn() || tbl.getColumn(mappingColumnName) != null) {
copiedColumnExprs.add(importColumnDesc);
}
}
// check whether the OlapTable has sequenceCol
boolean hasSequenceCol = false;
if (tbl instanceof OlapTable && ((OlapTable) tbl).hasSequenceCol()) {
hasSequenceCol = true;
}
// If user does not specify the file field names, generate it by using base schema of table.
// So that the following process can be unified
boolean specifyFileFieldNames = copiedColumnExprs.stream().anyMatch(p -> p.isColumn());
if (!specifyFileFieldNames) {
List<Column> columns = tbl.getBaseSchema(false);
for (Column column : columns) {
// columnExprs has sequence column, don't need to generate the sequence column
if (hasSequenceCol && column.isSequenceColumn()) {
continue;
}
ImportColumnDesc columnDesc = null;
if (formatType == TFileFormatType.FORMAT_JSON) {
columnDesc = new ImportColumnDesc(column.getName());
} else {
columnDesc = new ImportColumnDesc(column.getName().toLowerCase());
}
LOG.debug("add base column {} to stream load task", column.getName());
copiedColumnExprs.add(columnDesc);
}
if (hiddenColumns != null) {
for (String columnName : hiddenColumns) {
Column column = tbl.getColumn(columnName);
if (column != null && !column.isVisible()) {
ImportColumnDesc columnDesc = new ImportColumnDesc(column.getName());
LOG.debug("add hidden column {} to stream load task", column.getName());
copiedColumnExprs.add(columnDesc);
}
}
}
}
// generate a map for checking easily
Map<String, Expr> columnExprMap = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
for (ImportColumnDesc importColumnDesc : copiedColumnExprs) {
columnExprMap.put(importColumnDesc.getColumnName(), importColumnDesc.getExpr());
}
HashMap<String, Type> colToType = new HashMap<>();
// check default value and auto-increment column
for (Column column : tbl.getBaseSchema()) {
String columnName = column.getName();
colToType.put(columnName, column.getType());
if (columnExprMap.containsKey(columnName)) {
continue;
}
if (column.getDefaultValue() != null) {
exprsByName.put(column.getName(), column.getDefaultValueExpr());
continue;
}
if (column.isAllowNull()) {
exprsByName.put(column.getName(), NullLiteral.create(column.getType()));
continue;
}
if (isPartialUpdate) {
continue;
}
if (column.isAutoInc()) {
continue;
}
throw new DdlException("Column has no default value. column: " + columnName);
}
// get shadow column desc when table schema change
copiedColumnExprs.addAll(getSchemaChangeShadowColumnDesc(tbl, columnExprMap));
// validate hadoop functions
if (columnToHadoopFunction != null) {
Map<String, String> columnNameMap = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
for (ImportColumnDesc importColumnDesc : copiedColumnExprs) {
if (importColumnDesc.isColumn()) {
columnNameMap.put(importColumnDesc.getColumnName(), importColumnDesc.getColumnName());
}
}
for (Entry<String, Pair<String, List<String>>> entry : columnToHadoopFunction.entrySet()) {
String mappingColumnName = entry.getKey();
Column mappingColumn = tbl.getColumn(mappingColumnName);
if (mappingColumn == null) {
throw new DdlException("Mapping column is not in table. column: " + mappingColumnName);
}
Pair<String, List<String>> function = entry.getValue();
try {
DataDescription.validateMappingFunction(function.first, function.second, columnNameMap,
mappingColumn, false);
} catch (AnalysisException e) {
throw new DdlException(e.getMessage());
}
}
}
if (!needInitSlotAndAnalyzeExprs) {
return;
}
Set<String> exprSrcSlotName = Sets.newTreeSet(String.CASE_INSENSITIVE_ORDER);
for (ImportColumnDesc importColumnDesc : copiedColumnExprs) {
if (importColumnDesc.isColumn()) {
continue;
}
List<SlotRef> slots = Lists.newArrayList();
importColumnDesc.getExpr().collect(SlotRef.class, slots);
for (SlotRef slot : slots) {
String slotColumnName = slot.getColumnName();
exprSrcSlotName.add(slotColumnName);
}
}
// init slot desc add expr map, also transform hadoop functions
for (ImportColumnDesc importColumnDesc : copiedColumnExprs) {
// make column name case match with real column name
String columnName = importColumnDesc.getColumnName();
Column tblColumn = tbl.getColumn(columnName);
String realColName;
if (tblColumn == null || tblColumn.getName() == null || importColumnDesc.getExpr() == null) {
realColName = columnName;
} else {
realColName = tblColumn.getName();
}
if (importColumnDesc.getExpr() != null) {
Expr expr = transformHadoopFunctionExpr(tbl, realColName, importColumnDesc.getExpr());
exprsByName.put(realColName, expr);
} else {
SlotDescriptor slotDesc = analyzer.getDescTbl().addSlotDescriptor(srcTupleDesc);
if (formatType == TFileFormatType.FORMAT_ARROW) {
slotDesc.setColumn(new Column(realColName, colToType.get(realColName)));
} else {
// columns default be varchar type
slotDesc.setType(ScalarType.createType(PrimitiveType.VARCHAR));
slotDesc.setColumn(new Column(realColName, PrimitiveType.VARCHAR));
}
// ISSUE A: src slot should be nullable even if the column is not nullable.
// because src slot is what we read from file, not represent to real column value.
// If column is not nullable, error will be thrown when filling the dest slot,
// which is not nullable.
slotDesc.setIsNullable(true);
slotDesc.setIsMaterialized(true);
srcSlotIds.add(slotDesc.getId().asInt());
slotDescByName.put(realColName, slotDesc);
}
}
LOG.debug("plan srcTupleDesc {}", srcTupleDesc.toString());
/*
* The extension column of the materialized view is added to the expression evaluation of load
* To avoid nested expressions. eg : column(a, tmp_c, c = expr(tmp_c)) ,
* __doris_materialized_view_bitmap_union_c need be analyzed after exprsByName
* So the columns of the materialized view are stored separately here
*/
Map<String, Expr> mvDefineExpr = Maps.newHashMap();
for (Column column : tbl.getFullSchema()) {
if (column.getDefineExpr() != null) {
if (column.getDefineExpr().getType().isInvalid()) {
column.getDefineExpr().setType(column.getType());
}
mvDefineExpr.put(column.getName(), column.getDefineExpr());
}
}
LOG.debug("slotDescByName: {}, exprsByName: {}, mvDefineExpr: {}", slotDescByName, exprsByName, mvDefineExpr);
// in vectorized load, reanalyze exprs with castExpr type
// otherwise analyze exprs with varchar type
analyzeAllExprs(tbl, analyzer, exprsByName, mvDefineExpr, slotDescByName);
LOG.debug("after init column, exprMap: {}", exprsByName);
}
private static SlotRef getSlotFromDesc(SlotDescriptor slotDesc) {
SlotRef slot = new SlotRef(slotDesc);
slot.setType(slotDesc.getType());
return slot;
}
public static Expr getExprFromDesc(Analyzer analyzer, Expr rhs, SlotRef slot) throws AnalysisException {
Type rhsType = rhs.getType();
rhs = rhs.castTo(slot.getType());
if (slot.getDesc() == null) {
// shadow column
return rhs;
}
if (rhs.isNullable() && !slot.isNullable()) {
rhs = new FunctionCallExpr("non_nullable", Lists.newArrayList(rhs));
rhs.setType(rhsType);
rhs.analyze(analyzer);
} else if (!rhs.isNullable() && slot.isNullable()) {
rhs = new FunctionCallExpr("nullable", Lists.newArrayList(rhs));
rhs.setType(rhsType);
rhs.analyze(analyzer);
}
return rhs;
}
private static void analyzeAllExprs(Table tbl, Analyzer analyzer, Map<String, Expr> exprsByName,
Map<String, Expr> mvDefineExpr, Map<String, SlotDescriptor> slotDescByName) throws UserException {
// analyze all exprs
for (Map.Entry<String, Expr> entry : exprsByName.entrySet()) {
ExprSubstitutionMap smap = new ExprSubstitutionMap();
List<SlotRef> slots = Lists.newArrayList();
entry.getValue().collect(SlotRef.class, slots);
for (SlotRef slot : slots) {
SlotDescriptor slotDesc = slotDescByName.get(slot.getColumnName());
if (slotDesc == null) {
if (entry.getKey() != null) {
if (entry.getKey().equalsIgnoreCase(Column.DELETE_SIGN)) {
throw new UserException("unknown reference column in DELETE ON clause:"
+ slot.getColumnName());
} else if (entry.getKey().equalsIgnoreCase(Column.SEQUENCE_COL)) {
throw new UserException("unknown reference column in ORDER BY clause:"
+ slot.getColumnName());
}
}
throw new UserException("unknown reference column, column=" + entry.getKey()
+ ", reference=" + slot.getColumnName());
}
smap.getLhs().add(slot);
smap.getRhs().add(new SlotRef(slotDesc));
}
Expr expr = entry.getValue().clone(smap);
expr.analyze(analyzer);
// check if contain aggregation
List<FunctionCallExpr> funcs = Lists.newArrayList();
expr.collect(FunctionCallExpr.class, funcs);
for (FunctionCallExpr fn : funcs) {
if (fn.isAggregateFunction()) {
throw new AnalysisException("Don't support aggregation function in load expression");
}
}
// Array type do not support cast now
Type exprReturnType = expr.getType();
if (exprReturnType.isArrayType()) {
Type schemaType = tbl.getColumn(entry.getKey()).getType();
if (exprReturnType != schemaType) {
throw new AnalysisException("Don't support load from type:" + exprReturnType + " to type:"
+ schemaType + " for column:" + entry.getKey());
}
}
exprsByName.put(entry.getKey(), expr);
}
for (Map.Entry<String, Expr> entry : mvDefineExpr.entrySet()) {
ExprSubstitutionMap smap = new ExprSubstitutionMap();
List<SlotRef> slots = Lists.newArrayList();
entry.getValue().collect(SlotRef.class, slots);
for (SlotRef slot : slots) {
if (slotDescByName.get(slot.getColumnName()) != null) {
smap.getLhs().add(slot);
smap.getRhs().add(
getExprFromDesc(analyzer, getSlotFromDesc(slotDescByName.get(slot.getColumnName())), slot));
} else if (exprsByName.get(slot.getColumnName()) != null) {
smap.getLhs().add(slot);
smap.getRhs().add(new CastExpr(tbl.getColumn(slot.getColumnName()).getType(),
exprsByName.get(slot.getColumnName())));
} else {
if (entry.getKey().equalsIgnoreCase(Column.DELETE_SIGN)) {
throw new UserException("unknown reference column in DELETE ON clause:" + slot.getColumnName());
} else if (entry.getKey().equalsIgnoreCase(Column.SEQUENCE_COL)) {
throw new UserException("unknown reference column in ORDER BY clause:" + slot.getColumnName());
} else {
throw new UserException("unknown reference column, column=" + entry.getKey()
+ ", reference=" + slot.getColumnName());
}
}
}
Expr expr = entry.getValue().clone(smap);
expr.analyze(analyzer);
exprsByName.put(entry.getKey(), expr);
}
}
public static void rewriteColumns(LoadTaskInfo.ImportColumnDescs columnDescs) {
if (columnDescs.isColumnDescsRewrited) {
return;
}
Map<String, Expr> derivativeColumns = new HashMap<>();
// find and rewrite the derivative columns
// e.g. (v1,v2=v1+1,v3=v2+1) --> (v1, v2=v1+1, v3=v1+1+1)
// 1. find the derivative columns
for (ImportColumnDesc importColumnDesc : columnDescs.descs) {
if (!importColumnDesc.isColumn()) {
if (importColumnDesc.getExpr() instanceof SlotRef) {
String columnName = ((SlotRef) importColumnDesc.getExpr()).getColumnName();
if (derivativeColumns.containsKey(columnName)) {
importColumnDesc.setExpr(derivativeColumns.get(columnName));
}
} else {
recursiveRewrite(importColumnDesc.getExpr(), derivativeColumns);
}
derivativeColumns.put(importColumnDesc.getColumnName(), importColumnDesc.getExpr());
}
}
columnDescs.isColumnDescsRewrited = true;
}
private static void recursiveRewrite(Expr expr, Map<String, Expr> derivativeColumns) {
if (CollectionUtils.isEmpty(expr.getChildren())) {
return;
}
for (int i = 0; i < expr.getChildren().size(); i++) {
Expr e = expr.getChild(i);
if (e instanceof SlotRef) {
String columnName = ((SlotRef) e).getColumnName();
if (derivativeColumns.containsKey(columnName)) {
expr.setChild(i, derivativeColumns.get(columnName));
}
} else {
recursiveRewrite(e, derivativeColumns);
}
}
}
/**
* This method is used to transform hadoop function.
* The hadoop function includes: replace_value, strftime, time_format, alignment_timestamp, default_value, now.
* It rewrites those function with real function name and param.
* For the other function, the expr only go through this function and the origin expr is returned.
*
* @param columnName
* @param originExpr
* @return
* @throws UserException
*/
private static Expr transformHadoopFunctionExpr(Table tbl, String columnName, Expr originExpr)
throws UserException {
Column column = tbl.getColumn(columnName);
if (column == null) {
// the unknown column will be checked later.
return originExpr;
}
// To compatible with older load version
if (originExpr instanceof FunctionCallExpr) {
FunctionCallExpr funcExpr = (FunctionCallExpr) originExpr;
String funcName = funcExpr.getFnName().getFunction();
if (funcName.equalsIgnoreCase("replace_value")) {
List<Expr> exprs = Lists.newArrayList();
SlotRef slotRef = new SlotRef(null, columnName);
// We will convert this to IF(`col` != child0, `col`, child1),
// because we need the if return type equal to `col`, we use NE
/*
* We will convert this based on different cases:
* case 1: k1 = replace_value(null, anyval);
* to: k1 = if (k1 is not null, k1, anyval);
*
* case 2: k1 = replace_value(anyval1, anyval2);
* to: k1 = if (k1 is not null, if(k1 != anyval1, k1, anyval2), null);
*/
if (funcExpr.getChild(0) instanceof NullLiteral) {
// case 1
exprs.add(new IsNullPredicate(slotRef, true));
exprs.add(slotRef);
if (funcExpr.hasChild(1)) {
exprs.add(funcExpr.getChild(1));
} else {
if (column.getDefaultValue() != null) {
if (column.getDefaultValueExprDef() != null) {
exprs.add(column.getDefaultValueExpr());
} else {
exprs.add(new StringLiteral(column.getDefaultValue()));
}
} else {
if (column.isAllowNull()) {
exprs.add(NullLiteral.create(Type.VARCHAR));
} else {
throw new UserException("Column(" + columnName + ") has no default value.");
}
}
}
} else {
// case 2
exprs.add(new IsNullPredicate(slotRef, true));
List<Expr> innerIfExprs = Lists.newArrayList();
innerIfExprs.add(new BinaryPredicate(BinaryPredicate.Operator.NE, slotRef, funcExpr.getChild(0)));
innerIfExprs.add(slotRef);
if (funcExpr.hasChild(1)) {
innerIfExprs.add(funcExpr.getChild(1));
} else {
if (column.getDefaultValue() != null) {
if (column.getDefaultValueExprDef() != null) {
innerIfExprs.add(column.getDefaultValueExpr());
} else {
innerIfExprs.add(new StringLiteral(column.getDefaultValue()));
}
} else {
if (column.isAllowNull()) {
innerIfExprs.add(NullLiteral.create(Type.VARCHAR));
} else {
throw new UserException("Column(" + columnName + ") has no default value.");
}
}
}
FunctionCallExpr innerIfFn = new FunctionCallExpr("if", innerIfExprs);
exprs.add(innerIfFn);
exprs.add(NullLiteral.create(Type.VARCHAR));
}
LOG.debug("replace_value expr: {}", exprs);
FunctionCallExpr newFn = new FunctionCallExpr("if", exprs);
return newFn;
} else if (funcName.equalsIgnoreCase("strftime")) {
// FROM_UNIXTIME(val)
FunctionName fromUnixName = new FunctionName("FROM_UNIXTIME");
List<Expr> fromUnixArgs = Lists.newArrayList(funcExpr.getChild(1));
FunctionCallExpr fromUnixFunc = new FunctionCallExpr(
fromUnixName, new FunctionParams(false, fromUnixArgs));
return fromUnixFunc;
} else if (funcName.equalsIgnoreCase("time_format")) {
// DATE_FORMAT(STR_TO_DATE(dt_str, dt_fmt))
FunctionName strToDateName = new FunctionName("STR_TO_DATE");
List<Expr> strToDateExprs = Lists.newArrayList(funcExpr.getChild(2), funcExpr.getChild(1));
FunctionCallExpr strToDateFuncExpr = new FunctionCallExpr(
strToDateName, new FunctionParams(false, strToDateExprs));
FunctionName dateFormatName = new FunctionName("DATE_FORMAT");
List<Expr> dateFormatArgs = Lists.newArrayList(strToDateFuncExpr, funcExpr.getChild(0));
FunctionCallExpr dateFormatFunc = new FunctionCallExpr(
dateFormatName, new FunctionParams(false, dateFormatArgs));
return dateFormatFunc;
} else if (funcName.equalsIgnoreCase("alignment_timestamp")) {
/*
* change to:
* UNIX_TIMESTAMP(DATE_FORMAT(FROM_UNIXTIME(ts), "%Y-01-01 00:00:00"));
*
*/
// FROM_UNIXTIME
FunctionName fromUnixName = new FunctionName("FROM_UNIXTIME");
List<Expr> fromUnixArgs = Lists.newArrayList(funcExpr.getChild(1));
FunctionCallExpr fromUnixFunc = new FunctionCallExpr(
fromUnixName, new FunctionParams(false, fromUnixArgs));
// DATE_FORMAT
StringLiteral precision = (StringLiteral) funcExpr.getChild(0);
StringLiteral format;
if (precision.getStringValue().equalsIgnoreCase("year")) {
format = new StringLiteral("%Y-01-01 00:00:00");
} else if (precision.getStringValue().equalsIgnoreCase("month")) {
format = new StringLiteral("%Y-%m-01 00:00:00");
} else if (precision.getStringValue().equalsIgnoreCase("day")) {
format = new StringLiteral("%Y-%m-%d 00:00:00");
} else if (precision.getStringValue().equalsIgnoreCase("hour")) {
format = new StringLiteral("%Y-%m-%d %H:00:00");
} else {
throw new UserException("Unknown precision(" + precision.getStringValue() + ")");
}
FunctionName dateFormatName = new FunctionName("DATE_FORMAT");
List<Expr> dateFormatArgs = Lists.newArrayList(fromUnixFunc, format);
FunctionCallExpr dateFormatFunc = new FunctionCallExpr(
dateFormatName, new FunctionParams(false, dateFormatArgs));
// UNIX_TIMESTAMP
FunctionName unixTimeName = new FunctionName("UNIX_TIMESTAMP");
List<Expr> unixTimeArgs = Lists.newArrayList();
unixTimeArgs.add(dateFormatFunc);
FunctionCallExpr unixTimeFunc = new FunctionCallExpr(
unixTimeName, new FunctionParams(false, unixTimeArgs));
return unixTimeFunc;
} else if (funcName.equalsIgnoreCase("default_value")) {
return funcExpr.getChild(0);
} else if (funcName.equalsIgnoreCase("now")) {
FunctionName nowFunctionName = new FunctionName("NOW");
FunctionCallExpr newFunc = new FunctionCallExpr(nowFunctionName, new FunctionParams(null));
return newFunc;
} else if (funcName.equalsIgnoreCase("substitute")) {
return funcExpr.getChild(0);
}
}
return originExpr;
}
// return true if we truly register a mini load label
// return false otherwise (eg: a retry request)
public boolean registerMiniLabel(String fullDbName, String label, long timestamp) throws DdlException {
Database db = Env.getCurrentInternalCatalog().getDbOrDdlException(fullDbName);
long dbId = db.getId();
writeLock();
try {
if (unprotectIsLabelUsed(dbId, label, timestamp, true)) {
// label is used and this is a retry request.
// no need to do further operation, just return.
return false;
}
Map<String, Long> miniLabels = null;
if (dbToMiniLabels.containsKey(dbId)) {
miniLabels = dbToMiniLabels.get(dbId);
} else {
miniLabels = Maps.newHashMap();
dbToMiniLabels.put(dbId, miniLabels);
}
miniLabels.put(label, timestamp);
return true;
} finally {
writeUnlock();
}
}
public void deregisterMiniLabel(String fullDbName, String label) throws DdlException {
Database db = Env.getCurrentInternalCatalog().getDbOrDdlException(fullDbName);
long dbId = db.getId();
writeLock();
try {
if (!dbToMiniLabels.containsKey(dbId)) {
return;
}
Map<String, Long> miniLabels = dbToMiniLabels.get(dbId);
miniLabels.remove(label);
if (miniLabels.isEmpty()) {
dbToMiniLabels.remove(dbId);
}
} finally {
writeUnlock();
}
}
public boolean isUncommittedLabel(long dbId, String label) throws DdlException {
readLock();
try {
if (dbToMiniLabels.containsKey(dbId)) {
Map<String, Long> uncommittedLabels = dbToMiniLabels.get(dbId);
return uncommittedLabels.containsKey(label);
}
} finally {
readUnlock();
}
return false;
}
public boolean isLabelUsed(long dbId, String label) throws DdlException {
readLock();
try {
return unprotectIsLabelUsed(dbId, label, -1, true);
} finally {
readUnlock();
}
}
/*
* 1. if label is already used, and this is not a retry request,
* throw exception ("Label already used")
* 2. if label is already used, but this is a retry request,
* return true
* 3. if label is not used, return false
* 4. throw exception if encounter error.
*/
private boolean unprotectIsLabelUsed(long dbId, String label, long timestamp, boolean checkMini)
throws DdlException {
// check dbLabelToLoadJobs
if (dbLabelToLoadJobs.containsKey(dbId)) {
Map<String, List<LoadJob>> labelToLoadJobs = dbLabelToLoadJobs.get(dbId);
if (labelToLoadJobs.containsKey(label)) {
List<LoadJob> labelLoadJobs = labelToLoadJobs.get(label);
for (LoadJob oldJob : labelLoadJobs) {
JobState oldJobState = oldJob.getState();
if (oldJobState != JobState.CANCELLED) {
if (timestamp == -1) {
// timestamp == -1 is for compatibility
throw new LabelAlreadyUsedException(label);
} else {
if (timestamp == oldJob.getTimestamp()) {
// this timestamp is used to verify if this label check is a retry request from backend.
// if the timestamp in request is same as timestamp in existing load job,
// which means this load job is already submitted
LOG.info("get a retry request with label: {}, timestamp: {}. return ok",
label, timestamp);
return true;
} else {
throw new LabelAlreadyUsedException(label);
}
}
}
}
}
}
// check dbToMiniLabel
if (checkMini) {
return checkMultiLabelUsed(dbId, label, timestamp);
}
return false;
}
private boolean checkMultiLabelUsed(long dbId, String label, long timestamp) throws DdlException {
if (dbToMiniLabels.containsKey(dbId)) {
Map<String, Long> uncommittedLabels = dbToMiniLabels.get(dbId);
if (uncommittedLabels.containsKey(label)) {
if (timestamp == -1) {
throw new LabelAlreadyUsedException(label);
} else {
if (timestamp == uncommittedLabels.get(label)) {
// this timestamp is used to verify if this label check is a retry request from backend.
// if the timestamp in request is same as timestamp in existing load job,
// which means this load job is already submitted
LOG.info("get a retry mini load request with label: {}, timestamp: {}. return ok",
label, timestamp);
return true;
} else {
throw new LabelAlreadyUsedException(label);
}
}
}
}
return false;
}
public Map<Long, LoadJob> getIdToLoadJob() {
return idToLoadJob;
}
public Map<Long, List<LoadJob>> getDbToLoadJobs() {
return dbToLoadJobs;
}
public List<LoadJob> getLoadJobs(JobState jobState) {
List<LoadJob> jobs = new ArrayList<LoadJob>();
Collection<LoadJob> stateJobs = null;
readLock();
try {
switch (jobState) {
case PENDING:
stateJobs = idToPendingLoadJob.values();
break;
case ETL:
stateJobs = idToEtlLoadJob.values();
break;
case LOADING:
stateJobs = idToLoadingLoadJob.values();
break;
case QUORUM_FINISHED:
stateJobs = idToQuorumFinishedLoadJob.values();
break;
default:
break;
}
if (stateJobs != null) {
jobs.addAll(stateJobs);
}
} finally {
readUnlock();
}
return jobs;
}
public long getLoadJobNum(JobState jobState, long dbId) {
readLock();
try {
List<LoadJob> loadJobs = this.dbToLoadJobs.get(dbId);
if (loadJobs == null) {
return 0;
}
int jobNum = 0;
for (LoadJob job : loadJobs) {
if (job.getState() == jobState) {
++jobNum;
}
}
return jobNum;
} finally {
readUnlock();
}
}
public long getLoadJobNum(JobState jobState) {
readLock();
try {
List<LoadJob> loadJobs = new ArrayList<>();
for (Long dbId : dbToLoadJobs.keySet()) {
if (!Env.getCurrentEnv().getAccessManager().checkDbPriv(ConnectContext.get(),
Env.getCurrentEnv().getCatalogMgr().getDbNullable(dbId).getFullName(),
PrivPredicate.LOAD)) {
continue;
}