You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@paimon.apache.org by lz...@apache.org on 2024/01/08 09:31:39 UTC

(incubator-paimon) 02/05: [core] Clean TableQueryImpl and add test

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

lzljs3620320 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-paimon.git

commit f20d935179bbc735465004d28fed30e882b96aad
Author: Jingsong <ji...@gmail.com>
AuthorDate: Mon Jan 8 15:54:10 2024 +0800

    [core] Clean TableQueryImpl and add test
---
 .../java/org/apache/paimon/KeyValueFileStore.java  |  12 +-
 .../paimon/io/KeyValueFileReaderFactory.java       |   4 +
 .../paimon/operation/KeyValueFileStoreRead.java    |  23 +++-
 .../apache/paimon/table/query/TableQueryImpl.java  | 130 +++++++++------------
 .../paimon/table/PrimaryKeyFileStoreTableTest.java |  75 ++++++++++++
 5 files changed, 163 insertions(+), 81 deletions(-)

diff --git a/paimon-core/src/main/java/org/apache/paimon/KeyValueFileStore.java b/paimon-core/src/main/java/org/apache/paimon/KeyValueFileStore.java
index 43aadcbfd..710b01585 100644
--- a/paimon-core/src/main/java/org/apache/paimon/KeyValueFileStore.java
+++ b/paimon-core/src/main/java/org/apache/paimon/KeyValueFileStore.java
@@ -24,6 +24,7 @@ import org.apache.paimon.format.FileFormatDiscover;
 import org.apache.paimon.fs.FileIO;
 import org.apache.paimon.index.HashIndexMaintainer;
 import org.apache.paimon.index.IndexMaintainer;
+import org.apache.paimon.io.KeyValueFileReaderFactory;
 import org.apache.paimon.manifest.ManifestCacheFilter;
 import org.apache.paimon.mergetree.compact.MergeFunctionFactory;
 import org.apache.paimon.operation.KeyValueFileStoreRead;
