hudi-agent commented on code in PR #18741:
URL: https://github.com/apache/hudi/pull/18741#discussion_r3245908316
##########
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/table/HoodieTableFactory.java:
##########
@@ -220,12 +215,21 @@ private void checkIndexType(Configuration conf) {
}
/**
- * Validate the base file format. Lance is only supported with the Spark
engine.
+ * Validate the base file format. Flink Lance support is scoped to
append-only COW tables.
*/
- private void checkBaseFileFormat(Configuration conf) {
+ private void checkBaseFileFormat(Configuration conf, boolean write) {
String baseFileFormat =
conf.getString(HoodieTableConfig.BASE_FILE_FORMAT.key(), null);
if (baseFileFormat != null &&
HoodieFileFormat.LANCE.name().equalsIgnoreCase(baseFileFormat)) {
- throw new
HoodieValidationException(HoodieFileFormat.LANCE_SPARK_ONLY_ERROR_MSG);
+ if (conf.containsKey(FlinkOptions.RECORD_KEY_FIELD.key())) {
Review Comment:
🤖 On the sink path, `sanityCheck` (and so `checkBaseFileFormat`) runs
*before* `setupConfOptions` → `setupHoodieKeyOptions`, which is where `PRIMARY
KEY` syntax is copied into `FlinkOptions.RECORD_KEY_FIELD`. So a Lance +
`operation=insert` table declared with `PRIMARY KEY (..) NOT ENFORCED` passes
this validation and only fails on the source side — leaving the user able to
write but not read. Would it make sense to also check
`schema.getPrimaryKey().isPresent()` here (and add a test using PRIMARY KEY
syntax rather than the option)?
<sub><i>- AI-generated; verify before applying. React 👍/👎 to flag
quality.</i></sub>
##########
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/table/format/cow/CopyOnWriteInputFormat.java:
##########
@@ -116,32 +124,50 @@ public CopyOnWriteInputFormat(
@Override
public void open(FileInputSplit fileSplit) throws IOException {
- LinkedHashMap<String, Object> partObjects =
FilePathUtils.generatePartitionSpecs(
- fileSplit.getPath().getPath(),
- Arrays.asList(fullFieldNames),
- Arrays.asList(fullFieldTypes),
- this.partDefaultName,
- this.partPathField,
- this.hiveStylePartitioning
- );
-
- this.itr = RecordIterators.getParquetRecordIterator(
- internalSchemaManager,
- utcTimestamp,
- true,
- conf.conf(),
- fullFieldNames,
- fullFieldTypes,
- partObjects,
- selectedFields,
- 2048,
- fileSplit.getPath(),
- fileSplit.getStart(),
- fileSplit.getLength(),
- predicates);
+ if
(fileSplit.getPath().getName().endsWith(HoodieFileFormat.LANCE.getFileExtension()))
{
+ this.itr = getLanceRecordIterator(fileSplit.getPath());
+ } else {
+ LinkedHashMap<String, Object> partObjects =
FilePathUtils.generatePartitionSpecs(
+ fileSplit.getPath().getPath(),
+ Arrays.asList(fullFieldNames),
+ Arrays.asList(fullFieldTypes),
+ this.partDefaultName,
+ this.partPathField,
+ this.hiveStylePartitioning
+ );
+ this.itr = RecordIterators.getParquetRecordIterator(
+ internalSchemaManager,
+ utcTimestamp,
+ true,
+ conf.conf(),
+ fullFieldNames,
+ fullFieldTypes,
+ partObjects,
+ selectedFields,
+ 2048,
+ fileSplit.getPath(),
+ fileSplit.getStart(),
+ fileSplit.getLength(),
+ predicates);
+ }
this.currentReadCount = 0L;
}
+ private ClosableIterator<RowData> getLanceRecordIterator(Path path) {
+ DataType selectedDataType = DataTypes.ROW(Arrays.stream(selectedFields)
+ .mapToObj(i -> DataTypes.FIELD(fullFieldNames[i],
fullFieldTypes[i]))
+ .toArray(DataTypes.Field[]::new))
+ .bridgedTo(RowData.class);
+ HoodieSchema requestedSchema =
HoodieSchemaConverter.convertToSchema(selectedDataType.getLogicalType());
Review Comment:
🤖 The Lance branch projects only `selectedFields` from the file and does not
inject partition values from the path (which the Parquet branch does via
`partObjects`). If `hoodie.datasource.write.drop.partitioncolumns=true`, the
partition column won't be in the Lance file and `orderVectors` will throw
`Missing Lance column in projected batch: <partition>` for any query that
selects the partition column. Is this combination intended to be unsupported,
or should we either inject the value here or block the config in
`checkBaseFileFormat`?
<sub><i>- AI-generated; verify before applying. React 👍/👎 to flag
quality.</i></sub>
##########
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/table/format/HoodieRowDataLanceReader.java:
##########
@@ -0,0 +1,302 @@
+/*
+ * 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.hudi.table.format;
+
+import org.apache.hudi.client.model.HoodieFlinkRecord;
+import org.apache.hudi.common.bloom.BloomFilter;
+import org.apache.hudi.common.bloom.HoodieDynamicBoundedBloomFilter;
+import org.apache.hudi.common.bloom.SimpleBloomFilter;
+import org.apache.hudi.common.config.HoodieConfig;
+import org.apache.hudi.common.config.HoodieStorageConfig;
+import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.common.schema.HoodieSchema;
+import org.apache.hudi.common.schema.HoodieSchemaUtils;
+import org.apache.hudi.common.util.collection.ClosableIterator;
+import org.apache.hudi.common.util.collection.CloseableMappingIterator;
+import org.apache.hudi.common.util.collection.Pair;
+import org.apache.hudi.exception.HoodieException;
+import org.apache.hudi.exception.HoodieIOException;
+import org.apache.hudi.io.memory.HoodieArrowAllocator;
+import org.apache.hudi.io.storage.HoodieFileReader;
+import org.apache.hudi.io.storage.row.HoodieFlinkLanceArrowUtils;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.util.HoodieSchemaConverter;
+import org.apache.hudi.util.RowDataQueryContexts;
+
+import org.apache.arrow.memory.BufferAllocator;
+import org.apache.arrow.vector.FieldVector;
+import org.apache.arrow.vector.VectorSchemaRoot;
+import org.apache.arrow.vector.ipc.ArrowReader;
+import org.apache.arrow.vector.types.pojo.Schema;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.logical.RowType;
+import org.lance.file.LanceFileReader;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static
org.apache.hudi.avro.HoodieBloomFilterWriteSupport.HOODIE_AVRO_BLOOM_FILTER_METADATA_KEY;
+import static
org.apache.hudi.avro.HoodieBloomFilterWriteSupport.HOODIE_BLOOM_FILTER_TYPE_CODE;
+import static
org.apache.hudi.avro.HoodieBloomFilterWriteSupport.HOODIE_MAX_RECORD_KEY_FOOTER;
+import static
org.apache.hudi.avro.HoodieBloomFilterWriteSupport.HOODIE_MIN_RECORD_KEY_FOOTER;
+
+/**
+ * Lance reader for Flink RowData base files.
+ */
+public class HoodieRowDataLanceReader implements HoodieFileReader<RowData> {
+
+ private static final int DEFAULT_BATCH_SIZE = 512;
+
+ private final StoragePath path;
+ private final long dataAllocatorSize;
+ private final BufferAllocator metadataAllocator;
+ private final LanceFileReader metadataReader;
+ private final Schema arrowSchema;
+ private boolean closed;
+
+ public HoodieRowDataLanceReader(StoragePath path, HoodieConfig hoodieConfig)
{
+ this.path = path;
+ this.dataAllocatorSize =
hoodieConfig.getLongOrDefault(HoodieStorageConfig.LANCE_READ_ALLOCATOR_SIZE_BYTES);
+ this.metadataAllocator = HoodieArrowAllocator.newChildAllocator(
+ getClass().getSimpleName() + "-metadata-" + path.getName(),
+
hoodieConfig.getLongOrDefault(HoodieStorageConfig.LANCE_READ_METADATA_ALLOCATOR_SIZE_BYTES));
+ try {
+ this.metadataReader = LanceFileReader.open(path.toString(),
metadataAllocator);
+ this.arrowSchema = metadataReader.schema();
+ } catch (Exception e) {
+ close();
+ throw new HoodieException("Failed to create Lance reader for: " + path,
e);
+ }
+ }
+
+ @Override
+ public String[] readMinMaxRecordKeys() {
+ Map<String, String> metadata = arrowSchema.getCustomMetadata();
+ if (metadata != null) {
+ String minKey = metadata.get(HOODIE_MIN_RECORD_KEY_FOOTER);
+ String maxKey = metadata.get(HOODIE_MAX_RECORD_KEY_FOOTER);
+ if (minKey != null && maxKey != null) {
+ return new String[] {minKey, maxKey};
+ }
+ }
+ throw new HoodieException("Could not read min/max record key out of Lance
file: " + path);
+ }
+
+ @Override
+ public BloomFilter readBloomFilter() {
+ Map<String, String> metadata = arrowSchema.getCustomMetadata();
+ if (metadata == null ||
!metadata.containsKey(HOODIE_AVRO_BLOOM_FILTER_METADATA_KEY)) {
+ return null;
+ }
+ String bloomSer = metadata.get(HOODIE_AVRO_BLOOM_FILTER_METADATA_KEY);
+ String filterType = metadata.get(HOODIE_BLOOM_FILTER_TYPE_CODE);
+ if (filterType != null &&
filterType.contains(HoodieDynamicBoundedBloomFilter.TYPE_CODE_PREFIX)) {
+ return new HoodieDynamicBoundedBloomFilter(bloomSer);
+ }
+ return new SimpleBloomFilter(bloomSer);
+ }
+
+ @Override
+ public Set<Pair<String, Long>> filterRowKeys(Set<String> candidateRowKeys) {
+ throw new HoodieException("Filtering row keys from Lance files is not
supported for Flink append-only tables without primary keys: " + path);
+ }
+
+ @Override
+ public ClosableIterator<HoodieRecord<RowData>>
getRecordIterator(HoodieSchema readerSchema, HoodieSchema requestedSchema)
throws IOException {
+ ClosableIterator<RowData> rowDataItr =
getRowDataIterator(RowDataQueryContexts.fromSchema(requestedSchema).getRowType(),
requestedSchema);
+ return new CloseableMappingIterator<>(rowDataItr, HoodieFlinkRecord::new);
+ }
+
+ @Override
+ public ClosableIterator<String> getRecordKeyIterator() throws IOException {
+ HoodieSchema schema = HoodieSchemaUtils.getRecordKeySchema();
+ ClosableIterator<RowData> rowDataItr =
getRowDataIterator(RowDataQueryContexts.fromSchema(schema).getRowType(),
schema);
+ return new CloseableMappingIterator<>(rowDataItr, rowData ->
rowData.getString(0).toString());
+ }
+
+ public ClosableIterator<RowData> getRowDataIterator(DataType dataType,
HoodieSchema requestedSchema) {
+ RowType rowType = (RowType) dataType.getLogicalType();
+ List<String> columnNames = new ArrayList<>(rowType.getFieldCount());
+ for (RowType.RowField field : rowType.getFields()) {
+ columnNames.add(field.getName());
+ }
+ BufferAllocator allocator = HoodieArrowAllocator.newChildAllocator(
+ getClass().getSimpleName() + "-data-" + path.getName(),
dataAllocatorSize);
+ LanceFileReader lanceReader = null;
+ ArrowReader arrowReader = null;
+ try {
+ lanceReader = LanceFileReader.open(path.toString(), allocator);
+ arrowReader = lanceReader.readAll(columnNames, null, DEFAULT_BATCH_SIZE);
+ return new LanceRowDataIterator(allocator, lanceReader, arrowReader,
rowType, this);
+ } catch (Exception e) {
+ if (arrowReader != null) {
+ try {
+ arrowReader.close();
+ } catch (Exception closeException) {
+ e.addSuppressed(closeException);
+ }
+ }
+ if (lanceReader != null) {
+ try {
+ lanceReader.close();
+ } catch (Exception closeException) {
+ e.addSuppressed(closeException);
+ }
+ }
+ allocator.close();
+ throw new HoodieException("Failed to create Lance row iterator for: " +
path, e);
+ }
+ }
+
+ @Override
+ public HoodieSchema getSchema() {
+ RowType rowType = HoodieFlinkLanceArrowUtils.toRowType(arrowSchema);
+ return HoodieSchemaConverter.convertToSchema(rowType);
+ }
+
+ @Override
+ public void close() {
+ if (closed) {
+ return;
+ }
+ closed = true;
+ if (metadataReader != null) {
+ try {
+ metadataReader.close();
+ } catch (Exception e) {
+ // ignore close failure; readers surface data-path exceptions earlier
+ }
+ }
+ if (metadataAllocator != null) {
+ metadataAllocator.close();
+ }
+ }
+
+ @Override
+ public long getTotalRecords() {
+ try {
+ return metadataReader.numRows();
+ } catch (Exception e) {
+ throw new HoodieException("Failed to read row count from Lance file: " +
path, e);
+ }
+ }
+
+ private static class LanceRowDataIterator implements
ClosableIterator<RowData> {
+ private final BufferAllocator allocator;
+ private final LanceFileReader lanceReader;
+ private final ArrowReader arrowReader;
+ private final RowType rowType;
+ private final HoodieRowDataLanceReader reader;
+ private VectorSchemaRoot batch;
+ private List<FieldVector> orderedVectors;
+ private int rowId;
+ private boolean hasNext;
+ private boolean closed;
+
+ private LanceRowDataIterator(
+ BufferAllocator allocator,
+ LanceFileReader lanceReader,
+ ArrowReader arrowReader,
+ RowType rowType,
+ HoodieRowDataLanceReader reader) {
+ this.allocator = allocator;
+ this.lanceReader = lanceReader;
+ this.arrowReader = arrowReader;
+ this.rowType = rowType;
+ this.reader = reader;
+ loadNextBatch();
+ }
+
+ @Override
+ public boolean hasNext() {
+ return hasNext;
+ }
+
+ @Override
+ public RowData next() {
+ RowData rowData = HoodieFlinkLanceArrowUtils.toRowData(rowType,
orderedVectors, rowId++);
+ if (rowId >= batch.getRowCount()) {
+ loadNextBatch();
+ }
+ return rowData;
+ }
+
+ private void loadNextBatch() {
+ try {
+ hasNext = arrowReader.loadNextBatch();
+ if (hasNext) {
+ batch = arrowReader.getVectorSchemaRoot();
+ orderedVectors = orderVectors(rowType, batch.getFieldVectors());
+ rowId = 0;
+ if (batch.getRowCount() == 0) {
Review Comment:
🤖 Recursing into `loadNextBatch()` for empty batches will blow the stack if
a Lance file contains many consecutive empty batches in a row. Could you
convert this to an iterative loop (`do { … } while (hasNext &&
batch.getRowCount() == 0)`)?
<sub><i>- AI-generated; verify before applying. React 👍/👎 to flag
quality.</i></sub>
##########
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/util/StreamerUtil.java:
##########
@@ -275,6 +277,22 @@ public static TypedProperties
flinkConf2TypedProperties(Configuration conf) {
return properties;
}
+ /**
+ * Builds a Lance write config from storage options carried in the Hadoop
configuration.
+ */
+ public static HoodieConfig
getLanceWriteConfig(org.apache.hadoop.conf.Configuration conf) {
+ HoodieConfig hoodieConfig = new HoodieConfig();
Review Comment:
🤖 The method is named `getLanceWriteConfig` but it only carries over
`LANCE_READ_ALLOCATOR_SIZE_BYTES` / `LANCE_READ_METADATA_ALLOCATOR_SIZE_BYTES`,
and the only caller is the reader path in `CopyOnWriteInputFormat`. Worth
renaming to `getLanceReadConfig` (or extending it to also propagate the
write-side allocator/flush/max-file-size keys if a write-side use is planned)?
<sub><i>- AI-generated; verify before applying. React 👍/👎 to flag
quality.</i></sub>
##########
hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/io/storage/row/HoodieRowDataFileWriterFactory.java:
##########
@@ -55,6 +62,30 @@ public HoodieRowDataFileWriterFactory(HoodieStorage storage)
{
super(storage);
}
+ public HoodieFileWriter getFileWriter(String instantTime, StoragePath
storagePath, HoodieWriteConfig config, RowType rowType,
+ TaskContextSupplier taskContextSupplier)
throws IOException {
+ final String extension = FSUtils.getFileExtension(storagePath.getName());
+ return getFileWriterByFormat(extension, instantTime, storagePath, config,
rowType, taskContextSupplier);
+ }
+
+ private <T, I, K, O> HoodieFileWriter getFileWriterByFormat(
Review Comment:
🤖 nit: `<T, I, K, O>` are declared on this method but none of them appear
anywhere in the signature or body — could you drop them?
<sub><i>- AI-generated; verify before applying. React 👍/👎 to flag
quality.</i></sub>
##########
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/util/StreamerUtil.java:
##########
@@ -275,6 +277,22 @@ public static TypedProperties
flinkConf2TypedProperties(Configuration conf) {
return properties;
}
+ /**
+ * Builds a Lance write config from storage options carried in the Hadoop
configuration.
+ */
+ public static HoodieConfig
getLanceWriteConfig(org.apache.hadoop.conf.Configuration conf) {
Review Comment:
🤖 nit: the method body only reads `LANCE_READ_*` config keys, so
`getLanceWriteConfig` is a misleading name — `getLanceReadConfig` would match
what it actually does.
<sub><i>- AI-generated; verify before applying. React 👍/👎 to flag
quality.</i></sub>
##########
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/table/HoodieTableFactory.java:
##########
@@ -220,12 +215,21 @@ private void checkIndexType(Configuration conf) {
}
/**
- * Validate the base file format. Lance is only supported with the Spark
engine.
+ * Validate the base file format. Flink Lance support is scoped to
append-only COW tables.
*/
- private void checkBaseFileFormat(Configuration conf) {
+ private void checkBaseFileFormat(Configuration conf, boolean write) {
Review Comment:
🤖 nit: a bare `boolean write` makes call sites like
`checkBaseFileFormat(conf, false)` opaque — could you split into two methods
(`checkBaseFileFormatForRead` / `checkBaseFileFormatForWrite`) or at least name
it `isWritePath`?
<sub><i>- AI-generated; verify before applying. React 👍/👎 to flag
quality.</i></sub>
##########
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/table/format/FlinkRowDataReaderContext.java:
##########
@@ -98,18 +98,22 @@ public ClosableIterator<RowData> getFileRecordIterator(
HoodieSchema dataSchema,
HoodieSchema requiredSchema,
HoodieStorage storage) throws IOException {
- if
(filePath.toString().endsWith(HoodieFileFormat.LANCE.getFileExtension())) {
- throw new
UnsupportedOperationException(HoodieFileFormat.LANCE_SPARK_ONLY_ERROR_MSG);
- }
boolean isLogFile = FSUtils.isLogFile(filePath);
// disable schema evolution in fileReader if it's log file, since schema
evolution for log file is handled in `FileGroupRecordBuffer`
InternalSchemaManager schemaManager = isLogFile ?
InternalSchemaManager.DISABLED : internalSchemaManager.get();
+ if (HoodieFileFormat.fromFileExtension(filePath.getFileExtension()) ==
HoodieFileFormat.LANCE) {
+ HoodieRowDataLanceReader rowDataLanceReader =
+ (HoodieRowDataLanceReader) HoodieIOFactory.getIOFactory(storage)
+ .getReaderFactory(HoodieRecord.HoodieRecordType.FLINK)
+ .getFileReader(tableConfig, filePath, HoodieFileFormat.LANCE,
Option.empty());
+ return
rowDataLanceReader.getRowDataIterator(RowDataQueryContexts.fromSchema(requiredSchema).getRowType(),
requiredSchema);
Review Comment:
🤖 If `getRowDataIterator(...)` throws (e.g. `loadNextBatch` failure surfaces
as `HoodieIOException`), `rowDataLanceReader` is leaked — the metadata
`LanceFileReader` and `metadataAllocator` from the constructor are never
released, since the parent reader's `close()` is only chained through the
iterator's `close()`. Could you wrap this in a try/catch that closes the reader
on failure (the `CopyOnWriteInputFormat.getLanceRecordIterator` path already
does this)?
<sub><i>- AI-generated; verify before applying. React 👍/👎 to flag
quality.</i></sub>
##########
hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/io/storage/row/HoodieFlinkLanceArrowUtils.java:
##########
@@ -0,0 +1,282 @@
+/*
+ * 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.hudi.io.storage.row;
+
+import org.apache.hudi.exception.HoodieNotSupportedException;
+
+import org.apache.arrow.vector.BigIntVector;
+import org.apache.arrow.vector.BitVector;
+import org.apache.arrow.vector.DateDayVector;
+import org.apache.arrow.vector.DecimalVector;
+import org.apache.arrow.vector.FieldVector;
+import org.apache.arrow.vector.Float4Vector;
+import org.apache.arrow.vector.Float8Vector;
+import org.apache.arrow.vector.IntVector;
+import org.apache.arrow.vector.SmallIntVector;
+import org.apache.arrow.vector.TimeMilliVector;
+import org.apache.arrow.vector.TimeStampMicroVector;
+import org.apache.arrow.vector.TinyIntVector;
+import org.apache.arrow.vector.ValueVector;
+import org.apache.arrow.vector.VarBinaryVector;
+import org.apache.arrow.vector.VarCharVector;
+import org.apache.arrow.vector.types.DateUnit;
+import org.apache.arrow.vector.types.FloatingPointPrecision;
+import org.apache.arrow.vector.types.TimeUnit;
+import org.apache.arrow.vector.types.pojo.ArrowType;
+import org.apache.arrow.vector.types.pojo.Field;
+import org.apache.arrow.vector.types.pojo.FieldType;
+import org.apache.arrow.vector.types.pojo.Schema;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.StringData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.logical.DecimalType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.RowType;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Primitive RowData/Arrow conversion helpers for Flink Lance base files.
+ */
+public final class HoodieFlinkLanceArrowUtils {
+
+ private HoodieFlinkLanceArrowUtils() {
+ }
+
+ public static Schema toArrowSchema(RowType rowType) {
+ List<Field> fields = new ArrayList<>(rowType.getFieldCount());
+ for (RowType.RowField field : rowType.getFields()) {
+ fields.add(toArrowField(field.getName(), field.getType()));
+ }
+ return new Schema(fields);
+ }
+
+ public static RowType toRowType(Schema schema) {
+ List<RowType.RowField> fields = new ArrayList<>(schema.getFields().size());
+ for (Field field : schema.getFields()) {
+ fields.add(new RowType.RowField(field.getName(),
toLogicalType(field.getType())));
+ }
+ return new RowType(fields);
+ }
+
+ public static RowData toRowData(RowType rowType, List<FieldVector> vectors,
int rowId) {
+ GenericRowData rowData = new GenericRowData(vectors.size());
+ for (int i = 0; i < vectors.size(); i++) {
+ FieldVector vector = vectors.get(i);
+ if (vector.isNull(rowId)) {
+ rowData.setField(i, null);
+ } else {
+ rowData.setField(i, readValue(rowType.getTypeAt(i), vector, rowId));
+ }
+ }
+ return rowData;
+ }
+
+ public static void writeValue(LogicalType type, FieldVector vector, int
rowId, RowData rowData, int ordinal) {
+ if (rowData.isNullAt(ordinal)) {
+ vector.setNull(rowId);
+ return;
+ }
+ switch (type.getTypeRoot()) {
+ case BOOLEAN:
+ ((BitVector) vector).setSafe(rowId, rowData.getBoolean(ordinal) ? 1 :
0);
+ return;
+ case TINYINT:
+ ((TinyIntVector) vector).setSafe(rowId, rowData.getByte(ordinal));
+ return;
+ case SMALLINT:
+ ((SmallIntVector) vector).setSafe(rowId, rowData.getShort(ordinal));
+ return;
+ case INTEGER:
+ ((IntVector) vector).setSafe(rowId, rowData.getInt(ordinal));
+ return;
+ case DATE:
+ ((DateDayVector) vector).setSafe(rowId, rowData.getInt(ordinal));
+ return;
+ case TIME_WITHOUT_TIME_ZONE:
+ ((TimeMilliVector) vector).setSafe(rowId, rowData.getInt(ordinal));
+ return;
+ case BIGINT:
+ ((BigIntVector) vector).setSafe(rowId, rowData.getLong(ordinal));
+ return;
+ case FLOAT:
+ ((Float4Vector) vector).setSafe(rowId, rowData.getFloat(ordinal));
+ return;
+ case DOUBLE:
+ ((Float8Vector) vector).setSafe(rowId, rowData.getDouble(ordinal));
+ return;
+ case CHAR:
+ case VARCHAR:
+ ((VarCharVector) vector).setSafe(rowId,
rowData.getString(ordinal).toBytes());
+ return;
+ case BINARY:
+ case VARBINARY:
+ ((VarBinaryVector) vector).setSafe(rowId, rowData.getBinary(ordinal));
+ return;
+ case DECIMAL:
+ DecimalType decimalType = (DecimalType) type;
+ DecimalData decimal = rowData.getDecimal(ordinal,
decimalType.getPrecision(), decimalType.getScale());
+ ((DecimalVector) vector).setSafe(rowId, decimal.toBigDecimal());
+ return;
+ case TIMESTAMP_WITHOUT_TIME_ZONE:
+ case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
+ TimestampData timestamp = rowData.getTimestamp(ordinal,
LogicalTypeChecks.getPrecision(type));
+ long micros = timestamp.getMillisecond() * 1000L +
timestamp.getNanoOfMillisecond() / 1000L;
+ ((TimeStampMicroVector) vector).setSafe(rowId, micros);
+ return;
+ default:
+ throw unsupported(type);
+ }
+ }
+
+ private static Object readValue(LogicalType type, ValueVector vector, int
rowId) {
+ switch (type.getTypeRoot()) {
+ case BOOLEAN:
+ return ((BitVector) vector).get(rowId) == 1;
+ case TINYINT:
+ return ((TinyIntVector) vector).get(rowId);
+ case SMALLINT:
+ return ((SmallIntVector) vector).get(rowId);
+ case INTEGER:
+ return ((IntVector) vector).get(rowId);
+ case DATE:
+ return ((DateDayVector) vector).get(rowId);
+ case TIME_WITHOUT_TIME_ZONE:
+ return ((TimeMilliVector) vector).get(rowId);
+ case BIGINT:
+ return ((BigIntVector) vector).get(rowId);
+ case FLOAT:
+ return ((Float4Vector) vector).get(rowId);
+ case DOUBLE:
+ return ((Float8Vector) vector).get(rowId);
+ case CHAR:
+ case VARCHAR:
+ return StringData.fromBytes(((VarCharVector) vector).get(rowId));
+ case BINARY:
+ case VARBINARY:
+ return ((VarBinaryVector) vector).get(rowId);
+ case DECIMAL:
+ DecimalType decimalType = (DecimalType) type;
+ BigDecimal decimal = ((DecimalVector) vector).getObject(rowId);
+ return DecimalData.fromBigDecimal(decimal, decimalType.getPrecision(),
decimalType.getScale());
+ case TIMESTAMP_WITHOUT_TIME_ZONE:
+ case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
+ long micros = ((TimeStampMicroVector) vector).get(rowId);
+ return TimestampData.fromEpochMillis(micros / 1000L, (int) (micros %
1000L) * 1000);
+ default:
+ throw unsupported(type);
+ }
+ }
+
+ private static Field toArrowField(String name, LogicalType type) {
+ return new Field(name, FieldType.nullable(toArrowType(type)),
Collections.emptyList());
+ }
+
+ private static ArrowType toArrowType(LogicalType type) {
+ switch (type.getTypeRoot()) {
+ case BOOLEAN:
+ return ArrowType.Bool.INSTANCE;
+ case TINYINT:
+ return new ArrowType.Int(8, true);
+ case SMALLINT:
+ return new ArrowType.Int(16, true);
+ case INTEGER:
+ return new ArrowType.Int(32, true);
+ case BIGINT:
+ return new ArrowType.Int(64, true);
+ case FLOAT:
+ return new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE);
+ case DOUBLE:
+ return new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE);
+ case CHAR:
+ case VARCHAR:
+ return ArrowType.Utf8.INSTANCE;
+ case BINARY:
+ case VARBINARY:
+ return ArrowType.Binary.INSTANCE;
+ case DATE:
+ return new ArrowType.Date(DateUnit.DAY);
+ case TIME_WITHOUT_TIME_ZONE:
+ return new ArrowType.Time(TimeUnit.MILLISECOND, 32);
+ case DECIMAL:
+ DecimalType decimalType = (DecimalType) type;
+ return new ArrowType.Decimal(decimalType.getPrecision(),
decimalType.getScale(), 128);
+ case TIMESTAMP_WITHOUT_TIME_ZONE:
+ return new ArrowType.Timestamp(TimeUnit.MICROSECOND, null);
+ case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
+ return new ArrowType.Timestamp(TimeUnit.MICROSECOND, "UTC");
+ default:
+ throw unsupported(type);
+ }
+ }
+
+ private static LogicalType toLogicalType(ArrowType arrowType) {
+ if (arrowType instanceof ArrowType.Bool) {
+ return new org.apache.flink.table.types.logical.BooleanType();
+ } else if (arrowType instanceof ArrowType.Int) {
+ ArrowType.Int intType = (ArrowType.Int) arrowType;
+ switch (intType.getBitWidth()) {
+ case 8:
+ return new org.apache.flink.table.types.logical.TinyIntType();
+ case 16:
+ return new org.apache.flink.table.types.logical.SmallIntType();
+ case 32:
+ return new org.apache.flink.table.types.logical.IntType();
+ case 64:
+ return new org.apache.flink.table.types.logical.BigIntType();
+ default:
+ throw new HoodieNotSupportedException("Unsupported Arrow int width
for Lance Flink reader: " + intType.getBitWidth());
+ }
+ } else if (arrowType instanceof ArrowType.FloatingPoint) {
+ ArrowType.FloatingPoint fp = (ArrowType.FloatingPoint) arrowType;
+ return fp.getPrecision() == FloatingPointPrecision.SINGLE
+ ? new org.apache.flink.table.types.logical.FloatType()
+ : new org.apache.flink.table.types.logical.DoubleType();
+ } else if (arrowType instanceof ArrowType.Utf8) {
+ return new org.apache.flink.table.types.logical.VarCharType();
+ } else if (arrowType instanceof ArrowType.Binary) {
+ return new org.apache.flink.table.types.logical.VarBinaryType();
+ } else if (arrowType instanceof ArrowType.Date) {
+ return new org.apache.flink.table.types.logical.DateType();
+ } else if (arrowType instanceof ArrowType.Time) {
+ return new org.apache.flink.table.types.logical.TimeType();
+ } else if (arrowType instanceof ArrowType.Decimal) {
+ ArrowType.Decimal decimal = (ArrowType.Decimal) arrowType;
+ return new DecimalType(decimal.getPrecision(), decimal.getScale());
+ } else if (arrowType instanceof ArrowType.Timestamp) {
+ return new org.apache.flink.table.types.logical.TimestampType(6);
+ }
+ throw new HoodieNotSupportedException("Unsupported Arrow type for Lance
Flink reader: " + arrowType);
+ }
+
+ private static HoodieNotSupportedException unsupported(LogicalType type) {
+ return new HoodieNotSupportedException("Flink Lance base-file support
currently supports primitive append-only columns; unsupported type: " + type);
+ }
+
+ private static final class LogicalTypeChecks {
Review Comment:
🤖 nit: this private inner class is just a one-liner forwarding to
`org.apache.flink.table.types.logical.utils.LogicalTypeChecks.getPrecision` — a
static import would eliminate the wrapper entirely.
<sub><i>- AI-generated; verify before applying. React 👍/👎 to flag
quality.</i></sub>
##########
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/table/format/HoodieRowDataLanceReader.java:
##########
@@ -0,0 +1,302 @@
+/*
+ * 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.hudi.table.format;
+
+import org.apache.hudi.client.model.HoodieFlinkRecord;
+import org.apache.hudi.common.bloom.BloomFilter;
+import org.apache.hudi.common.bloom.HoodieDynamicBoundedBloomFilter;
+import org.apache.hudi.common.bloom.SimpleBloomFilter;
+import org.apache.hudi.common.config.HoodieConfig;
+import org.apache.hudi.common.config.HoodieStorageConfig;
+import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.common.schema.HoodieSchema;
+import org.apache.hudi.common.schema.HoodieSchemaUtils;
+import org.apache.hudi.common.util.collection.ClosableIterator;
+import org.apache.hudi.common.util.collection.CloseableMappingIterator;
+import org.apache.hudi.common.util.collection.Pair;
+import org.apache.hudi.exception.HoodieException;
+import org.apache.hudi.exception.HoodieIOException;
+import org.apache.hudi.io.memory.HoodieArrowAllocator;
+import org.apache.hudi.io.storage.HoodieFileReader;
+import org.apache.hudi.io.storage.row.HoodieFlinkLanceArrowUtils;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.util.HoodieSchemaConverter;
+import org.apache.hudi.util.RowDataQueryContexts;
+
+import org.apache.arrow.memory.BufferAllocator;
+import org.apache.arrow.vector.FieldVector;
+import org.apache.arrow.vector.VectorSchemaRoot;
+import org.apache.arrow.vector.ipc.ArrowReader;
+import org.apache.arrow.vector.types.pojo.Schema;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.logical.RowType;
+import org.lance.file.LanceFileReader;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static
org.apache.hudi.avro.HoodieBloomFilterWriteSupport.HOODIE_AVRO_BLOOM_FILTER_METADATA_KEY;
+import static
org.apache.hudi.avro.HoodieBloomFilterWriteSupport.HOODIE_BLOOM_FILTER_TYPE_CODE;
+import static
org.apache.hudi.avro.HoodieBloomFilterWriteSupport.HOODIE_MAX_RECORD_KEY_FOOTER;
+import static
org.apache.hudi.avro.HoodieBloomFilterWriteSupport.HOODIE_MIN_RECORD_KEY_FOOTER;
+
+/**
+ * Lance reader for Flink RowData base files.
+ */
+public class HoodieRowDataLanceReader implements HoodieFileReader<RowData> {
+
+ private static final int DEFAULT_BATCH_SIZE = 512;
+
+ private final StoragePath path;
+ private final long dataAllocatorSize;
+ private final BufferAllocator metadataAllocator;
+ private final LanceFileReader metadataReader;
+ private final Schema arrowSchema;
+ private boolean closed;
+
+ public HoodieRowDataLanceReader(StoragePath path, HoodieConfig hoodieConfig)
{
+ this.path = path;
+ this.dataAllocatorSize =
hoodieConfig.getLongOrDefault(HoodieStorageConfig.LANCE_READ_ALLOCATOR_SIZE_BYTES);
+ this.metadataAllocator = HoodieArrowAllocator.newChildAllocator(
+ getClass().getSimpleName() + "-metadata-" + path.getName(),
+
hoodieConfig.getLongOrDefault(HoodieStorageConfig.LANCE_READ_METADATA_ALLOCATOR_SIZE_BYTES));
+ try {
+ this.metadataReader = LanceFileReader.open(path.toString(),
metadataAllocator);
+ this.arrowSchema = metadataReader.schema();
+ } catch (Exception e) {
+ close();
+ throw new HoodieException("Failed to create Lance reader for: " + path,
e);
+ }
+ }
+
+ @Override
+ public String[] readMinMaxRecordKeys() {
+ Map<String, String> metadata = arrowSchema.getCustomMetadata();
+ if (metadata != null) {
+ String minKey = metadata.get(HOODIE_MIN_RECORD_KEY_FOOTER);
+ String maxKey = metadata.get(HOODIE_MAX_RECORD_KEY_FOOTER);
+ if (minKey != null && maxKey != null) {
+ return new String[] {minKey, maxKey};
+ }
+ }
+ throw new HoodieException("Could not read min/max record key out of Lance
file: " + path);
+ }
+
+ @Override
+ public BloomFilter readBloomFilter() {
+ Map<String, String> metadata = arrowSchema.getCustomMetadata();
+ if (metadata == null ||
!metadata.containsKey(HOODIE_AVRO_BLOOM_FILTER_METADATA_KEY)) {
+ return null;
+ }
+ String bloomSer = metadata.get(HOODIE_AVRO_BLOOM_FILTER_METADATA_KEY);
+ String filterType = metadata.get(HOODIE_BLOOM_FILTER_TYPE_CODE);
+ if (filterType != null &&
filterType.contains(HoodieDynamicBoundedBloomFilter.TYPE_CODE_PREFIX)) {
+ return new HoodieDynamicBoundedBloomFilter(bloomSer);
+ }
+ return new SimpleBloomFilter(bloomSer);
+ }
+
+ @Override
+ public Set<Pair<String, Long>> filterRowKeys(Set<String> candidateRowKeys) {
+ throw new HoodieException("Filtering row keys from Lance files is not
supported for Flink append-only tables without primary keys: " + path);
+ }
+
+ @Override
+ public ClosableIterator<HoodieRecord<RowData>>
getRecordIterator(HoodieSchema readerSchema, HoodieSchema requestedSchema)
throws IOException {
+ ClosableIterator<RowData> rowDataItr =
getRowDataIterator(RowDataQueryContexts.fromSchema(requestedSchema).getRowType(),
requestedSchema);
+ return new CloseableMappingIterator<>(rowDataItr, HoodieFlinkRecord::new);
+ }
+
+ @Override
+ public ClosableIterator<String> getRecordKeyIterator() throws IOException {
+ HoodieSchema schema = HoodieSchemaUtils.getRecordKeySchema();
+ ClosableIterator<RowData> rowDataItr =
getRowDataIterator(RowDataQueryContexts.fromSchema(schema).getRowType(),
schema);
+ return new CloseableMappingIterator<>(rowDataItr, rowData ->
rowData.getString(0).toString());
+ }
+
+ public ClosableIterator<RowData> getRowDataIterator(DataType dataType,
HoodieSchema requestedSchema) {
+ RowType rowType = (RowType) dataType.getLogicalType();
+ List<String> columnNames = new ArrayList<>(rowType.getFieldCount());
+ for (RowType.RowField field : rowType.getFields()) {
+ columnNames.add(field.getName());
+ }
+ BufferAllocator allocator = HoodieArrowAllocator.newChildAllocator(
+ getClass().getSimpleName() + "-data-" + path.getName(),
dataAllocatorSize);
+ LanceFileReader lanceReader = null;
+ ArrowReader arrowReader = null;
+ try {
+ lanceReader = LanceFileReader.open(path.toString(), allocator);
+ arrowReader = lanceReader.readAll(columnNames, null, DEFAULT_BATCH_SIZE);
+ return new LanceRowDataIterator(allocator, lanceReader, arrowReader,
rowType, this);
+ } catch (Exception e) {
+ if (arrowReader != null) {
+ try {
+ arrowReader.close();
+ } catch (Exception closeException) {
+ e.addSuppressed(closeException);
+ }
+ }
+ if (lanceReader != null) {
+ try {
+ lanceReader.close();
+ } catch (Exception closeException) {
+ e.addSuppressed(closeException);
+ }
+ }
+ allocator.close();
+ throw new HoodieException("Failed to create Lance row iterator for: " +
path, e);
+ }
+ }
+
+ @Override
+ public HoodieSchema getSchema() {
+ RowType rowType = HoodieFlinkLanceArrowUtils.toRowType(arrowSchema);
+ return HoodieSchemaConverter.convertToSchema(rowType);
+ }
+
+ @Override
+ public void close() {
+ if (closed) {
+ return;
+ }
+ closed = true;
+ if (metadataReader != null) {
+ try {
+ metadataReader.close();
+ } catch (Exception e) {
+ // ignore close failure; readers surface data-path exceptions earlier
+ }
+ }
+ if (metadataAllocator != null) {
+ metadataAllocator.close();
+ }
+ }
+
+ @Override
+ public long getTotalRecords() {
+ try {
+ return metadataReader.numRows();
+ } catch (Exception e) {
+ throw new HoodieException("Failed to read row count from Lance file: " +
path, e);
+ }
+ }
+
+ private static class LanceRowDataIterator implements
ClosableIterator<RowData> {
+ private final BufferAllocator allocator;
+ private final LanceFileReader lanceReader;
+ private final ArrowReader arrowReader;
+ private final RowType rowType;
+ private final HoodieRowDataLanceReader reader;
+ private VectorSchemaRoot batch;
+ private List<FieldVector> orderedVectors;
+ private int rowId;
+ private boolean hasNext;
+ private boolean closed;
+
+ private LanceRowDataIterator(
+ BufferAllocator allocator,
+ LanceFileReader lanceReader,
+ ArrowReader arrowReader,
+ RowType rowType,
+ HoodieRowDataLanceReader reader) {
+ this.allocator = allocator;
+ this.lanceReader = lanceReader;
+ this.arrowReader = arrowReader;
+ this.rowType = rowType;
+ this.reader = reader;
+ loadNextBatch();
+ }
+
+ @Override
+ public boolean hasNext() {
+ return hasNext;
+ }
+
+ @Override
+ public RowData next() {
+ RowData rowData = HoodieFlinkLanceArrowUtils.toRowData(rowType,
orderedVectors, rowId++);
+ if (rowId >= batch.getRowCount()) {
+ loadNextBatch();
+ }
+ return rowData;
+ }
+
+ private void loadNextBatch() {
+ try {
+ hasNext = arrowReader.loadNextBatch();
+ if (hasNext) {
+ batch = arrowReader.getVectorSchemaRoot();
+ orderedVectors = orderVectors(rowType, batch.getFieldVectors());
+ rowId = 0;
+ if (batch.getRowCount() == 0) {
+ loadNextBatch();
+ }
+ }
+ } catch (IOException e) {
+ throw new HoodieIOException("Failed to read Lance batch", e);
+ }
+ }
+
+ private static List<FieldVector> orderVectors(RowType rowType,
List<FieldVector> vectors) {
+ Map<String, FieldVector> vectorsByName = new HashMap<>();
+ for (FieldVector vector : vectors) {
+ vectorsByName.put(vector.getName(), vector);
+ }
+ List<FieldVector> orderedVectors = new
ArrayList<>(rowType.getFieldCount());
+ for (RowType.RowField field : rowType.getFields()) {
+ FieldVector vector = vectorsByName.get(field.getName());
+ if (vector == null) {
+ throw new HoodieException("Missing Lance column in projected batch:
" + field.getName());
+ }
+ orderedVectors.add(vector);
+ }
+ return orderedVectors;
+ }
+
+ @Override
+ public void close() {
+ if (closed) {
+ return;
+ }
+ closed = true;
+ try {
+ arrowReader.close();
+ } catch (Exception e) {
+ throw new HoodieException("Failed to close Lance Arrow reader", e);
Review Comment:
🤖 If `arrowReader.close()` throws, the throw inside the outer `finally` for
`lanceReader.close()` (or `reader.close()` inside the innermost finally) will
replace it and the original exception is lost — `finally`-throws override
exceptions from the `try` body. Could you switch to the `addSuppressed` pattern
(e.g. accumulate a primary exception across all four closes)? The Spark
equivalent uses log-and-swallow which avoids this entirely.
<sub><i>- AI-generated; verify before applying. React 👍/👎 to flag
quality.</i></sub>
##########
hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/io/storage/row/HoodieFlinkLanceArrowUtils.java:
##########
@@ -0,0 +1,282 @@
+/*
+ * 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.hudi.io.storage.row;
+
+import org.apache.hudi.exception.HoodieNotSupportedException;
+
+import org.apache.arrow.vector.BigIntVector;
+import org.apache.arrow.vector.BitVector;
+import org.apache.arrow.vector.DateDayVector;
+import org.apache.arrow.vector.DecimalVector;
+import org.apache.arrow.vector.FieldVector;
+import org.apache.arrow.vector.Float4Vector;
+import org.apache.arrow.vector.Float8Vector;
+import org.apache.arrow.vector.IntVector;
+import org.apache.arrow.vector.SmallIntVector;
+import org.apache.arrow.vector.TimeMilliVector;
+import org.apache.arrow.vector.TimeStampMicroVector;
+import org.apache.arrow.vector.TinyIntVector;
+import org.apache.arrow.vector.ValueVector;
+import org.apache.arrow.vector.VarBinaryVector;
+import org.apache.arrow.vector.VarCharVector;
+import org.apache.arrow.vector.types.DateUnit;
+import org.apache.arrow.vector.types.FloatingPointPrecision;
+import org.apache.arrow.vector.types.TimeUnit;
+import org.apache.arrow.vector.types.pojo.ArrowType;
+import org.apache.arrow.vector.types.pojo.Field;
+import org.apache.arrow.vector.types.pojo.FieldType;
+import org.apache.arrow.vector.types.pojo.Schema;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.StringData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.logical.DecimalType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.RowType;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Primitive RowData/Arrow conversion helpers for Flink Lance base files.
+ */
+public final class HoodieFlinkLanceArrowUtils {
+
+ private HoodieFlinkLanceArrowUtils() {
+ }
+
+ public static Schema toArrowSchema(RowType rowType) {
+ List<Field> fields = new ArrayList<>(rowType.getFieldCount());
+ for (RowType.RowField field : rowType.getFields()) {
+ fields.add(toArrowField(field.getName(), field.getType()));
+ }
+ return new Schema(fields);
+ }
+
+ public static RowType toRowType(Schema schema) {
+ List<RowType.RowField> fields = new ArrayList<>(schema.getFields().size());
+ for (Field field : schema.getFields()) {
+ fields.add(new RowType.RowField(field.getName(),
toLogicalType(field.getType())));
+ }
+ return new RowType(fields);
+ }
+
+ public static RowData toRowData(RowType rowType, List<FieldVector> vectors,
int rowId) {
+ GenericRowData rowData = new GenericRowData(vectors.size());
+ for (int i = 0; i < vectors.size(); i++) {
+ FieldVector vector = vectors.get(i);
+ if (vector.isNull(rowId)) {
+ rowData.setField(i, null);
+ } else {
+ rowData.setField(i, readValue(rowType.getTypeAt(i), vector, rowId));
+ }
+ }
+ return rowData;
+ }
+
+ public static void writeValue(LogicalType type, FieldVector vector, int
rowId, RowData rowData, int ordinal) {
+ if (rowData.isNullAt(ordinal)) {
+ vector.setNull(rowId);
+ return;
+ }
+ switch (type.getTypeRoot()) {
+ case BOOLEAN:
+ ((BitVector) vector).setSafe(rowId, rowData.getBoolean(ordinal) ? 1 :
0);
+ return;
+ case TINYINT:
+ ((TinyIntVector) vector).setSafe(rowId, rowData.getByte(ordinal));
+ return;
+ case SMALLINT:
+ ((SmallIntVector) vector).setSafe(rowId, rowData.getShort(ordinal));
+ return;
+ case INTEGER:
+ ((IntVector) vector).setSafe(rowId, rowData.getInt(ordinal));
+ return;
+ case DATE:
+ ((DateDayVector) vector).setSafe(rowId, rowData.getInt(ordinal));
+ return;
+ case TIME_WITHOUT_TIME_ZONE:
+ ((TimeMilliVector) vector).setSafe(rowId, rowData.getInt(ordinal));
+ return;
+ case BIGINT:
+ ((BigIntVector) vector).setSafe(rowId, rowData.getLong(ordinal));
+ return;
+ case FLOAT:
+ ((Float4Vector) vector).setSafe(rowId, rowData.getFloat(ordinal));
+ return;
+ case DOUBLE:
+ ((Float8Vector) vector).setSafe(rowId, rowData.getDouble(ordinal));
+ return;
+ case CHAR:
+ case VARCHAR:
+ ((VarCharVector) vector).setSafe(rowId,
rowData.getString(ordinal).toBytes());
+ return;
+ case BINARY:
+ case VARBINARY:
+ ((VarBinaryVector) vector).setSafe(rowId, rowData.getBinary(ordinal));
+ return;
+ case DECIMAL:
+ DecimalType decimalType = (DecimalType) type;
+ DecimalData decimal = rowData.getDecimal(ordinal,
decimalType.getPrecision(), decimalType.getScale());
+ ((DecimalVector) vector).setSafe(rowId, decimal.toBigDecimal());
+ return;
+ case TIMESTAMP_WITHOUT_TIME_ZONE:
+ case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
+ TimestampData timestamp = rowData.getTimestamp(ordinal,
LogicalTypeChecks.getPrecision(type));
+ long micros = timestamp.getMillisecond() * 1000L +
timestamp.getNanoOfMillisecond() / 1000L;
+ ((TimeStampMicroVector) vector).setSafe(rowId, micros);
+ return;
+ default:
+ throw unsupported(type);
+ }
+ }
+
+ private static Object readValue(LogicalType type, ValueVector vector, int
rowId) {
+ switch (type.getTypeRoot()) {
+ case BOOLEAN:
+ return ((BitVector) vector).get(rowId) == 1;
+ case TINYINT:
+ return ((TinyIntVector) vector).get(rowId);
+ case SMALLINT:
+ return ((SmallIntVector) vector).get(rowId);
+ case INTEGER:
+ return ((IntVector) vector).get(rowId);
+ case DATE:
+ return ((DateDayVector) vector).get(rowId);
+ case TIME_WITHOUT_TIME_ZONE:
+ return ((TimeMilliVector) vector).get(rowId);
+ case BIGINT:
+ return ((BigIntVector) vector).get(rowId);
+ case FLOAT:
+ return ((Float4Vector) vector).get(rowId);
+ case DOUBLE:
+ return ((Float8Vector) vector).get(rowId);
+ case CHAR:
+ case VARCHAR:
+ return StringData.fromBytes(((VarCharVector) vector).get(rowId));
+ case BINARY:
+ case VARBINARY:
+ return ((VarBinaryVector) vector).get(rowId);
+ case DECIMAL:
+ DecimalType decimalType = (DecimalType) type;
+ BigDecimal decimal = ((DecimalVector) vector).getObject(rowId);
+ return DecimalData.fromBigDecimal(decimal, decimalType.getPrecision(),
decimalType.getScale());
+ case TIMESTAMP_WITHOUT_TIME_ZONE:
+ case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
+ long micros = ((TimeStampMicroVector) vector).get(rowId);
+ return TimestampData.fromEpochMillis(micros / 1000L, (int) (micros %
1000L) * 1000);
+ default:
+ throw unsupported(type);
+ }
+ }
+
+ private static Field toArrowField(String name, LogicalType type) {
+ return new Field(name, FieldType.nullable(toArrowType(type)),
Collections.emptyList());
+ }
+
+ private static ArrowType toArrowType(LogicalType type) {
+ switch (type.getTypeRoot()) {
+ case BOOLEAN:
+ return ArrowType.Bool.INSTANCE;
+ case TINYINT:
+ return new ArrowType.Int(8, true);
+ case SMALLINT:
+ return new ArrowType.Int(16, true);
+ case INTEGER:
+ return new ArrowType.Int(32, true);
+ case BIGINT:
+ return new ArrowType.Int(64, true);
+ case FLOAT:
+ return new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE);
+ case DOUBLE:
+ return new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE);
+ case CHAR:
+ case VARCHAR:
+ return ArrowType.Utf8.INSTANCE;
+ case BINARY:
+ case VARBINARY:
+ return ArrowType.Binary.INSTANCE;
+ case DATE:
+ return new ArrowType.Date(DateUnit.DAY);
+ case TIME_WITHOUT_TIME_ZONE:
+ return new ArrowType.Time(TimeUnit.MILLISECOND, 32);
+ case DECIMAL:
+ DecimalType decimalType = (DecimalType) type;
+ return new ArrowType.Decimal(decimalType.getPrecision(),
decimalType.getScale(), 128);
+ case TIMESTAMP_WITHOUT_TIME_ZONE:
+ return new ArrowType.Timestamp(TimeUnit.MICROSECOND, null);
+ case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
+ return new ArrowType.Timestamp(TimeUnit.MICROSECOND, "UTC");
+ default:
+ throw unsupported(type);
+ }
+ }
+
+ private static LogicalType toLogicalType(ArrowType arrowType) {
+ if (arrowType instanceof ArrowType.Bool) {
+ return new org.apache.flink.table.types.logical.BooleanType();
+ } else if (arrowType instanceof ArrowType.Int) {
+ ArrowType.Int intType = (ArrowType.Int) arrowType;
+ switch (intType.getBitWidth()) {
+ case 8:
+ return new org.apache.flink.table.types.logical.TinyIntType();
+ case 16:
+ return new org.apache.flink.table.types.logical.SmallIntType();
+ case 32:
+ return new org.apache.flink.table.types.logical.IntType();
+ case 64:
+ return new org.apache.flink.table.types.logical.BigIntType();
+ default:
+ throw new HoodieNotSupportedException("Unsupported Arrow int width
for Lance Flink reader: " + intType.getBitWidth());
+ }
+ } else if (arrowType instanceof ArrowType.FloatingPoint) {
+ ArrowType.FloatingPoint fp = (ArrowType.FloatingPoint) arrowType;
+ return fp.getPrecision() == FloatingPointPrecision.SINGLE
+ ? new org.apache.flink.table.types.logical.FloatType()
+ : new org.apache.flink.table.types.logical.DoubleType();
+ } else if (arrowType instanceof ArrowType.Utf8) {
+ return new org.apache.flink.table.types.logical.VarCharType();
+ } else if (arrowType instanceof ArrowType.Binary) {
+ return new org.apache.flink.table.types.logical.VarBinaryType();
+ } else if (arrowType instanceof ArrowType.Date) {
+ return new org.apache.flink.table.types.logical.DateType();
+ } else if (arrowType instanceof ArrowType.Time) {
+ return new org.apache.flink.table.types.logical.TimeType();
+ } else if (arrowType instanceof ArrowType.Decimal) {
+ ArrowType.Decimal decimal = (ArrowType.Decimal) arrowType;
+ return new DecimalType(decimal.getPrecision(), decimal.getScale());
+ } else if (arrowType instanceof ArrowType.Timestamp) {
+ return new org.apache.flink.table.types.logical.TimestampType(6);
Review Comment:
🤖 `toLogicalType` maps every `ArrowType.Timestamp` to `TimestampType(6)`,
even when the Arrow timezone is `"UTC"` (which the writer uses for
`TIMESTAMP_WITH_LOCAL_TIME_ZONE`). Is that intentional, or should the
timezone-set case map to `LocalZonedTimestampType(6)` so schema round-trips?
Today `HoodieRowDataLanceReader.getSchema()` would silently lose the
local-zone-ness.
<sub><i>- AI-generated; verify before applying. React 👍/👎 to flag
quality.</i></sub>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]