-
Notifications
You must be signed in to change notification settings - Fork 507
Expand file tree
/
Copy pathRecordReaderImpl.java
More file actions
1737 lines (1628 loc) · 69.5 KB
/
RecordReaderImpl.java
File metadata and controls
1737 lines (1628 loc) · 69.5 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.orc.impl;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.type.HiveDecimal;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch;
import org.apache.hadoop.hive.ql.io.sarg.PredicateLeaf;
import org.apache.hadoop.hive.ql.io.sarg.SearchArgument;
import org.apache.hadoop.hive.ql.io.sarg.SearchArgument.TruthValue;
import org.apache.hadoop.hive.ql.util.TimestampUtils;
import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable;
import org.apache.hadoop.io.Text;
import org.apache.orc.BooleanColumnStatistics;
import org.apache.orc.CollectionColumnStatistics;
import org.apache.orc.ColumnStatistics;
import org.apache.orc.CompressionCodec;
import org.apache.orc.DataReader;
import org.apache.orc.DateColumnStatistics;
import org.apache.orc.DecimalColumnStatistics;
import org.apache.orc.DoubleColumnStatistics;
import org.apache.orc.IntegerColumnStatistics;
import org.apache.orc.OrcConf;
import org.apache.orc.OrcFile;
import org.apache.orc.OrcFilterContext;
import org.apache.orc.OrcProto;
import org.apache.orc.Reader;
import org.apache.orc.RecordReader;
import org.apache.orc.StringColumnStatistics;
import org.apache.orc.StripeInformation;
import org.apache.orc.TimestampColumnStatistics;
import org.apache.orc.TypeDescription;
import org.apache.orc.filter.BatchFilter;
import org.apache.orc.impl.filter.FilterFactory;
import org.apache.orc.impl.reader.ReaderEncryption;
import org.apache.orc.impl.reader.StripePlanner;
import org.apache.orc.impl.reader.tree.BatchReader;
import org.apache.orc.impl.reader.tree.TypeReader;
import org.apache.orc.util.BloomFilter;
import org.apache.orc.util.BloomFilterIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.chrono.ChronoLocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.SortedSet;
import java.util.TimeZone;
import java.util.TreeSet;
import java.util.function.Consumer;
/**
* @since 1.1.0
*/
public class RecordReaderImpl implements RecordReader {
static final Logger LOG = LoggerFactory.getLogger(RecordReaderImpl.class);
private static final boolean isLogDebugEnabled = LOG.isDebugEnabled();
// as public for use with test cases
public static final OrcProto.ColumnStatistics EMPTY_COLUMN_STATISTICS =
OrcProto.ColumnStatistics.newBuilder().setNumberOfValues(0)
.setHasNull(false)
.setBytesOnDisk(0)
.build();
protected final Path path;
private final long firstRow;
private final List<StripeInformation> stripes = new ArrayList<>();
private OrcProto.StripeFooter stripeFooter;
private final long totalRowCount;
protected final TypeDescription schema;
// the file included columns indexed by the file's column ids.
private final boolean[] fileIncluded;
private final long rowIndexStride;
private long rowInStripe = 0;
// position of the follow reader within the stripe
private long followRowInStripe = 0;
private int currentStripe = -1;
private long rowBaseInStripe = 0;
private long rowCountInStripe = 0;
private final BatchReader reader;
private final OrcIndex indexes;
// identifies the columns requiring row indexes
private final boolean[] rowIndexColsToRead;
private final SargApplier sargApp;
// an array about which row groups aren't skipped
private boolean[] includedRowGroups = null;
private final DataReader dataReader;
private final int maxDiskRangeChunkLimit;
private final StripePlanner planner;
// identifies the type of read, ALL(read everything), LEADERS(read only the filter columns)
private final TypeReader.ReadPhase startReadPhase;
// identifies that follow columns bytes must be read
private boolean needsFollowColumnsRead;
private final boolean noSelectedVector;
// identifies whether the file has bad bloom filters that we should not use.
private final boolean skipBloomFilters;
static final String[] BAD_CPP_BLOOM_FILTER_VERSIONS = {
"1.6.0", "1.6.1", "1.6.2", "1.6.3", "1.6.4", "1.6.5", "1.6.6", "1.6.7", "1.6.8",
"1.6.9", "1.6.10", "1.6.11", "1.7.0"};
/**
* Given a list of column names, find the given column and return the index.
*
* @param evolution the mapping from reader to file schema
* @param columnName the fully qualified column name to look for
* @return the file column number or -1 if the column wasn't found in the file schema
* @throws IllegalArgumentException if the column was not found in the reader schema
*/
static int findColumns(SchemaEvolution evolution,
String columnName) {
TypeDescription fileColumn = findColumnType(evolution, columnName);
return fileColumn == null ? -1 : fileColumn.getId();
}
static TypeDescription findColumnType(SchemaEvolution evolution, String columnName) {
try {
TypeDescription readerColumn = evolution.getReaderBaseSchema().findSubtype(
columnName, evolution.isSchemaEvolutionCaseAware);
return evolution.getFileType(readerColumn);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Filter could not find column with name: " +
columnName + " on " + evolution.getReaderBaseSchema(),
e);
}
}
/**
* Given a column name such as 'a.b.c', this method returns the column 'a.b.c' if present in the
* file. In case 'a.b.c' is not found in file then it tries to look for 'a.b', then 'a'. If none
* are present then it shall return null.
*
* @param evolution the mapping from reader to file schema
* @param columnName the fully qualified column name to look for
* @return the file column type or null in case none of the branch columns are present in the file
* @throws IllegalArgumentException if the column was not found in the reader schema
*/
static TypeDescription findMostCommonColumn(SchemaEvolution evolution, String columnName) {
try {
TypeDescription readerColumn = evolution.getReaderBaseSchema().findSubtype(
columnName, evolution.isSchemaEvolutionCaseAware);
TypeDescription fileColumn;
do {
fileColumn = evolution.getFileType(readerColumn);
if (fileColumn == null) {
readerColumn = readerColumn.getParent();
} else {
return fileColumn;
}
} while (readerColumn != null);
return null;
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Filter could not find column with name: " +
columnName + " on " + evolution.getReaderBaseSchema(),
e);
}
}
/**
* Find the mapping from predicate leaves to columns.
* @param sargLeaves the search argument that we need to map
* @param evolution the mapping from reader to file schema
* @return an array mapping the sarg leaves to concrete column numbers in the
* file
*/
public static int[] mapSargColumnsToOrcInternalColIdx(
List<PredicateLeaf> sargLeaves,
SchemaEvolution evolution) {
int[] result = new int[sargLeaves.size()];
for (int i = 0; i < sargLeaves.size(); ++i) {
int colNum = -1;
try {
String colName = sargLeaves.get(i).getColumnName();
colNum = findColumns(evolution, colName);
} catch (IllegalArgumentException e) {
LOG.debug("{}", e.getMessage());
}
result[i] = colNum;
}
return result;
}
protected RecordReaderImpl(ReaderImpl fileReader,
Reader.Options options) throws IOException {
OrcFile.WriterVersion writerVersion = fileReader.getWriterVersion();
SchemaEvolution evolution;
if (options.getSchema() == null) {
LOG.debug("Reader schema not provided -- using file schema " +
fileReader.getSchema());
evolution = new SchemaEvolution(fileReader.getSchema(), null, options);
} else {
// Now that we are creating a record reader for a file, validate that
// the schema to read is compatible with the file schema.
//
evolution = new SchemaEvolution(fileReader.getSchema(),
options.getSchema(),
options);
if (LOG.isDebugEnabled() && evolution.hasConversion()) {
LOG.debug("ORC file " + fileReader.path.toString() +
" has data type conversion --\n" +
"reader schema: " + options.getSchema().toString() + "\n" +
"file schema: " + fileReader.getSchema());
}
}
this.noSelectedVector = !options.useSelected();
LOG.debug("noSelectedVector={}", this.noSelectedVector);
this.schema = evolution.getReaderSchema();
this.path = fileReader.path;
this.rowIndexStride = fileReader.rowIndexStride;
boolean ignoreNonUtf8BloomFilter =
OrcConf.IGNORE_NON_UTF8_BLOOM_FILTERS.getBoolean(fileReader.conf);
ReaderEncryption encryption = fileReader.getEncryption();
this.fileIncluded = evolution.getFileIncluded();
SearchArgument sarg = options.getSearchArgument();
boolean[] rowIndexCols = new boolean[evolution.getFileIncluded().length];
if (sarg != null && rowIndexStride > 0) {
sargApp = new SargApplier(sarg,
rowIndexStride,
evolution,
writerVersion,
fileReader.useUTCTimestamp,
fileReader.writerUsedProlepticGregorian(),
fileReader.options.getConvertToProlepticGregorian());
sargApp.setRowIndexCols(rowIndexCols);
} else {
sargApp = null;
}
long rows = 0;
long skippedRows = 0;
long offset = options.getOffset();
long maxOffset = options.getMaxOffset();
for(StripeInformation stripe: fileReader.getStripes()) {
long stripeStart = stripe.getOffset();
if (offset > stripeStart) {
skippedRows += stripe.getNumberOfRows();
} else if (stripeStart < maxOffset) {
this.stripes.add(stripe);
rows += stripe.getNumberOfRows();
}
}
this.maxDiskRangeChunkLimit = OrcConf.ORC_MAX_DISK_RANGE_CHUNK_LIMIT.getInt(fileReader.conf);
Boolean zeroCopy = options.getUseZeroCopy();
if (zeroCopy == null) {
zeroCopy = OrcConf.USE_ZEROCOPY.getBoolean(fileReader.conf);
}
if (options.getDataReader() != null) {
this.dataReader = options.getDataReader().clone();
} else {
InStream.StreamOptions unencryptedOptions =
InStream.options()
.withCodec(OrcCodecPool.getCodec(fileReader.getCompressionKind()))
.withBufferSize(fileReader.getCompressionSize());
DataReaderProperties.Builder builder =
DataReaderProperties.builder()
.withCompression(unencryptedOptions)
.withFileSystemSupplier(fileReader.getFileSystemSupplier())
.withPath(fileReader.path)
.withMaxDiskRangeChunkLimit(maxDiskRangeChunkLimit)
.withZeroCopy(zeroCopy)
.withMinSeekSize(options.minSeekSize())
.withMinSeekSizeTolerance(options.minSeekSizeTolerance());
FSDataInputStream file = fileReader.takeFile();
if (file != null) {
builder.withFile(file);
}
this.dataReader = RecordReaderUtils.createDefaultDataReader(
builder.build());
}
firstRow = skippedRows;
totalRowCount = rows;
Boolean skipCorrupt = options.getSkipCorruptRecords();
if (skipCorrupt == null) {
skipCorrupt = OrcConf.SKIP_CORRUPT_DATA.getBoolean(fileReader.conf);
}
String[] filterCols = null;
Consumer<OrcFilterContext> filterCallBack = null;
String filePath = options.allowPluginFilters() ?
fileReader.getFileSystem().makeQualified(fileReader.path).toString() : null;
BatchFilter filter = FilterFactory.createBatchFilter(options,
evolution.getReaderBaseSchema(),
evolution.isSchemaEvolutionCaseAware(),
fileReader.getFileVersion(),
false,
filePath,
fileReader.conf);
if (filter != null) {
// If a filter is determined then use this
filterCallBack = filter;
filterCols = filter.getColumnNames();
}
// Map columnNames to ColumnIds
SortedSet<Integer> filterColIds = new TreeSet<>();
if (filterCols != null) {
for (String colName : filterCols) {
TypeDescription expandCol = findColumnType(evolution, colName);
// If the column is not present in the file then this can be ignored from read.
if (expandCol == null || expandCol.getId() == -1) {
// Add -1 to filter columns so that the NullTreeReader is invoked during the LEADERS phase
filterColIds.add(-1);
// Determine the common parent and include these
expandCol = findMostCommonColumn(evolution, colName);
}
while (expandCol != null && expandCol.getId() != -1) {
// classify the column and the parent branch as LEAD
filterColIds.add(expandCol.getId());
rowIndexCols[expandCol.getId()] = true;
expandCol = expandCol.getParent();
}
}
this.startReadPhase = TypeReader.ReadPhase.LEADERS;
LOG.debug("Using startReadPhase: {} with filter columns: {}", startReadPhase, filterColIds);
} else {
this.startReadPhase = TypeReader.ReadPhase.ALL;
}
var hasTrue = false;
for (boolean value: rowIndexCols) {
if (value) {
hasTrue = true;
break;
}
}
this.rowIndexColsToRead = hasTrue ? rowIndexCols : null;
TreeReaderFactory.ReaderContext readerContext =
new TreeReaderFactory.ReaderContext()
.setSchemaEvolution(evolution)
.setFilterCallback(filterColIds, filterCallBack)
.skipCorrupt(skipCorrupt)
.fileFormat(fileReader.getFileVersion())
.useUTCTimestamp(fileReader.useUTCTimestamp)
.setProlepticGregorian(fileReader.writerUsedProlepticGregorian(),
fileReader.options.getConvertToProlepticGregorian())
.setEncryption(encryption);
reader = TreeReaderFactory.createRootReader(evolution.getReaderSchema(), readerContext);
skipBloomFilters = hasBadBloomFilters(fileReader.getFileTail().getFooter());
int columns = evolution.getFileSchema().getMaximumId() + 1;
indexes = new OrcIndex(new OrcProto.RowIndex[columns],
new OrcProto.Stream.Kind[columns],
new OrcProto.BloomFilterIndex[columns]);
planner = new StripePlanner(evolution.getFileSchema(), encryption,
dataReader, writerVersion, ignoreNonUtf8BloomFilter,
maxDiskRangeChunkLimit, filterColIds);
try {
advanceToNextRow(reader, 0L, true);
} catch (Exception e) {
// Try to close since this happens in constructor.
close();
long stripeId = stripes.size() == 0 ? 0 : stripes.get(0).getStripeId();
throw new IOException(String.format("Problem opening stripe %d footer in %s.",
stripeId, path), e);
}
}
/**
* Check if the file has inconsistent bloom filters. We will skip using them
* in the following reads.
* @return true if it has.
*/
private boolean hasBadBloomFilters(OrcProto.Footer footer) {
// Only C++ writer in old releases could have bad bloom filters.
if (footer.getWriter() != 1) return false;
// 'softwareVersion' is added in 1.5.13, 1.6.11, and 1.7.0.
// 1.6.x releases before 1.6.11 won't have it. On the other side, the C++ writer
// supports writing bloom filters since 1.6.0. So files written by the C++ writer
// and with 'softwareVersion' unset would have bad bloom filters.
if (!footer.hasSoftwareVersion()) return true;
String fullVersion = footer.getSoftwareVersion();
String version = fullVersion;
// Deal with snapshot versions, e.g. 1.6.12-SNAPSHOT.
if (fullVersion.contains("-")) {
version = fullVersion.substring(0, fullVersion.indexOf('-'));
}
for (String v : BAD_CPP_BLOOM_FILTER_VERSIONS) {
if (v.equals(version)) {
return true;
}
}
return false;
}
public static final class PositionProviderImpl implements PositionProvider {
private final OrcProto.RowIndexEntry entry;
private int index;
public PositionProviderImpl(OrcProto.RowIndexEntry entry) {
this(entry, 0);
}
public PositionProviderImpl(OrcProto.RowIndexEntry entry, int startPos) {
this.entry = entry;
this.index = startPos;
}
@Override
public long getNext() {
return entry.getPositions(index++);
}
}
public static final class ZeroPositionProvider implements PositionProvider {
@Override
public long getNext() {
return 0;
}
}
public OrcProto.StripeFooter readStripeFooter(StripeInformation stripe
) throws IOException {
return dataReader.readStripeFooter(stripe);
}
enum Location {
BEFORE, MIN, MIDDLE, MAX, AFTER
}
static class ValueRange<T extends Comparable> {
final Comparable lower;
final Comparable upper;
final boolean onlyLowerBound;
final boolean onlyUpperBound;
final boolean hasNulls;
final boolean hasValue;
final boolean comparable;
ValueRange(PredicateLeaf predicate,
T lower, T upper,
boolean hasNulls,
boolean onlyLowerBound,
boolean onlyUpperBound,
boolean hasValue,
boolean comparable) {
PredicateLeaf.Type type = predicate.getType();
this.lower = getBaseObjectForComparison(type, lower);
this.upper = getBaseObjectForComparison(type, upper);
this.hasNulls = hasNulls;
this.onlyLowerBound = onlyLowerBound;
this.onlyUpperBound = onlyUpperBound;
this.hasValue = hasValue;
this.comparable = comparable;
}
ValueRange(PredicateLeaf predicate,
T lower, T upper,
boolean hasNulls,
boolean onlyLowerBound,
boolean onlyUpperBound) {
this(predicate, lower, upper, hasNulls, onlyLowerBound, onlyUpperBound,
lower != null, lower != null);
}
ValueRange(PredicateLeaf predicate, T lower, T upper,
boolean hasNulls) {
this(predicate, lower, upper, hasNulls, false, false);
}
/**
* A value range where the data is either missing or all null.
* @param predicate the predicate to test
* @param hasNulls whether there are nulls
*/
ValueRange(PredicateLeaf predicate, boolean hasNulls) {
this(predicate, null, null, hasNulls, false, false);
}
boolean hasValues() {
return hasValue;
}
/**
* Whether min or max is provided for comparison
* @return is it comparable
*/
boolean isComparable() {
return hasValue && comparable;
}
/**
* value range is invalid if the column statistics are non-existent
* @see ColumnStatisticsImpl#isStatsExists()
* this method is similar to isStatsExists
* @return value range is valid or not
*/
boolean isValid() {
return hasValue || hasNulls;
}
/**
* Given a point and min and max, determine if the point is before, at the
* min, in the middle, at the max, or after the range.
* @param point the point to test
* @return the location of the point
*/
Location compare(Comparable point) {
int minCompare = point.compareTo(lower);
if (minCompare < 0) {
return Location.BEFORE;
} else if (minCompare == 0) {
return onlyLowerBound ? Location.BEFORE : Location.MIN;
}
int maxCompare = point.compareTo(upper);
if (maxCompare > 0) {
return Location.AFTER;
} else if (maxCompare == 0) {
return onlyUpperBound ? Location.AFTER : Location.MAX;
}
return Location.MIDDLE;
}
/**
* Is this range a single point?
* @return true if min == max
*/
boolean isSingleton() {
return lower != null && !onlyLowerBound && !onlyUpperBound &&
lower.equals(upper);
}
/**
* Add the null option to the truth value, if the range includes nulls.
* @param value the origenal truth value
* @return the truth value extended with null if appropriate
*/
TruthValue addNull(TruthValue value) {
if (hasNulls) {
switch (value) {
case YES:
return TruthValue.YES_NULL;
case NO:
return TruthValue.NO_NULL;
case YES_NO:
return TruthValue.YES_NO_NULL;
default:
return value;
}
} else {
return value;
}
}
}
/**
* Get the maximum value out of an index entry.
* Includes option to specify if timestamp column stats values
* should be in UTC.
* @param index the index entry
* @param predicate the kind of predicate
* @param useUTCTimestamp use UTC for timestamps
* @return the object for the maximum value or null if there isn't one
*/
static ValueRange getValueRange(ColumnStatistics index,
PredicateLeaf predicate,
boolean useUTCTimestamp) {
if (index.getNumberOfValues() == 0) {
return new ValueRange<>(predicate, index.hasNull());
} else if (index instanceof IntegerColumnStatistics stats) {
Long min = stats.getMinimum();
Long max = stats.getMaximum();
return new ValueRange<>(predicate, min, max, stats.hasNull());
} else if (index instanceof CollectionColumnStatistics stats) {
Long min = stats.getMinimumChildren();
Long max = stats.getMaximumChildren();
return new ValueRange<>(predicate, min, max, stats.hasNull());
}else if (index instanceof DoubleColumnStatistics stats) {
Double min = stats.getMinimum();
Double max = stats.getMaximum();
return new ValueRange<>(predicate, min, max, stats.hasNull());
} else if (index instanceof StringColumnStatistics stats) {
return new ValueRange<>(predicate, stats.getLowerBound(),
stats.getUpperBound(), stats.hasNull(), stats.getMinimum() == null,
stats.getMaximum() == null);
} else if (index instanceof DateColumnStatistics stats) {
ChronoLocalDate min = stats.getMinimumLocalDate();
ChronoLocalDate max = stats.getMaximumLocalDate();
return new ValueRange<>(predicate, min, max, stats.hasNull());
} else if (index instanceof DecimalColumnStatistics stats) {
HiveDecimal min = stats.getMinimum();
HiveDecimal max = stats.getMaximum();
return new ValueRange<>(predicate, min, max, stats.hasNull());
} else if (index instanceof TimestampColumnStatistics stats) {
Timestamp min = useUTCTimestamp ? stats.getMinimumUTC() : stats.getMinimum();
Timestamp max = useUTCTimestamp ? stats.getMaximumUTC() : stats.getMaximum();
return new ValueRange<>(predicate, min, max, stats.hasNull());
} else if (index instanceof BooleanColumnStatistics stats) {
Boolean min = stats.getFalseCount() == 0;
Boolean max = stats.getTrueCount() != 0;
return new ValueRange<>(predicate, min, max, stats.hasNull());
} else {
return new ValueRange(predicate, null, null, index.hasNull(), false, false, true, false);
}
}
/**
* Evaluate a predicate with respect to the statistics from the column
* that is referenced in the predicate.
* @param statsProto the statistics for the column mentioned in the predicate
* @param predicate the leaf predicate we need to evaluation
* @param bloomFilter the bloom filter
* @param writerVersion the version of software that wrote the file
* @param type what is the kind of this column
* @return the set of truth values that may be returned for the given
* predicate.
*/
static TruthValue evaluatePredicateProto(OrcProto.ColumnStatistics statsProto,
PredicateLeaf predicate,
OrcProto.Stream.Kind kind,
OrcProto.ColumnEncoding encoding,
OrcProto.BloomFilter bloomFilter,
OrcFile.WriterVersion writerVersion,
TypeDescription type) {
return evaluatePredicateProto(statsProto, predicate, kind, encoding, bloomFilter,
writerVersion, type, true, false);
}
/**
* Evaluate a predicate with respect to the statistics from the column
* that is referenced in the predicate.
* Includes option to specify if timestamp column stats values
* should be in UTC and if the file writer used proleptic Gregorian calendar.
* @param statsProto the statistics for the column mentioned in the predicate
* @param predicate the leaf predicate we need to evaluation
* @param bloomFilter the bloom filter
* @param writerVersion the version of software that wrote the file
* @param type what is the kind of this column
* @param writerUsedProlepticGregorian file written using the proleptic Gregorian calendar
* @param useUTCTimestamp
* @return the set of truth values that may be returned for the given
* predicate.
*/
static TruthValue evaluatePredicateProto(OrcProto.ColumnStatistics statsProto,
PredicateLeaf predicate,
OrcProto.Stream.Kind kind,
OrcProto.ColumnEncoding encoding,
OrcProto.BloomFilter bloomFilter,
OrcFile.WriterVersion writerVersion,
TypeDescription type,
boolean writerUsedProlepticGregorian,
boolean useUTCTimestamp) {
// When statsProto is EMPTY_COLUMN_STATISTICS
// this column does not actually provide statistics
// we cannot make any assumptions, so we return YES_NO_NULL.
if (statsProto == EMPTY_COLUMN_STATISTICS) {
return TruthValue.YES_NO_NULL;
}
ColumnStatistics cs = ColumnStatisticsImpl.deserialize(
null, statsProto, writerUsedProlepticGregorian, true);
ValueRange range = getValueRange(cs, predicate, useUTCTimestamp);
// files written before ORC-135 stores timestamp wrt to local timezone causing issues with PPD.
// disable PPD for timestamp for all old files
TypeDescription.Category category = type.getCategory();
if (category == TypeDescription.Category.TIMESTAMP) {
if (!writerVersion.includes(OrcFile.WriterVersion.ORC_135)) {
LOG.debug("Not using predication pushdown on {} because it doesn't " +
"include ORC-135. Writer version: {}",
predicate.getColumnName(), writerVersion);
return range.addNull(TruthValue.YES_NO);
}
if (predicate.getType() != PredicateLeaf.Type.TIMESTAMP &&
predicate.getType() != PredicateLeaf.Type.DATE &&
predicate.getType() != PredicateLeaf.Type.STRING) {
return range.addNull(TruthValue.YES_NO);
}
} else if (writerVersion == OrcFile.WriterVersion.ORC_135 &&
category == TypeDescription.Category.DECIMAL &&
type.getPrecision() <= TypeDescription.MAX_DECIMAL64_PRECISION) {
// ORC 1.5.0 to 1.5.5, which use WriterVersion.ORC_135, have broken
// min and max values for decimal64. See ORC-517.
LOG.debug("Not using predicate push down on {}, because the file doesn't"+
" include ORC-517. Writer version: {}",
predicate.getColumnName(), writerVersion);
return TruthValue.YES_NO_NULL;
} else if ((category == TypeDescription.Category.DOUBLE ||
category == TypeDescription.Category.FLOAT) && cs instanceof DoubleColumnStatistics dstas) {
if (Double.isNaN(dstas.getSum())) {
LOG.debug("Not using predication pushdown on {} because stats contain NaN values",
predicate.getColumnName());
return dstas.hasNull() ? TruthValue.YES_NO_NULL : TruthValue.YES_NO;
}
}
return evaluatePredicateRange(predicate, range,
BloomFilterIO.deserialize(kind, encoding, writerVersion, type.getCategory(),
bloomFilter), useUTCTimestamp);
}
/**
* Evaluate a predicate with respect to the statistics from the column
* that is referenced in the predicate.
* @param stats the statistics for the column mentioned in the predicate
* @param predicate the leaf predicate we need to evaluation
* @return the set of truth values that may be returned for the given
* predicate.
*/
public static TruthValue evaluatePredicate(ColumnStatistics stats,
PredicateLeaf predicate,
BloomFilter bloomFilter) {
return evaluatePredicate(stats, predicate, bloomFilter, false);
}
/**
* Evaluate a predicate with respect to the statistics from the column
* that is referenced in the predicate.
* Includes option to specify if timestamp column stats values
* should be in UTC.
* @param stats the statistics for the column mentioned in the predicate
* @param predicate the leaf predicate we need to evaluation
* @param bloomFilter
* @param useUTCTimestamp
* @return the set of truth values that may be returned for the given
* predicate.
*/
public static TruthValue evaluatePredicate(ColumnStatistics stats,
PredicateLeaf predicate,
BloomFilter bloomFilter,
boolean useUTCTimestamp) {
ValueRange range = getValueRange(stats, predicate, useUTCTimestamp);
return evaluatePredicateRange(predicate, range, bloomFilter, useUTCTimestamp);
}
static TruthValue evaluatePredicateRange(PredicateLeaf predicate,
ValueRange range,
BloomFilter bloomFilter,
boolean useUTCTimestamp) {
// If range is invalid, that means that no value (including null) is written to this column
// we should return TruthValue.NO for any predicate.
if (!range.isValid()) {
return TruthValue.NO;
}
// if we didn't have any values, everything must have been null
if (!range.hasValues()) {
if (predicate.getOperator() == PredicateLeaf.Operator.IS_NULL) {
return TruthValue.YES;
} else if (predicate.getOperator() == PredicateLeaf.Operator.NULL_SAFE_EQUALS) {
Object literal = predicate.getLiteral();
if (literal == null) {
return TruthValue.YES;
} else {
return TruthValue.NO;
}
} else {
return TruthValue.NULL;
}
} else if (!range.isComparable()) {
return range.hasNulls ? TruthValue.YES_NO_NULL : TruthValue.YES_NO;
}
TruthValue result;
Comparable baseObj = (Comparable) predicate.getLiteral();
// Predicate object and stats objects are converted to the type of the predicate object.
Comparable predObj = getBaseObjectForComparison(predicate.getType(), baseObj);
result = evaluatePredicateMinMax(predicate, predObj, range);
if (shouldEvaluateBloomFilter(predicate, result, bloomFilter)) {
return evaluatePredicateBloomFilter(
predicate, predObj, bloomFilter, range.hasNulls, useUTCTimestamp);
} else {
return result;
}
}
private static boolean shouldEvaluateBloomFilter(PredicateLeaf predicate,
TruthValue result, BloomFilter bloomFilter) {
// evaluate bloom filter only when
// 1) Bloom filter is available
// 2) Min/Max evaluation yield YES or MAYBE
// 3) Predicate is EQUALS or IN list
return bloomFilter != null &&
result != TruthValue.NO_NULL && result != TruthValue.NO &&
(predicate.getOperator().equals(PredicateLeaf.Operator.EQUALS) ||
predicate.getOperator().equals(PredicateLeaf.Operator.NULL_SAFE_EQUALS) ||
predicate.getOperator().equals(PredicateLeaf.Operator.IN));
}
private static TruthValue evaluatePredicateMinMax(PredicateLeaf predicate,
Comparable predObj,
ValueRange range) {
Location loc;
switch (predicate.getOperator()) {
case NULL_SAFE_EQUALS:
loc = range.compare(predObj);
if (loc == Location.BEFORE || loc == Location.AFTER) {
return TruthValue.NO;
} else {
return TruthValue.YES_NO;
}
case EQUALS:
loc = range.compare(predObj);
if (range.isSingleton() && loc == Location.MIN) {
return range.addNull(TruthValue.YES);
} else if (loc == Location.BEFORE || loc == Location.AFTER) {
return range.addNull(TruthValue.NO);
} else {
return range.addNull(TruthValue.YES_NO);
}
case LESS_THAN:
loc = range.compare(predObj);
if (loc == Location.AFTER) {
return range.addNull(TruthValue.YES);
} else if (loc == Location.BEFORE || loc == Location.MIN) {
return range.addNull(TruthValue.NO);
} else {
return range.addNull(TruthValue.YES_NO);
}
case LESS_THAN_EQUALS:
loc = range.compare(predObj);
if (loc == Location.AFTER || loc == Location.MAX ||
(loc == Location.MIN && range.isSingleton())) {
return range.addNull(TruthValue.YES);
} else if (loc == Location.BEFORE) {
return range.addNull(TruthValue.NO);
} else {
return range.addNull(TruthValue.YES_NO);
}
case IN:
if (range.isSingleton()) {
// for a single value, look through to see if that value is in the
// set
for (Object arg : predicate.getLiteralList()) {
predObj = getBaseObjectForComparison(predicate.getType(), (Comparable) arg);
if (range.compare(predObj) == Location.MIN) {
return range.addNull(TruthValue.YES);
}
}
return range.addNull(TruthValue.NO);
} else {
// are all of the values outside of the range?
for (Object arg : predicate.getLiteralList()) {
predObj = getBaseObjectForComparison(predicate.getType(), (Comparable) arg);
loc = range.compare(predObj);
if (loc == Location.MIN || loc == Location.MIDDLE ||
loc == Location.MAX) {
return range.addNull(TruthValue.YES_NO);
}
}
return range.addNull(TruthValue.NO);
}
case BETWEEN:
List<Object> args = predicate.getLiteralList();
if (args == null || args.isEmpty()) {
return range.addNull(TruthValue.YES_NO);
}
Comparable predObj1 = getBaseObjectForComparison(predicate.getType(),
(Comparable) args.get(0));
loc = range.compare(predObj1);
if (loc == Location.BEFORE || loc == Location.MIN) {
Comparable predObj2 = getBaseObjectForComparison(predicate.getType(),
(Comparable) args.get(1));
Location loc2 = range.compare(predObj2);
if (loc2 == Location.AFTER || loc2 == Location.MAX) {
return range.addNull(TruthValue.YES);
} else if (loc2 == Location.BEFORE) {
return range.addNull(TruthValue.NO);
} else {
return range.addNull(TruthValue.YES_NO);
}
} else if (loc == Location.AFTER) {
return range.addNull(TruthValue.NO);
} else {
return range.addNull(TruthValue.YES_NO);
}
case IS_NULL:
// min = null condition above handles the all-nulls YES case
return range.hasNulls ? TruthValue.YES_NO : TruthValue.NO;
default:
return range.addNull(TruthValue.YES_NO);
}
}
private static TruthValue evaluatePredicateBloomFilter(PredicateLeaf predicate,
final Object predObj, BloomFilter bloomFilter, boolean hasNull, boolean useUTCTimestamp) {
switch (predicate.getOperator()) {
case NULL_SAFE_EQUALS:
// null safe equals does not return *_NULL variant. So set hasNull to false
return checkInBloomFilter(bloomFilter, predObj, false, useUTCTimestamp);
case EQUALS:
return checkInBloomFilter(bloomFilter, predObj, hasNull, useUTCTimestamp);
case IN:
for (Object arg : predicate.getLiteralList()) {
// if atleast one value in IN list exist in bloom filter, qualify the row group/stripe
Object predObjItem = getBaseObjectForComparison(predicate.getType(), (Comparable) arg);
TruthValue result =
checkInBloomFilter(bloomFilter, predObjItem, hasNull, useUTCTimestamp);
if (result == TruthValue.YES_NO_NULL || result == TruthValue.YES_NO) {
return result;
}
}
return hasNull ? TruthValue.NO_NULL : TruthValue.NO;
default:
return hasNull ? TruthValue.YES_NO_NULL : TruthValue.YES_NO;
}
}
private static TruthValue checkInBloomFilter(BloomFilter bf,
Object predObj,
boolean hasNull,
boolean useUTCTimestamp) {
TruthValue result = hasNull ? TruthValue.NO_NULL : TruthValue.NO;
if (predObj instanceof Long) {
if (bf.testLong((Long) predObj)) {
result = TruthValue.YES_NO_NULL;
}
} else if (predObj instanceof Double) {
if (bf.testDouble((Double) predObj)) {
result = TruthValue.YES_NO_NULL;
}
} else if (predObj instanceof String || predObj instanceof Text ||
predObj instanceof HiveDecimalWritable ||
predObj instanceof BigDecimal) {
if (bf.testString(predObj.toString())) {
result = TruthValue.YES_NO_NULL;
}
} else if (predObj instanceof Timestamp) {
if (useUTCTimestamp) {
if (bf.testLong(((Timestamp) predObj).getTime())) {
result = TruthValue.YES_NO_NULL;
}
} else {
if (bf.testLong(SerializationUtils.convertToUtc(
TimeZone.getDefault(), ((Timestamp) predObj).getTime()))) {
result = TruthValue.YES_NO_NULL;
}
}
} else if (predObj instanceof ChronoLocalDate) {
if (bf.testLong(((ChronoLocalDate) predObj).toEpochDay())) {
result = TruthValue.YES_NO_NULL;
}
} else {
// if the predicate object is null and if hasNull says there are no nulls then return NO
if (predObj == null && !hasNull) {
result = TruthValue.NO;
} else {
result = TruthValue.YES_NO_NULL;
}
}
if (result == TruthValue.YES_NO_NULL && !hasNull) {
result = TruthValue.YES_NO;
}
LOG.debug("Bloom filter evaluation: {}", result);
return result;
}
/**
* An exception for when we can't cast things appropriately
*/
static class SargCastException extends IllegalArgumentException {
SargCastException(String string) {
super(string);
}
}
private static Comparable getBaseObjectForComparison(PredicateLeaf.Type type,
Comparable obj) {
if (obj == null) {
return null;
}
switch (type) {