@@ -112,13 +113,22 @@ public class KeyValueFileStore extends AbstractFileStore<KeyValue> {
     @Override
     public KeyValueFileStoreRead newRead() {
         return new KeyValueFileStoreRead(
-                fileIO,
                 schemaManager,
                 schemaId,
                 keyType,
                 valueType,
                 newKeyComparator(),
                 mfFactory,
+                newReaderFactoryBuilder());
+    }
+
+    public KeyValueFileReaderFactory.Builder newReaderFactoryBuilder() {
+        return KeyValueFileReaderFactory.builder(
+                fileIO,
+                schemaManager,
+                schemaId,
+                keyType,
+                valueType,
                 FileFormatDiscover.of(options),
                 pathFactory(),
                 keyValueFieldsExtractor,
diff --git a/paimon-core/src/main/java/org/apache/paimon/io/KeyValueFileReaderFactory.java b/paimon-core/src/main/java/org/apache/paimon/io/KeyValueFileReaderFactory.java
index 938bc1997..6d4896cde 100644
--- a/paimon-core/src/main/java/org/apache/paimon/io/KeyValueFileReaderFactory.java
+++ b/paimon-core/src/main/java/org/apache/paimon/io/KeyValueFileReaderFactory.java
@@ -218,6 +218,10 @@ public class KeyValueFileReaderFactory {
             return this;
         }
 
+        public RowType keyType() {
+            return keyType;
+        }
+
         public RowType projectedValueType() {
             return projectedValueType;
         }
diff --git a/paimon-core/src/main/java/org/apache/paimon/operation/KeyValueFileStoreRead.java b/paimon-core/src/main/java/org/apache/paimon/operation/KeyValueFileStoreRead.java
index 2da7125c9..09b9cb81b 100644
--- a/paimon-core/src/main/java/org/apache/paimon/operation/KeyValueFileStoreRead.java
+++ b/paimon-core/src/main/java/org/apache/paimon/operation/KeyValueFileStoreRead.java
@@ -96,8 +96,13 @@ public class KeyValueFileStoreRead implements FileStoreRead<KeyValue> {
             FileStorePathFactory pathFactory,
             KeyValueFieldsExtractor extractor,
             CoreOptions options) {
-        this.tableSchema = schemaManager.schema(schemaId);
-        this.readerFactoryBuilder =
+        this(
+                schemaManager,
+                schemaId,
+                keyType,
+                valueType,
+                keyComparator,
+                mfFactory,
                 KeyValueFileReaderFactory.builder(
                         fileIO,
                         schemaManager,
@@ -107,7 +112,19 @@ public class KeyValueFileStoreRead implements FileStoreRead<KeyValue> {
                         formatDiscover,
                         pathFactory,
                         extractor,
-                        options);
+                        options));
+    }
+
+    public KeyValueFileStoreRead(
+            SchemaManager schemaManager,
+            long schemaId,
+            RowType keyType,
+            RowType valueType,
+            Comparator<InternalRow> keyComparator,
+            MergeFunctionFactory<KeyValue> mfFactory,
+            KeyValueFileReaderFactory.Builder readerFactoryBuilder) {
+        this.tableSchema = schemaManager.schema(schemaId);
+        this.readerFactoryBuilder = readerFactoryBuilder;
         this.keyComparator = keyComparator;
         this.mfFactory = mfFactory;
         this.mergeSorter =
diff --git a/paimon-core/src/main/java/org/apache/paimon/table/query/TableQueryImpl.java b/paimon-core/src/main/java/org/apache/paimon/table/query/TableQueryImpl.java
index 94649cf9b..c261f0d84 100644
--- a/paimon-core/src/main/java/org/apache/paimon/table/query/TableQueryImpl.java
+++ b/paimon-core/src/main/java/org/apache/paimon/table/query/TableQueryImpl.java
@@ -21,26 +21,21 @@
 package org.apache.paimon.table.query;
 
 import org.apache.paimon.CoreOptions;
+import org.apache.paimon.FileStore;
 import org.apache.paimon.KeyValue;
+import org.apache.paimon.KeyValueFileStore;
 import org.apache.paimon.data.BinaryRow;
 import org.apache.paimon.data.InternalRow;
 import org.apache.paimon.disk.IOManager;
-import org.apache.paimon.format.FileFormatDiscover;
 import org.apache.paimon.io.DataFileMeta;
 import org.apache.paimon.io.KeyValueFileReaderFactory;
 import org.apache.paimon.io.cache.CacheManager;
 import org.apache.paimon.lookup.hash.HashLookupStoreFactory;
 import org.apache.paimon.mergetree.Levels;
 import org.apache.paimon.mergetree.LookupLevels;
-import org.apache.paimon.schema.KeyValueFieldsExtractor;
-import org.apache.paimon.schema.SchemaManager;
 import org.apache.paimon.table.FileStoreTable;
-import org.apache.paimon.table.PrimaryKeyTableUtils;
-import org.apache.paimon.types.RowType;
-import org.apache.paimon.utils.FileStorePathFactory;
 import org.apache.paimon.utils.KeyComparatorSupplier;
 import org.apache.paimon.utils.Preconditions;
-import org.apache.paimon.utils.Projection;
 
 import javax.annotation.Nullable;
 
@@ -62,47 +57,29 @@ public class TableQueryImpl implements TableQuery {
 
     private final Supplier<Comparator<InternalRow>> keyComparatorSupplier;
 
-    private final RowType keyType;
-
-    private RowType projectedValueType;
-
     private final KeyValueFileReaderFactory.Builder readerFactoryBuilder;
 
-    private IOManager ioManager;
-
     private final HashLookupStoreFactory hashLookupStoreFactory;
 
+    private IOManager ioManager;
+
     public TableQueryImpl(FileStoreTable table) {
-        this.options = new CoreOptions(table.options());
+        this.options = table.coreOptions();
         this.tableView = new HashMap<>();
-        KeyValueFieldsExtractor pkExtractor =
-                PrimaryKeyTableUtils.PrimaryKeyFieldsExtractor.EXTRACTOR;
-        this.keyType = new RowType(pkExtractor.keyFields(table.schema()));
-        CacheManager cacheManager =
-                new CacheManager(
-                        options.pageSize(),
-                        options.toConfiguration().get(LOOKUP_CACHE_MAX_MEMORY_SIZE));
-        RowType partitionType = table.schema().logicalPartitionType();
-        this.readerFactoryBuilder =
-                KeyValueFileReaderFactory.builder(
-                        table.fileIO(),
-                        new SchemaManager(table.fileIO(), table.location()),
-                        table.schema().id(),
-                        keyType,
-                        table.rowType(),
-                        FileFormatDiscover.of(options),
-                        new FileStorePathFactory(
-                                options.path(),
-                                partitionType,
-                                options.partitionDefaultName(),
-                                options.fileFormat().getFormatIdentifier()),
-                        PrimaryKeyTableUtils.PrimaryKeyFieldsExtractor.EXTRACTOR,
-                        options);
-        this.projectedValueType = readerFactoryBuilder.projectedValueType();
-        this.keyComparatorSupplier = new KeyComparatorSupplier(keyType);
+        FileStore<?> tableStore = table.store();
+        if (!(tableStore instanceof KeyValueFileStore)) {
+            throw new UnsupportedOperationException(
+                    "Table Query only supports table with primary key.");
+        }
+        KeyValueFileStore store = (KeyValueFileStore) tableStore;
+
+        this.readerFactoryBuilder = store.newReaderFactoryBuilder();
+        this.keyComparatorSupplier = new KeyComparatorSupplier(readerFactoryBuilder.keyType());
         this.hashLookupStoreFactory =
                 new HashLookupStoreFactory(
-                        cacheManager,
+                        new CacheManager(
+                                options.pageSize(),
+                                options.toConfiguration().get(LOOKUP_CACHE_MAX_MEMORY_SIZE)),
                         options.toConfiguration().get(CoreOptions.LOOKUP_HASH_LOAD_FACTOR));
         Preconditions.checkArgument(
                 options.changelogProducer() == CoreOptions.ChangelogProducer.LOOKUP,
@@ -115,43 +92,43 @@ public class TableQueryImpl implements TableQuery {
             int bucket,
             List<DataFileMeta> beforeFiles,
             List<DataFileMeta> dataFiles) {
-        Map<Integer, LookupLevels> buckets =
-                tableView.computeIfAbsent(partition, k -> new HashMap<>());
-        LookupLevels lookupLevels = buckets.get(bucket);
-
+        LookupLevels lookupLevels =
+                tableView.computeIfAbsent(partition, k -> new HashMap<>()).get(bucket);
         if (lookupLevels == null) {
             Preconditions.checkArgument(
                     beforeFiles.isEmpty(),
                     "The before file should be empty for the initial phase.");
-            Levels levels = new Levels(keyComparatorSupplier.get(), dataFiles, options.numLevels());
-
-            KeyValueFileReaderFactory factory = readerFactoryBuilder.build(partition, bucket);
-
-            lookupLevels =
-                    new LookupLevels(
-                            levels,
-                            keyComparatorSupplier.get(),
-                            keyType,
-                            projectedValueType,
-                            file ->
-                                    factory.createRecordReader(
-                                            file.schemaId(),
-                                            file.fileName(),
-                                            file.fileSize(),
-                                            file.level()),
-                            () ->
-                                    Preconditions.checkNotNull(ioManager, "IOManager is required.")
-                                            .createChannel()
-                                            .getPathFile(),
-                            hashLookupStoreFactory,
-                            options.toConfiguration().get(CoreOptions.LOOKUP_CACHE_FILE_RETENTION),
-                            options.toConfiguration().get(CoreOptions.LOOKUP_CACHE_MAX_DISK_SIZE));
-            buckets.put(bucket, lookupLevels);
+            newLookupLevels(partition, bucket, dataFiles);
         } else {
             lookupLevels.getLevels().update(beforeFiles, dataFiles);
         }
     }
 
+    private void newLookupLevels(BinaryRow partition, int bucket, List<DataFileMeta> dataFiles) {
+        Levels levels = new Levels(keyComparatorSupplier.get(), dataFiles, options.numLevels());
+        KeyValueFileReaderFactory factory = readerFactoryBuilder.build(partition, bucket);
+        LookupLevels lookupLevels =
+                new LookupLevels(
+                        levels,
+                        keyComparatorSupplier.get(),
+                        readerFactoryBuilder.keyType(),
+                        readerFactoryBuilder.projectedValueType(),
+                        file ->
+                                factory.createRecordReader(
+                                        file.schemaId(),
+                                        file.fileName(),
+                                        file.fileSize(),
+                                        file.level()),
+                        () ->
+                                Preconditions.checkNotNull(ioManager, "IOManager is required.")
+                                        .createChannel()
+                                        .getPathFile(),
+                        hashLookupStoreFactory,
+                        options.toConfiguration().get(CoreOptions.LOOKUP_CACHE_FILE_RETENTION),
+                        options.toConfiguration().get(CoreOptions.LOOKUP_CACHE_MAX_DISK_SIZE));
+        tableView.computeIfAbsent(partition, k -> new HashMap<>()).put(bucket, lookupLevels);
+    }
+
     @Nullable
     @Override
     public InternalRow lookup(BinaryRow partition, int bucket, InternalRow key) throws IOException {
@@ -162,21 +139,20 @@ public class TableQueryImpl implements TableQuery {
         LookupLevels lookupLevels = buckets.get(bucket);
         if (lookupLevels == null) {
             return null;
+        }
+
+        // lookup start from level 1.
+        KeyValue kv = lookupLevels.lookup(key, 1);
+        if (kv == null || kv.valueKind().isRetract()) {
+            return null;
         } else {
-            // lookup start from level 1.
-            KeyValue kv = lookupLevels.lookup(key, 1);
-            if (kv == null || kv.valueKind().isRetract()) {
-                return null;
-            } else {
-                return kv.value();
-            }
+            return kv.value();
         }
     }
 
     @Override
     public TableQuery withValueProjection(int[][] projection) {
-        this.readerFactoryBuilder.withValueProjection(Projection.of(projection).toNestedIndexes());
-        this.projectedValueType = readerFactoryBuilder.projectedValueType();
+        this.readerFactoryBuilder.withValueProjection(projection);
         return this;
     }
 
diff --git a/paimon-core/src/test/java/org/apache/paimon/table/PrimaryKeyFileStoreTableTest.java b/paimon-core/src/test/java/org/apache/paimon/table/PrimaryKeyFileStoreTableTest.java
index 4863053e1..79d9c0600 100644
--- a/paimon-core/src/test/java/org/apache/paimon/table/PrimaryKeyFileStoreTableTest.java
+++ b/paimon-core/src/test/java/org/apache/paimon/table/PrimaryKeyFileStoreTableTest.java
@@ -24,6 +24,7 @@ import org.apache.paimon.KeyValue;
 import org.apache.paimon.data.BinaryString;
 import org.apache.paimon.data.GenericRow;
 import org.apache.paimon.data.InternalRow;
+import org.apache.paimon.disk.IOManager;
 import org.apache.paimon.disk.IOManagerImpl;
 import org.apache.paimon.fs.FileIOFinder;
 import org.apache.paimon.fs.local.LocalFileIO;
@@ -34,10 +35,12 @@ import org.apache.paimon.schema.Schema;
 import org.apache.paimon.schema.SchemaManager;
 import org.apache.paimon.schema.SchemaUtils;
 import org.apache.paimon.schema.TableSchema;
+import org.apache.paimon.table.query.TableQuery;
 import org.apache.paimon.table.sink.BatchTableCommit;
 import org.apache.paimon.table.sink.BatchTableWrite;
 import org.apache.paimon.table.sink.BatchWriteBuilder;
 import org.apache.paimon.table.sink.CommitMessage;
+import org.apache.paimon.table.sink.CommitMessageImpl;
 import org.apache.paimon.table.sink.InnerTableCommit;
 import org.apache.paimon.table.sink.StreamTableCommit;
 import org.apache.paimon.table.sink.StreamTableWrite;
@@ -76,6 +79,7 @@ import java.util.function.Function;
 
 import static org.apache.paimon.CoreOptions.BUCKET;
 import static org.apache.paimon.data.DataFormatTestUtil.internalRowToString;
+import static org.apache.paimon.io.DataFileTestUtils.row;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
@@ -1150,6 +1154,77 @@ public class PrimaryKeyFileStoreTableTest extends FileStoreTableTestBase {
         commit.close();
     }
 
+    @Test
+    public void testTableQuery() throws Exception {
+        FileStoreTable table =
+                createFileStoreTable(
+                        options ->
+                                options.set(
+                                        CoreOptions.CHANGELOG_PRODUCER, ChangelogProducer.LOOKUP));
+        IOManager ioManager = IOManager.create(tablePath.toString());
+        StreamTableWrite write = table.newWrite(commitUser).withIOManager(ioManager);
+        StreamTableCommit commit = table.newCommit(commitUser);
+
+        // first write
+
+        write.write(rowData(1, 10, 100L));
+        List<CommitMessage> commitMessages = write.prepareCommit(true, 0);
+        commit.commit(0, commitMessages);
+
+        TableQuery query = table.newTableQuery();
+        query.withIOManager(ioManager);
+
+        refreshTableService(query, commitMessages);
+        InternalRow value = query.lookup(row(1), 0, row(10));
+        assertThat(value).isNotNull();
+        assertThat(BATCH_ROW_TO_STRING.apply(value))
+                .isEqualTo("1|10|100|binary|varbinary|mapKey:mapVal|multiset");
+
+        // second write
+
+        write.write(rowData(1, 10, 200L));
+        write.write(rowData(3, 10, 300L));
+        commitMessages = write.prepareCommit(true, 0);
+        commit.commit(0, commitMessages);
+
+        refreshTableService(query, commitMessages);
+
+        value = query.lookup(row(1), 0, row(10));
+        assertThat(value).isNotNull();
+        assertThat(BATCH_ROW_TO_STRING.apply(value))
+                .isEqualTo("1|10|200|binary|varbinary|mapKey:mapVal|multiset");
+
+        value = query.lookup(row(3), 0, row(10));
+        assertThat(value).isNotNull();
+        assertThat(BATCH_ROW_TO_STRING.apply(value))
+                .isEqualTo("3|10|300|binary|varbinary|mapKey:mapVal|multiset");
+
+        // query non value
+
+        value = query.lookup(row(1), 0, row(20));
+        assertThat(value).isNull();
+
+        query.close();
+        write.close();
+        commit.close();
+    }
+
+    private void refreshTableService(TableQuery query, List<CommitMessage> commitMessages) {
+        for (CommitMessage m : commitMessages) {
+            CommitMessageImpl msg = (CommitMessageImpl) m;
+            query.refreshFiles(
+                    msg.partition(),
+                    msg.bucket(),
+                    Collections.emptyList(),
+                    msg.newFilesIncrement().newFiles());
+            query.refreshFiles(
+                    msg.partition(),
+                    msg.bucket(),
+                    msg.compactIncrement().compactBefore(),
+                    msg.compactIncrement().compactAfter());
+        }
+    }
+
     @Override
     protected FileStoreTable createFileStoreTable(Consumer<Options> configure) throws Exception {
         return createFileStoreTable(configure, ROW_TYPE);