forked from apache/datafusion-comet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathColumnReader.java
More file actions
324 lines (281 loc) · 11.6 KB
/
ColumnReader.java
File metadata and controls
324 lines (281 loc) · 11.6 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
/*
* 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.comet.parquet;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.arrow.c.ArrowArray;
import org.apache.arrow.c.ArrowSchema;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.memory.RootAllocator;
import org.apache.arrow.vector.FieldVector;
import org.apache.arrow.vector.dictionary.Dictionary;
import org.apache.arrow.vector.types.pojo.DictionaryEncoding;
import org.apache.parquet.column.ColumnDescriptor;
import org.apache.parquet.column.Encoding;
import org.apache.parquet.column.page.DataPage;
import org.apache.parquet.column.page.DataPageV1;
import org.apache.parquet.column.page.DataPageV2;
import org.apache.parquet.column.page.DictionaryPage;
import org.apache.parquet.column.page.PageReader;
import org.apache.parquet.schema.LogicalTypeAnnotation;
import org.apache.spark.sql.types.DataType;
import org.apache.comet.CometConf;
import org.apache.comet.CometSchemaImporter;
import org.apache.comet.IcebergApi;
import org.apache.comet.vector.CometDecodedVector;
import org.apache.comet.vector.CometDictionary;
import org.apache.comet.vector.CometDictionaryVector;
import org.apache.comet.vector.CometPlainVector;
import org.apache.comet.vector.CometVector;
@IcebergApi
public class ColumnReader extends AbstractColumnReader {
protected static final Logger LOG = LoggerFactory.getLogger(ColumnReader.class);
protected final BufferAllocator ALLOCATOR = new RootAllocator();
/**
* The current Comet vector holding all the values read by this column reader. Owned by this
* reader and MUST be closed after use.
*/
private CometDecodedVector currentVector;
/** Dictionary values for this column. Only set if the column is using dictionary encoding. */
protected CometDictionary dictionary;
/** Reader for dictionary & data pages in the current column chunk. */
protected PageReader pageReader;
/** Whether the first data page has been loaded. */
private boolean firstPageLoaded = false;
/**
* The number of nulls in the current batch, used when we are skipping importing of Arrow vectors,
* in which case we'll simply update the null count of the existing vectors.
*/
int currentNumNulls;
/**
* The number of values in the current batch, used when we are skipping importing of Arrow
* vectors, in which case we'll simply update the null count of the existing vectors.
*/
int currentNumValues;
/**
* Whether the last loaded vector contains any null value. This is used to determine if we can
* skip vector reloading. If the flag is false, Arrow C API will skip to import the validity
* buffer, and therefore we cannot skip vector reloading.
*/
boolean hadNull;
private final CometSchemaImporter importer;
private ArrowArray array = null;
private ArrowSchema schema = null;
ColumnReader(
DataType type,
ColumnDescriptor descriptor,
CometSchemaImporter importer,
int batchSize,
boolean useDecimal128,
boolean useLegacyDateTimestamp) {
super(type, descriptor, useDecimal128, useLegacyDateTimestamp);
assert batchSize > 0 : "Batch size must be positive, found " + batchSize;
this.batchSize = batchSize;
this.importer = importer;
initNative();
}
/**
* Set the page reader for a new column chunk to read. Expects to call `readBatch` after this.
*
* @param pageReader the page reader for the new column chunk
* @see <a href="https://github.com/apache/datafusion-comet/issues/2079">Comet Issue #2079</a>
*/
@IcebergApi
public void setPageReader(PageReader pageReader) throws IOException {
this.pageReader = pageReader;
DictionaryPage dictionaryPage = pageReader.readDictionaryPage();
if (dictionaryPage != null) {
LOG.debug("dictionary page encoding = {}", dictionaryPage.getEncoding());
Native.setDictionaryPage(
nativeHandle,
dictionaryPage.getDictionarySize(),
dictionaryPage.getBytes().toByteArray(),
dictionaryPage.getEncoding().ordinal());
}
}
/** This method is called from Apache Iceberg. */
@IcebergApi
public void setRowGroupReader(RowGroupReader rowGroupReader, ParquetColumnSpec columnSpec)
throws IOException {
ColumnDescriptor descriptor = Utils.buildColumnDescriptor(columnSpec);
setPageReader(rowGroupReader.getPageReader(descriptor));
}
@Override
public void readBatch(int total) {
LOG.debug("Start to batch of size = " + total);
if (!firstPageLoaded) {
readPage();
firstPageLoaded = true;
}
// Now first reset the current columnar batch so that it can be used to fill in a new batch
// of values. Then, keep reading more data pages (via 'readBatch') until the current batch is
// full, or we have read 'total' number of values.
Native.resetBatch(nativeHandle);
int left = total, nullsRead = 0;
while (left > 0) {
int[] array = Native.readBatch(nativeHandle, left);
int valuesRead = array[0];
nullsRead += array[1];
if (valuesRead < left) {
readPage();
}
left -= valuesRead;
}
this.currentNumValues = total;
this.currentNumNulls = nullsRead;
}
/** Returns the {@link CometVector} read by this reader. */
@Override
public CometVector currentBatch() {
return loadVector();
}
@Override
public void close() {
if (currentVector != null) {
currentVector.close();
currentVector = null;
}
super.close();
}
/** Returns a decoded {@link CometDecodedVector Comet vector}. */
public CometDecodedVector loadVector() {
LOG.debug("Reloading vector");
// Close the previous vector first to release struct memory allocated to import Arrow array &
// schema from native side, through the C data interface
if (currentVector != null) {
currentVector.close();
}
LogicalTypeAnnotation logicalTypeAnnotation =
descriptor.getPrimitiveType().getLogicalTypeAnnotation();
boolean isUuid =
logicalTypeAnnotation instanceof LogicalTypeAnnotation.UUIDLogicalTypeAnnotation;
array = ArrowArray.allocateNew(ALLOCATOR);
schema = ArrowSchema.allocateNew(ALLOCATOR);
long arrayAddr = array.memoryAddress();
long schemaAddr = schema.memoryAddress();
Native.currentBatch(nativeHandle, arrayAddr, schemaAddr);
FieldVector vector = importer.importVector(array, schema);
DictionaryEncoding dictionaryEncoding = vector.getField().getDictionary();
CometPlainVector cometVector = new CometPlainVector(vector, useDecimal128);
// Update whether the current vector contains any null values. This is used in the following
// batch(s) to determine whether we can skip loading the native vector.
hadNull = cometVector.hasNull();
if (dictionaryEncoding == null) {
if (dictionary != null) {
// This means the column was using dictionary encoding but now has fall-back to plain
// encoding, on the native side. Setting 'dictionary' to null here, so we can use it as
// a condition to check if we can re-use vector later.
dictionary = null;
}
// Either the column is not dictionary encoded, or it was using dictionary encoding but
// a new data page has switched back to use plain encoding. For both cases we should
// return plain vector.
currentVector = cometVector;
return currentVector;
}
// We should already re-initiate `CometDictionary` here because `Data.importVector` API will
// release the previous dictionary vector and create a new one.
Dictionary arrowDictionary = importer.getProvider().lookup(dictionaryEncoding.getId());
CometPlainVector dictionaryVector =
new CometPlainVector(arrowDictionary.getVector(), useDecimal128, isUuid);
if (dictionary != null) {
dictionary.setDictionaryVector(dictionaryVector);
} else {
dictionary = new CometDictionary(dictionaryVector);
}
currentVector =
new CometDictionaryVector(
cometVector, dictionary, importer.getProvider(), useDecimal128, false, isUuid);
currentVector =
new CometDictionaryVector(cometVector, dictionary, importer.getProvider(), useDecimal128);
return currentVector;
}
protected void readPage() {
DataPage page = pageReader.readPage();
if (page == null) {
throw new RuntimeException("overreading: returned DataPage is null");
}
;
int pageValueCount = page.getValueCount();
page.accept(
new DataPage.Visitor<Void>() {
@Override
public Void visit(DataPageV1 dataPageV1) {
LOG.debug("data page encoding = {}", dataPageV1.getValueEncoding());
if (dataPageV1.getDlEncoding() != Encoding.RLE
&& descriptor.getMaxDefinitionLevel() != 0) {
throw new UnsupportedOperationException(
"Unsupported encoding: " + dataPageV1.getDlEncoding());
}
if (!isValidValueEncoding(dataPageV1.getValueEncoding())) {
throw new UnsupportedOperationException(
"Unsupported value encoding: " + dataPageV1.getValueEncoding());
}
try {
boolean useDirectBuffer =
(Boolean) CometConf.COMET_PARQUET_ENABLE_DIRECT_BUFFER().get();
if (useDirectBuffer) {
ByteBuffer buffer = dataPageV1.getBytes().toByteBuffer();
Native.setPageBufferV1(
nativeHandle, pageValueCount, buffer, dataPageV1.getValueEncoding().ordinal());
} else {
byte[] array = dataPageV1.getBytes().toByteArray();
Native.setPageV1(
nativeHandle, pageValueCount, array, dataPageV1.getValueEncoding().ordinal());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
@Override
public Void visit(DataPageV2 dataPageV2) {
if (!isValidValueEncoding(dataPageV2.getDataEncoding())) {
throw new UnsupportedOperationException(
"Unsupported encoding: " + dataPageV2.getDataEncoding());
}
try {
Native.setPageV2(
nativeHandle,
pageValueCount,
dataPageV2.getDefinitionLevels().toByteArray(),
dataPageV2.getRepetitionLevels().toByteArray(),
dataPageV2.getData().toByteArray(),
dataPageV2.getDataEncoding().ordinal());
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
});
}
@SuppressWarnings("deprecation")
private boolean isValidValueEncoding(Encoding encoding) {
switch (encoding) {
case PLAIN:
case RLE_DICTIONARY:
case PLAIN_DICTIONARY:
return true;
default:
return false;
}
}
}