You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iceberg.apache.org by st...@apache.org on 2023/01/20 16:29:22 UTC

[iceberg] branch master updated: Flink: support reading as Avro GenericRecord for FLIP-27 IcebergSource (#6584)

This is an automated email from the ASF dual-hosted git repository.

stevenwu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iceberg.git


The following commit(s) were added to refs/heads/master by this push:
     new eae322d203 Flink: support reading as Avro GenericRecord for FLIP-27 IcebergSource (#6584)
eae322d203 is described below

commit eae322d2038ab18ddee022ea97fcd8e7d1a38d19
Author: Steven Zhen Wu <st...@gmail.com>
AuthorDate: Fri Jan 20 08:29:15 2023 -0800

    Flink: support reading as Avro GenericRecord for FLIP-27 IcebergSource (#6584)
---
 docs/flink-getting-started.md                      |  32 ++++
 .../AvroGenericRecordFileScanTaskReader.java       |  42 +++++
 .../RowDataToAvroGenericRecordConverter.java       |  70 +++++++
 .../reader/AvroGenericRecordReaderFunction.java    |  98 ++++++++++
 .../flink/source/reader/ListBatchRecords.java      |  85 +++++++++
 .../source/reader/ListDataIteratorBatcher.java     |  94 ++++++++++
 .../org/apache/iceberg/flink/DataGenerators.java   |   2 +-
 .../TestRowDataToAvroGenericRecordConverter.java   |  34 ++++
 .../TestIcebergSourceBoundedGenericRecord.java     | 202 +++++++++++++++++++++
 9 files changed, 658 insertions(+), 1 deletion(-)

diff --git a/docs/flink-getting-started.md b/docs/flink-getting-started.md
index d0a31ec200..af2459f222 100644
--- a/docs/flink-getting-started.md
+++ b/docs/flink-getting-started.md
@@ -613,6 +613,38 @@ env.execute("Test Iceberg Streaming Read");
 There are other options that we could set by Java API, please see the 
 [IcebergSource#Builder](../../../javadoc/{{% icebergVersion %}}/org/apache/iceberg/flink/source/IcebergSource.html).
 
+### Read as Avro GenericRecord
+
+FLIP-27 Iceberg source provides `AvroGenericRecordReaderFunction` that converts
+Flink `RowData` Avro `GenericRecord`. You can use the convert to read from
+Iceberg table as Avro GenericRecord DataStream.
+
+Please make sure `flink-avro` jar is included in the classpath.
+Also `iceberg-flink-runtime` shaded bundle jar can't be used
+because the runtime jar shades the avro package.
+Please use non-shaded `iceberg-flink` jar instead.
+
+```java
+TableLoader tableLoader = ...;
+Table table;
+try (TableLoader loader = tableLoader) {
+    loader.open();
+    table = loader.loadTable();
+}
+
+AvroGenericRecordReaderFunction readerFunction = AvroGenericRecordReaderFunction.fromTable(table);
+
+IcebergSource<GenericRecord> source =
+    IcebergSource.<GenericRecord>builder()
+        .tableLoader(tableLoader)
+        .readerFunction(readerFunction)
+        .assignerFactory(new SimpleSplitAssignerFactory())
+        ...
+        .build();
+
+DataStream<Row> stream = env.fromSource(source, WatermarkStrategy.noWatermarks(),
+    "Iceberg Source as Avro GenericRecord", new GenericRecordAvroTypeInfo(avroSchema));
+```
 
 ## Writing with DataStream
 
diff --git a/flink/v1.16/flink/src/main/java/org/apache/iceberg/flink/source/AvroGenericRecordFileScanTaskReader.java b/flink/v1.16/flink/src/main/java/org/apache/iceberg/flink/source/AvroGenericRecordFileScanTaskReader.java
new file mode 100644
index 0000000000..796434c451
--- /dev/null
+++ b/flink/v1.16/flink/src/main/java/org/apache/iceberg/flink/source/AvroGenericRecordFileScanTaskReader.java
@@ -0,0 +1,42 @@
+/*
+ * 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.iceberg.flink.source;
+
+import org.apache.avro.generic.GenericRecord;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.encryption.InputFilesDecryptor;
+import org.apache.iceberg.io.CloseableIterator;
+
+public class AvroGenericRecordFileScanTaskReader implements FileScanTaskReader<GenericRecord> {
+  private final RowDataFileScanTaskReader rowDataReader;
+  private final RowDataToAvroGenericRecordConverter converter;
+
+  public AvroGenericRecordFileScanTaskReader(
+      RowDataFileScanTaskReader rowDataReader, RowDataToAvroGenericRecordConverter converter) {
+    this.rowDataReader = rowDataReader;
+    this.converter = converter;
+  }
+
+  @Override
+  public CloseableIterator<GenericRecord> open(
+      FileScanTask fileScanTask, InputFilesDecryptor inputFilesDecryptor) {
+    return CloseableIterator.transform(
+        rowDataReader.open(fileScanTask, inputFilesDecryptor), converter);
+  }
+}
diff --git a/flink/v1.16/flink/src/main/java/org/apache/iceberg/flink/source/RowDataToAvroGenericRecordConverter.java b/flink/v1.16/flink/src/main/java/org/apache/iceberg/flink/source/RowDataToAvroGenericRecordConverter.java
new file mode 100644
index 0000000000..8f95e3e554
--- /dev/null
+++ b/flink/v1.16/flink/src/main/java/org/apache/iceberg/flink/source/RowDataToAvroGenericRecordConverter.java
@@ -0,0 +1,70 @@
+/*
+ * 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.iceberg.flink.source;
+
+import java.io.Serializable;
+import java.util.function.Function;
+import org.apache.avro.Schema;
+import org.apache.avro.generic.GenericRecord;
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.formats.avro.RowDataToAvroConverters;
+import org.apache.flink.formats.avro.typeutils.AvroSchemaConverter;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.table.types.utils.TypeConversions;
+import org.apache.iceberg.avro.AvroSchemaUtil;
+import org.apache.iceberg.flink.FlinkSchemaUtil;
+
+/**
+ * This is not serializable because Avro {@link Schema} is not actually serializable, even though it
+ * implements {@link Serializable} interface.
+ */
+@Internal
+public class RowDataToAvroGenericRecordConverter implements Function<RowData, GenericRecord> {
+  private final RowDataToAvroConverters.RowDataToAvroConverter converter;
+  private final Schema avroSchema;
+
+  private RowDataToAvroGenericRecordConverter(RowType rowType, Schema avroSchema) {
+    this.converter = RowDataToAvroConverters.createConverter(rowType);
+    this.avroSchema = avroSchema;
+  }
+
+  @Override
+  public GenericRecord apply(RowData rowData) {
+    return (GenericRecord) converter.convert(avroSchema, rowData);
+  }
+
+  /** Create a converter based on Iceberg schema */
+  public static RowDataToAvroGenericRecordConverter fromIcebergSchema(
+      String tableName, org.apache.iceberg.Schema icebergSchema) {
+    RowType rowType = FlinkSchemaUtil.convert(icebergSchema);
+    Schema avroSchema = AvroSchemaUtil.convert(icebergSchema, tableName);
+    return new RowDataToAvroGenericRecordConverter(rowType, avroSchema);
+  }
+
+  /** Create a mapper based on Avro schema */
+  public static RowDataToAvroGenericRecordConverter fromAvroSchema(Schema avroSchema) {
+    DataType dataType = AvroSchemaConverter.convertToDataType(avroSchema.toString());
+    LogicalType logicalType = TypeConversions.fromDataToLogicalType(dataType);
+    RowType rowType = RowType.of(logicalType.getChildren().stream().toArray(LogicalType[]::new));
+    return new RowDataToAvroGenericRecordConverter(rowType, avroSchema);
+  }
+}
diff --git a/flink/v1.16/flink/src/main/java/org/apache/iceberg/flink/source/reader/AvroGenericRecordReaderFunction.java b/flink/v1.16/flink/src/main/java/org/apache/iceberg/flink/source/reader/AvroGenericRecordReaderFunction.java
new file mode 100644
index 0000000000..66c0e0ff23
--- /dev/null
+++ b/flink/v1.16/flink/src/main/java/org/apache/iceberg/flink/source/reader/AvroGenericRecordReaderFunction.java
@@ -0,0 +1,98 @@
+/*
+ * 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.iceberg.flink.source.reader;
+
+import org.apache.avro.generic.GenericRecord;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.configuration.ReadableConfig;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.encryption.EncryptionManager;
+import org.apache.iceberg.flink.source.AvroGenericRecordFileScanTaskReader;
+import org.apache.iceberg.flink.source.DataIterator;
+import org.apache.iceberg.flink.source.RowDataFileScanTaskReader;
+import org.apache.iceberg.flink.source.RowDataToAvroGenericRecordConverter;
+import org.apache.iceberg.flink.source.split.IcebergSourceSplit;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+
+/** Read Iceberg rows as {@link GenericRecord}. */
+public class AvroGenericRecordReaderFunction extends DataIteratorReaderFunction<GenericRecord> {
+  private final String tableName;
+  private final Schema readSchema;
+  private final FileIO io;
+  private final EncryptionManager encryption;
+  private final RowDataFileScanTaskReader rowDataReader;
+
+  private transient RowDataToAvroGenericRecordConverter converter;
+
+  /**
+   * Create a reader function without projection and name mapping. Column name is case-insensitive.
+   */
+  public static AvroGenericRecordReaderFunction fromTable(Table table) {
+    return new AvroGenericRecordReaderFunction(
+        table.name(),
+        new Configuration(),
+        table.schema(),
+        null,
+        null,
+        false,
+        table.io(),
+        table.encryption());
+  }
+
+  public AvroGenericRecordReaderFunction(
+      String tableName,
+      ReadableConfig config,
+      Schema tableSchema,
+      Schema projectedSchema,
+      String nameMapping,
+      boolean caseSensitive,
+      FileIO io,
+      EncryptionManager encryption) {
+    super(new ListDataIteratorBatcher<>(config));
+    this.tableName = tableName;
+    this.readSchema = readSchema(tableSchema, projectedSchema);
+    this.io = io;
+    this.encryption = encryption;
+    this.rowDataReader =
+        new RowDataFileScanTaskReader(tableSchema, readSchema, nameMapping, caseSensitive);
+  }
+
+  @Override
+  protected DataIterator<GenericRecord> createDataIterator(IcebergSourceSplit split) {
+    return new DataIterator<>(
+        new AvroGenericRecordFileScanTaskReader(rowDataReader, lazyConverter()),
+        split.task(),
+        io,
+        encryption);
+  }
+
+  private RowDataToAvroGenericRecordConverter lazyConverter() {
+    if (converter == null) {
+      this.converter = RowDataToAvroGenericRecordConverter.fromIcebergSchema(tableName, readSchema);
+    }
+    return converter;
+  }
+
+  private static Schema readSchema(Schema tableSchema, Schema projectedSchema) {
+    Preconditions.checkNotNull(tableSchema, "Table schema can't be null");
+    return projectedSchema == null ? tableSchema : projectedSchema;
+  }
+}
diff --git a/flink/v1.16/flink/src/main/java/org/apache/iceberg/flink/source/reader/ListBatchRecords.java b/flink/v1.16/flink/src/main/java/org/apache/iceberg/flink/source/reader/ListBatchRecords.java
new file mode 100644
index 0000000000..1acb3df761
--- /dev/null
+++ b/flink/v1.16/flink/src/main/java/org/apache/iceberg/flink/source/reader/ListBatchRecords.java
@@ -0,0 +1,85 @@
+/*
+ * 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.iceberg.flink.source.reader;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import javax.annotation.Nullable;
+import org.apache.flink.connector.base.source.reader.RecordsWithSplitIds;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+
+class ListBatchRecords<T> implements RecordsWithSplitIds<RecordAndPosition<T>> {
+  private String splitId;
+  private final List<T> records;
+  private final Set<String> finishedSplits;
+  private final RecordAndPosition<T> recordAndPosition;
+
+  // point to current read position within the records list
+  private int position;
+
+  ListBatchRecords(
+      String splitId,
+      List<T> records,
+      int fileOffset,
+      long startingRecordOffset,
+      Set<String> finishedSplits) {
+    this.splitId = splitId;
+    this.records = records;
+    this.finishedSplits =
+        Preconditions.checkNotNull(finishedSplits, "finishedSplits can be empty but not null");
+    this.recordAndPosition = new RecordAndPosition<>();
+    this.recordAndPosition.set(null, fileOffset, startingRecordOffset);
+
+    this.position = 0;
+  }
+
+  @Nullable
+  @Override
+  public String nextSplit() {
+    String nextSplit = this.splitId;
+    // set the splitId to null to indicate no more splits
+    // this class only contains record for one split
+    this.splitId = null;
+    return nextSplit;
+  }
+
+  @Nullable
+  @Override
+  public RecordAndPosition<T> nextRecordFromSplit() {
+    if (position < records.size()) {
+      recordAndPosition.record(records.get(position));
+      position++;
+      return recordAndPosition;
+    } else {
+      return null;
+    }
+  }
+
+  @Override
+  public Set<String> finishedSplits() {
+    return finishedSplits;
+  }
+
+  public static <T> ListBatchRecords<T> forRecords(
+      String splitId, List<T> records, int fileOffset, long startingRecordOffset) {
+    return new ListBatchRecords<>(
+        splitId, records, fileOffset, startingRecordOffset, Collections.emptySet());
+  }
+}
diff --git a/flink/v1.16/flink/src/main/java/org/apache/iceberg/flink/source/reader/ListDataIteratorBatcher.java b/flink/v1.16/flink/src/main/java/org/apache/iceberg/flink/source/reader/ListDataIteratorBatcher.java
new file mode 100644
index 0000000000..365416239d
--- /dev/null
+++ b/flink/v1.16/flink/src/main/java/org/apache/iceberg/flink/source/reader/ListDataIteratorBatcher.java
@@ -0,0 +1,94 @@
+/*
+ * 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.iceberg.flink.source.reader;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.NoSuchElementException;
+import org.apache.flink.configuration.ReadableConfig;
+import org.apache.flink.connector.base.source.reader.RecordsWithSplitIds;
+import org.apache.iceberg.flink.FlinkConfigOptions;
+import org.apache.iceberg.flink.source.DataIterator;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+
+/**
+ * FlinkRecordReaderFunction essentially cloned objects already. So there is no need to use array
+ * pool to clone objects. Simply create a new ArrayList for each batch.
+ */
+class ListDataIteratorBatcher<T> implements DataIteratorBatcher<T> {
+
+  private final int batchSize;
+
+  ListDataIteratorBatcher(ReadableConfig config) {
+    this.batchSize = config.get(FlinkConfigOptions.SOURCE_READER_FETCH_BATCH_RECORD_COUNT);
+  }
+
+  @Override
+  public CloseableIterator<RecordsWithSplitIds<RecordAndPosition<T>>> batch(
+      String splitId, DataIterator<T> dataIterator) {
+    return new ListBatchIterator(splitId, dataIterator);
+  }
+
+  private class ListBatchIterator
+      implements CloseableIterator<RecordsWithSplitIds<RecordAndPosition<T>>> {
+
+    private final String splitId;
+    private final DataIterator<T> inputIterator;
+
+    ListBatchIterator(String splitId, DataIterator<T> inputIterator) {
+      this.splitId = splitId;
+      this.inputIterator = inputIterator;
+    }
+
+    @Override
+    public boolean hasNext() {
+      return inputIterator.hasNext();
+    }
+
+    @Override
+    public RecordsWithSplitIds<RecordAndPosition<T>> next() {
+      if (!inputIterator.hasNext()) {
+        throw new NoSuchElementException();
+      }
+
+      final List<T> batch = Lists.newArrayListWithCapacity(batchSize);
+      int recordCount = 0;
+      while (inputIterator.hasNext() && recordCount < batchSize) {
+        T nextRecord = inputIterator.next();
+        batch.add(nextRecord);
+        recordCount++;
+        if (!inputIterator.currentFileHasNext()) {
+          // break early so that records have the same fileOffset.
+          break;
+        }
+      }
+
+      return ListBatchRecords.forRecords(
+          splitId, batch, inputIterator.fileOffset(), inputIterator.recordOffset() - recordCount);
+    }
+
+    @Override
+    public void close() throws IOException {
+      if (inputIterator != null) {
+        inputIterator.close();
+      }
+    }
+  }
+}
diff --git a/flink/v1.16/flink/src/test/java/org/apache/iceberg/flink/DataGenerators.java b/flink/v1.16/flink/src/test/java/org/apache/iceberg/flink/DataGenerators.java
index 04fec49b73..367afb75f9 100644
--- a/flink/v1.16/flink/src/test/java/org/apache/iceberg/flink/DataGenerators.java
+++ b/flink/v1.16/flink/src/test/java/org/apache/iceberg/flink/DataGenerators.java
@@ -259,7 +259,7 @@ public class DataGenerators {
       // Flink for decimal type
       genericRecord.put("decimal_field", ByteBuffer.wrap(bigDecimal.unscaledValue().toByteArray()));
 
-      genericRecord.put("fixed_field", FIXED_BYTES);
+      genericRecord.put("fixed_field", ByteBuffer.wrap(FIXED_BYTES));
 
       return genericRecord;
     }
diff --git a/flink/v1.16/flink/src/test/java/org/apache/iceberg/flink/TestRowDataToAvroGenericRecordConverter.java b/flink/v1.16/flink/src/test/java/org/apache/iceberg/flink/TestRowDataToAvroGenericRecordConverter.java
new file mode 100644
index 0000000000..fc53ce4789
--- /dev/null
+++ b/flink/v1.16/flink/src/test/java/org/apache/iceberg/flink/TestRowDataToAvroGenericRecordConverter.java
@@ -0,0 +1,34 @@
+/*
+ * 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.iceberg.flink;
+
+import org.apache.avro.generic.GenericRecord;
+import org.apache.iceberg.flink.source.RowDataToAvroGenericRecordConverter;
+import org.junit.Assert;
+
+public class TestRowDataToAvroGenericRecordConverter extends AvroGenericRecordConverterBase {
+  @Override
+  protected void testConverter(DataGenerator dataGenerator) {
+    RowDataToAvroGenericRecordConverter converter =
+        RowDataToAvroGenericRecordConverter.fromAvroSchema(dataGenerator.avroSchema());
+    GenericRecord expected = dataGenerator.generateAvroGenericRecord();
+    GenericRecord actual = converter.apply(dataGenerator.generateFlinkRowData());
+    Assert.assertEquals(expected, actual);
+  }
+}
diff --git a/flink/v1.16/flink/src/test/java/org/apache/iceberg/flink/source/TestIcebergSourceBoundedGenericRecord.java b/flink/v1.16/flink/src/test/java/org/apache/iceberg/flink/source/TestIcebergSourceBoundedGenericRecord.java
new file mode 100644
index 0000000000..4ffd92acee
--- /dev/null
+++ b/flink/v1.16/flink/src/test/java/org/apache/iceberg/flink/source/TestIcebergSourceBoundedGenericRecord.java
@@ -0,0 +1,202 @@
+/*
+ * 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.iceberg.flink.source;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.avro.generic.GenericRecord;
+import org.apache.flink.api.common.eventtime.WatermarkStrategy;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.formats.avro.typeutils.GenericRecordAvroTypeInfo;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.test.util.MiniClusterWithClientResource;
+import org.apache.flink.types.Row;
+import org.apache.flink.util.CloseableIterator;
+import org.apache.iceberg.FileFormat;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.avro.AvroSchemaUtil;
+import org.apache.iceberg.data.GenericAppenderHelper;
+import org.apache.iceberg.data.RandomGenericData;
+import org.apache.iceberg.data.Record;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.flink.FlinkConfigOptions;
+import org.apache.iceberg.flink.FlinkSchemaUtil;
+import org.apache.iceberg.flink.HadoopCatalogResource;
+import org.apache.iceberg.flink.MiniClusterResource;
+import org.apache.iceberg.flink.TableLoader;
+import org.apache.iceberg.flink.TestFixtures;
+import org.apache.iceberg.flink.TestHelpers;
+import org.apache.iceberg.flink.data.RowDataToRowMapper;
+import org.apache.iceberg.flink.sink.AvroGenericRecordToRowDataMapper;
+import org.apache.iceberg.flink.source.assigner.SimpleSplitAssignerFactory;
+import org.apache.iceberg.flink.source.reader.AvroGenericRecordReaderFunction;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+@RunWith(Parameterized.class)
+public class TestIcebergSourceBoundedGenericRecord {
+  @ClassRule
+  public static final MiniClusterWithClientResource MINI_CLUSTER_RESOURCE =
+      MiniClusterResource.createWithClassloaderCheckDisabled();
+
+  @ClassRule public static final TemporaryFolder TEMPORARY_FOLDER = new TemporaryFolder();
+
+  @Rule
+  public final HadoopCatalogResource catalogResource =
+      new HadoopCatalogResource(TEMPORARY_FOLDER, TestFixtures.DATABASE, TestFixtures.TABLE);
+
+  @Parameterized.Parameters(name = "format={0}, parallelism = {1}")
+  public static Object[][] parameters() {
+    return new Object[][] {
+      {"avro", 2},
+      {"parquet", 2},
+      {"orc", 2}
+    };
+  }
+
+  private final FileFormat fileFormat;
+  private final int parallelism;
+
+  public TestIcebergSourceBoundedGenericRecord(String format, int parallelism) {
+    this.fileFormat = FileFormat.valueOf(format.toUpperCase(Locale.ENGLISH));
+    this.parallelism = parallelism;
+  }
+
+  @Test
+  public void testUnpartitionedTable() throws Exception {
+    Table table =
+        catalogResource.catalog().createTable(TestFixtures.TABLE_IDENTIFIER, TestFixtures.SCHEMA);
+    List<Record> expectedRecords = RandomGenericData.generate(TestFixtures.SCHEMA, 2, 0L);
+    new GenericAppenderHelper(table, fileFormat, TEMPORARY_FOLDER).appendToTable(expectedRecords);
+    TestHelpers.assertRecords(run(), expectedRecords, TestFixtures.SCHEMA);
+  }
+
+  @Test
+  public void testPartitionedTable() throws Exception {
+    String dateStr = "2020-03-20";
+    Table table =
+        catalogResource
+            .catalog()
+            .createTable(TestFixtures.TABLE_IDENTIFIER, TestFixtures.SCHEMA, TestFixtures.SPEC);
+    List<Record> expectedRecords = RandomGenericData.generate(TestFixtures.SCHEMA, 2, 0L);
+    for (int i = 0; i < expectedRecords.size(); ++i) {
+      expectedRecords.get(i).setField("dt", dateStr);
+    }
+
+    new GenericAppenderHelper(table, fileFormat, TEMPORARY_FOLDER)
+        .appendToTable(org.apache.iceberg.TestHelpers.Row.of(dateStr, 0), expectedRecords);
+    TestHelpers.assertRecords(run(), expectedRecords, TestFixtures.SCHEMA);
+  }
+
+  @Test
+  public void testProjection() throws Exception {
+    Table table =
+        catalogResource
+            .catalog()
+            .createTable(TestFixtures.TABLE_IDENTIFIER, TestFixtures.SCHEMA, TestFixtures.SPEC);
+    List<Record> expectedRecords = RandomGenericData.generate(TestFixtures.SCHEMA, 2, 0L);
+    new GenericAppenderHelper(table, fileFormat, TEMPORARY_FOLDER)
+        .appendToTable(org.apache.iceberg.TestHelpers.Row.of("2020-03-20", 0), expectedRecords);
+    // select the "data" field (fieldId == 1)
+    Schema projectedSchema = TypeUtil.select(TestFixtures.SCHEMA, Sets.newHashSet(1));
+    List<Row> expectedRows =
+        Arrays.asList(Row.of(expectedRecords.get(0).get(0)), Row.of(expectedRecords.get(1).get(0)));
+    TestHelpers.assertRows(
+        run(projectedSchema, Collections.emptyList(), Collections.emptyMap()), expectedRows);
+  }
+
+  private List<Row> run() throws Exception {
+    return run(null, Collections.emptyList(), Collections.emptyMap());
+  }
+
+  private List<Row> run(
+      Schema projectedSchema, List<Expression> filters, Map<String, String> options)
+      throws Exception {
+
+    StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
+    env.setParallelism(parallelism);
+    env.getConfig().enableObjectReuse();
+
+    Configuration config = new Configuration();
+    config.setInteger(FlinkConfigOptions.SOURCE_READER_FETCH_BATCH_RECORD_COUNT, 128);
+    Table table;
+    try (TableLoader tableLoader = catalogResource.tableLoader()) {
+      tableLoader.open();
+      table = tableLoader.loadTable();
+    }
+
+    AvroGenericRecordReaderFunction readerFunction =
+        new AvroGenericRecordReaderFunction(
+            TestFixtures.TABLE_IDENTIFIER.name(),
+            new Configuration(),
+            table.schema(),
+            null,
+            null,
+            false,
+            table.io(),
+            table.encryption());
+
+    IcebergSource.Builder<GenericRecord> sourceBuilder =
+        IcebergSource.<GenericRecord>builder()
+            .tableLoader(catalogResource.tableLoader())
+            .readerFunction(readerFunction)
+            .assignerFactory(new SimpleSplitAssignerFactory())
+            .flinkConfig(config);
+    if (projectedSchema != null) {
+      sourceBuilder.project(projectedSchema);
+    }
+
+    sourceBuilder.filters(filters);
+    sourceBuilder.setAll(options);
+
+    Schema readSchema = projectedSchema != null ? projectedSchema : table.schema();
+    RowType rowType = FlinkSchemaUtil.convert(readSchema);
+    org.apache.avro.Schema avroSchema =
+        AvroSchemaUtil.convert(readSchema, TestFixtures.TABLE_IDENTIFIER.name());
+
+    DataStream<Row> stream =
+        env.fromSource(
+                sourceBuilder.build(),
+                WatermarkStrategy.noWatermarks(),
+                "testBasicRead",
+                new GenericRecordAvroTypeInfo(avroSchema))
+            // There are two reasons for converting GenericRecord back to Row.
+            // 1. Avro GenericRecord/Schema is not serializable.
+            // 2. leverage the TestHelpers.assertRecords for validation.
+            .map(AvroGenericRecordToRowDataMapper.forAvroSchema(avroSchema))
+            .map(new RowDataToRowMapper(rowType));
+
+    try (CloseableIterator<Row> iter = stream.executeAndCollect()) {
+      return Lists.newArrayList(iter);
+    }
+  }
+}