diff --git a/fluss-lake/fluss-lake-paimon/src/main/java/org/apache/fluss/lake/paimon/PaimonLakeCatalog.java b/fluss-lake/fluss-lake-paimon/src/main/java/org/apache/fluss/lake/paimon/PaimonLakeCatalog.java index e93d1686f1d..804aa4c4a23 100644 --- a/fluss-lake/fluss-lake-paimon/src/main/java/org/apache/fluss/lake/paimon/PaimonLakeCatalog.java +++ b/fluss-lake/fluss-lake-paimon/src/main/java/org/apache/fluss/lake/paimon/PaimonLakeCatalog.java @@ -40,6 +40,7 @@ import org.apache.paimon.options.Options; import org.apache.paimon.schema.Schema; import org.apache.paimon.schema.SchemaChange; +import org.apache.paimon.schema.TableSchema; import org.apache.paimon.table.FileStoreTable; import org.apache.paimon.table.Table; import org.apache.paimon.types.DataType; @@ -194,16 +195,18 @@ public void alterTable(TablePath tablePath, List tableChanges, Cont return; } - Schema currentPaimonSchema = fileStoreTable.schema().toSchema(); + TableSchema currentPaimonSchema = fileStoreTable.schema(); List paimonSchemaChanges; if (isPaimonSchemaCompatible( - currentPaimonSchema, toPaimonSchema(context.getCurrentTable()))) { + currentPaimonSchema, + TableSchema.create(0, toPaimonSchema(context.getCurrentTable())))) { // if the paimon schema is same as current fluss schema, directly apply all the // changes. paimonSchemaChanges = toPaimonSchemaChanges(table, changesToApply); } else if (isPaimonSchemaCompatible( - currentPaimonSchema, toPaimonSchema(context.getExpectedTable()))) { + currentPaimonSchema, + TableSchema.create(0, toPaimonSchema(context.getExpectedTable())))) { // if the schema is same as applied fluss schema , skip adding columns. paimonSchemaChanges = toPaimonSchemaChanges( @@ -330,14 +333,16 @@ private void createTable(TablePath tablePath, Schema schema, Context context) try { Table table = paimonCatalog.getTable(paimonPath); FileStoreTable fileStoreTable = (FileStoreTable) table; - Schema existingSchema = fileStoreTable.schema().toSchema(); - if (!isPaimonSchemaCompatible(existingSchema, schema)) { + TableSchema existingSchema = fileStoreTable.schema(); + if (!isPaimonSchemaCompatible(existingSchema, TableSchema.create(0, schema))) { throw new TableAlreadyExistException( String.format( "The table %s already exists in Paimon catalog, but the table schema is not compatible. " + "Existing schema: %s, new schema: %s. " + "Please first drop the table in Paimon catalog or use a new table name.", - paimonPath.getEscapedFullName(), existingSchema, schema)); + paimonPath.getEscapedFullName(), + existingSchema.toSchema(), + schema)); } // if creating a new fluss table, we should ensure the lake table is empty if (context.isCreatingFlussTable()) { diff --git a/fluss-lake/fluss-lake-paimon/src/main/java/org/apache/fluss/lake/paimon/utils/PaimonTableValidation.java b/fluss-lake/fluss-lake-paimon/src/main/java/org/apache/fluss/lake/paimon/utils/PaimonTableValidation.java index f85f2380183..46d01ed0ff8 100644 --- a/fluss-lake/fluss-lake-paimon/src/main/java/org/apache/fluss/lake/paimon/utils/PaimonTableValidation.java +++ b/fluss-lake/fluss-lake-paimon/src/main/java/org/apache/fluss/lake/paimon/utils/PaimonTableValidation.java @@ -24,6 +24,7 @@ import org.apache.paimon.options.ConfigOption; import org.apache.paimon.options.Options; import org.apache.paimon.schema.Schema; +import org.apache.paimon.schema.TableSchema; import org.apache.paimon.table.FileStoreTable; import org.apache.paimon.types.ArrayType; import org.apache.paimon.types.DataField; @@ -36,9 +37,11 @@ import org.apache.paimon.types.VarCharType; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.stream.Collectors; import static org.apache.fluss.lake.paimon.PaimonLakeCatalog.LEGACY_SYSTEM_COLUMNS; @@ -54,13 +57,14 @@ public class PaimonTableValidation { .collect(Collectors.toMap(ConfigOption::key, option -> option)); /** Checks physical schema and immutable option compatibility. */ - public static boolean isPaimonSchemaCompatible(Schema existingSchema, Schema newSchema) { + public static boolean isPaimonSchemaCompatible( + TableSchema existingSchema, TableSchema newSchema) { // FIP-27: newly generated schemas are always clean (no system columns). When the existing // table is a legacy table that still carries the three system columns (recognisable by the // presence of the __timestamp column), re-enabling lake tiering must keep that physical // layout. Enrich the clean new schema with the trailing system columns before comparison, // so an existing legacy table is recognised as compatible and its layout is preserved. - if (PaimonUtils.isLegacyTable(existingSchema.rowType())) { + if (PaimonUtils.isLegacyTable(existingSchema.logicalRowType())) { newSchema = appendSystemColumns(newSchema); } @@ -81,23 +85,22 @@ public static boolean isPaimonSchemaCompatible(Schema existingSchema, Schema new * preserved. System-column field ids continue the existing id sequence to avoid collisions; * they are irrelevant to {@link #equalPhysicalSchema}, which ignores field ids. */ - private static Schema appendSystemColumns(Schema cleanSchema) { + private static TableSchema appendSystemColumns(TableSchema cleanSchema) { List fields = new ArrayList<>(cleanSchema.fields()); - int nextFieldId = 0; - for (DataField field : fields) { - nextFieldId = Math.max(nextFieldId, field.id() + 1); - } + int nextFieldId = cleanSchema.highestFieldId() + 1; for (Map.Entry systemColumn : LEGACY_SYSTEM_COLUMNS.entrySet()) { fields.add( new DataField(nextFieldId++, systemColumn.getKey(), systemColumn.getValue())); } - return new Schema( - fields, - cleanSchema.partitionKeys(), - cleanSchema.primaryKeys(), - cleanSchema.options(), - cleanSchema.comment()); + return TableSchema.create( + cleanSchema.id(), + new Schema( + fields, + cleanSchema.partitionKeys(), + cleanSchema.primaryKeys(), + cleanSchema.options(), + cleanSchema.comment())); } /** @@ -115,7 +118,7 @@ private static Schema appendSystemColumns(Schema cleanSchema) { * options, and the precision of the system timestamp */ public static boolean equalIgnoreSystemColumnTimestampPrecision( - Schema existingSchema, Schema newSchema) { + TableSchema existingSchema, TableSchema newSchema) { List existingFields = new ArrayList<>(existingSchema.fields()); // The precision relaxation only applies to a legacy table's trailing __timestamp system // column. A clean table (or any table whose last column is not __timestamp) has no such @@ -140,11 +143,16 @@ public static boolean equalIgnoreSystemColumnTimestampPrecision( DataTypes.TIMESTAMP_LTZ_MILLIS(), systemTimestampField.description())); } - existingSchema = existingSchema.copy(RowType.of(existingFields.toArray(new DataField[0]))); + existingSchema = + TableSchema.create( + existingSchema.id(), + existingSchema + .toSchema() + .copy(RowType.of(existingFields.toArray(new DataField[0])))); return equalPhysicalSchema(existingSchema, newSchema); } - private static boolean equalPhysicalSchema(Schema existingSchema, Schema newSchema) { + private static boolean equalPhysicalSchema(TableSchema existingSchema, TableSchema newSchema) { List existingFields = existingSchema.fields(); List newFields = newSchema.fields(); if (existingFields.size() != newFields.size()) { @@ -161,25 +169,22 @@ private static boolean equalPhysicalSchema(Schema existingSchema, Schema newSche return Objects.equals(existingSchema.partitionKeys(), newSchema.partitionKeys()) && Objects.equals(existingSchema.primaryKeys(), newSchema.primaryKeys()) + && Objects.equals(existingSchema.bucketKeys(), newSchema.bucketKeys()) && equalPaimonOptions(existingSchema.options(), newSchema.options()); } private static boolean equalPaimonOptions( - Map existingOptions, Map newOptions) { + Map existingOptions, Map proposedOptions) { Options existing = Options.fromMap(existingOptions); - Options proposed = Options.fromMap(newOptions); - for (String option : PAIMON_UNSETTABLE_OPTIONS) { - if (PARTITION_GENERATE_LEGACY_NAME_OPTION_KEY.equals(option)) { - // Existing Paimon tables keep their partition path encoding. Fluss addresses - // partitions through logical values and Paimon APIs rather than the directory name. - continue; - } - if (!equalPaimonOption(option, existing, proposed)) { - return false; - } - } - - for (String option : CoreOptions.IMMUTABLE_OPTIONS) { + Options proposed = Options.fromMap(proposedOptions); + Set optionKeys = new HashSet<>(PAIMON_UNSETTABLE_OPTIONS); + optionKeys.addAll(CoreOptions.IMMUTABLE_OPTIONS); + // equalPhysicalSchema compares resolved bucket keys, including Paimon's default, so + // equivalent implicit and explicit keys must not be compared as raw option values here. + optionKeys.remove(CoreOptions.BUCKET_KEY.key()); + // Existing tables keep their partition path encoding; Fluss uses logical partition values. + optionKeys.remove(PARTITION_GENERATE_LEGACY_NAME_OPTION_KEY); + for (String option : optionKeys) { if (!equalPaimonOption(option, existing, proposed)) { return false; } diff --git a/fluss-lake/fluss-lake-paimon/src/test/java/org/apache/fluss/lake/paimon/CreateTableFromLakeITCase.java b/fluss-lake/fluss-lake-paimon/src/test/java/org/apache/fluss/lake/paimon/CreateTableFromLakeITCase.java index d94f7841a2c..d4b1886319f 100644 --- a/fluss-lake/fluss-lake-paimon/src/test/java/org/apache/fluss/lake/paimon/CreateTableFromLakeITCase.java +++ b/fluss-lake/fluss-lake-paimon/src/test/java/org/apache/fluss/lake/paimon/CreateTableFromLakeITCase.java @@ -26,9 +26,7 @@ import org.apache.fluss.exception.InvalidTableException; import org.apache.fluss.exception.LakeTableSnapshotNotExistException; import org.apache.fluss.exception.TableAlreadyExistException; -import org.apache.fluss.metadata.AggFunctions; import org.apache.fluss.metadata.DataLakeFormat; -import org.apache.fluss.metadata.DeleteBehavior; import org.apache.fluss.metadata.MergeEngineType; import org.apache.fluss.metadata.TableInfo; import org.apache.fluss.metadata.TablePath; @@ -59,7 +57,6 @@ import javax.annotation.Nullable; import java.nio.file.Files; -import java.time.Duration; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -149,9 +146,70 @@ void testCreatePrimaryKeyTableWithExistingData() throws Exception { } @ParameterizedTest - @CsvSource({"partial-update,true", "partial-update,false", "aggregation,true"}) - void testCreatePrimaryKeyTableWithMergeSemantics(String engine, boolean ignoreDelete) + @CsvSource({ + "merge-engine,first-row,table.merge-engine,first_row", + "sequence.field,version,table.merge-engine,versioned", + "record-level.expire-time,7 d,table.kv.ttl,7 d" + }) + void testRejectUnsupportedBulkLoadOptions( + String sourceKey, String sourceValue, String targetKey, String targetValue) throws Exception { + String database = "unsupported_bulkload_" + sourceKey.replace('.', '_').replace('-', '_'); + TablePath sourcePath = TablePath.of(database, "native_options"); + TablePath overridePath = TablePath.of(database, "override_options"); + Schema base = + Schema.newBuilder() + .column("id", org.apache.paimon.types.DataTypes.BIGINT().notNull()) + .column("version", org.apache.paimon.types.DataTypes.BIGINT().notNull()) + .column( + "event_time", + org.apache.paimon.types.DataTypes.TIMESTAMP_WITH_LOCAL_TIME_ZONE(3)) + .primaryKey("id") + .option(CoreOptions.BUCKET.key(), "3") + .option(CoreOptions.IGNORE_DELETE.key(), "true") + .build(); + Map sourceOptions = new HashMap<>(base.options()); + sourceOptions.put(sourceKey, sourceValue); + if (CoreOptions.RECORD_LEVEL_EXPIRE_TIME.key().equals(sourceKey)) { + sourceOptions.put(CoreOptions.RECORD_LEVEL_TIME_FIELD.key(), "event_time"); + } + createPaimonTable( + sourcePath, + new Schema( + base.fields(), + base.partitionKeys(), + base.primaryKeys(), + sourceOptions, + base.comment())); + createPaimonTable(overridePath, base); + assertThat(admin.databaseExists(database).get()).isFalse(); + + assertThatThrownBy( + () -> admin.createTableFromLake(sourcePath, Collections.emptyMap()).get()) + .cause() + .isInstanceOf(InvalidTableException.class) + .hasMessageContaining("BulkLoad"); + + // The same restriction applies after caller options are merged into a plain source. + Map overrides = new HashMap<>(); + overrides.put(targetKey, targetValue); + if ("versioned".equals(targetValue)) { + overrides.put(ConfigOptions.TABLE_MERGE_ENGINE_VERSION_COLUMN.key(), "version"); + } + assertThatThrownBy(() -> admin.createTableFromLake(overridePath, overrides).get()) + .cause() + .isInstanceOf(InvalidTableException.class) + .hasMessageContaining("BulkLoad"); + assertThat(admin.databaseExists(database).get()).isFalse(); + assertThat(admin.tableExists(sourcePath).get()).isFalse(); + assertThat(admin.tableExists(overridePath).get()).isFalse(); + assertThat(paimonCatalog.getTable(toPaimon(sourcePath)).options()) + .containsEntry(sourceKey, sourceValue); + } + + @ParameterizedTest + @CsvSource({"partial-update,true", "partial-update,false", "aggregation,true"}) + void testRejectPrimaryKeyMergeSemantics(String engine, boolean ignoreDelete) throws Exception { TablePath tablePath = TablePath.of(DATABASE, "promote_" + engine.replace('-', '_') + "_" + ignoreDelete); boolean aggregation = "aggregation".equals(engine); @@ -176,26 +234,12 @@ void testCreatePrimaryKeyTableWithMergeSemantics(String engine, boolean ignoreDe } createPaimonTable(tablePath, schema.build()); - TableInfo created = - admin.createTableFromLake(tablePath, Collections.emptyMap()).get(); - assertThat(created.getTableConfig().getMergeEngineType()) - .contains(MergeEngineType.AGGREGATION); - assertThat(created.getTableConfig().getDeleteBehavior()) - .contains(ignoreDelete ? DeleteBehavior.IGNORE : DeleteBehavior.ALLOW); - assertThat(created.getSchema().getAggFunction("amount")) - .contains( - aggregation ? AggFunctions.SUM() : AggFunctions.LAST_VALUE_IGNORE_NULLS()); - assertThat(created.getSchema().getAggFunction("payload")) - .contains(AggFunctions.LAST_VALUE_IGNORE_NULLS()); - assertThat(created.getTableConfig().isDataLakeEnabled()).isFalse(); - assertThatThrownBy( - () -> - admin.createTableFromLake( - tablePath, Collections.emptyMap()) - .get()) + assertThatThrownBy(() -> admin.createTableFromLake(tablePath, Collections.emptyMap()).get()) .cause() - .isInstanceOf(TableAlreadyExistException.class); - // Request the opposite DELETE behavior when reusing the existing Fluss table. + .isInstanceOf(InvalidTableException.class) + .hasMessageContaining("BulkLoad"); + assertThat(admin.tableExists(tablePath).get()).isFalse(); + // Request the opposite DELETE behavior before creating Fluss metadata. // IGNORE and ALLOW are both explicitly derived, so neither can be overridden. assertCreateTableFromLakeFails( tablePath, @@ -303,24 +347,15 @@ void testPrimaryKeyDerivedOptionsCannotBeOverridden() throws Exception { assertCreateTableFromLakeFails(tablePath, "bucket.num", "8", "uses 4 buckets"); assertThat(admin.tableExists(tablePath).get()).isFalse(); - TableInfo created = - admin.createTableFromLake( - tablePath, - Collections.singletonMap( - ConfigOptions.TABLE_KV_TTL.key(), "604800000 ms")) - .get(); - assertThat(created.getTableConfig().getMergeEngineType()) - .contains(MergeEngineType.VERSIONED); - assertThat(created.getProperties().get(ConfigOptions.TABLE_KV_TTL)) - .isEqualTo(Duration.ofDays(7)); + assertCreateTableFromLakeFails( + tablePath, ConfigOptions.TABLE_KV_TTL.key(), "604800000 ms", "BulkLoad"); + assertThat(admin.tableExists(tablePath).get()).isFalse(); } @ParameterizedTest - @CsvSource({", allow", ", ignore", "first_row, ignore", "versioned, ignore"}) - void testSetPrimaryKeyOptionsNotDerivedFromLake( - @Nullable String mergeEngine, String deleteBehavior) throws Exception { - TablePath tablePath = - TablePath.of(DATABASE, "primary_key_options_" + mergeEngine + "_" + deleteBehavior); + @ValueSource(strings = {"allow", "ignore"}) + void testSetPrimaryKeyDeleteBehavior(String deleteBehavior) throws Exception { + TablePath tablePath = TablePath.of(DATABASE, "primary_key_delete_" + deleteBehavior); createPaimonTable( tablePath, Schema.newBuilder() @@ -332,12 +367,6 @@ void testSetPrimaryKeyOptionsNotDerivedFromLake( Map options = new HashMap<>(); options.put(ConfigOptions.TABLE_DELETE_BEHAVIOR.key(), deleteBehavior); - if (mergeEngine != null) { - options.put(ConfigOptions.TABLE_MERGE_ENGINE.key(), mergeEngine); - } - if ("versioned".equals(mergeEngine)) { - options.put(ConfigOptions.TABLE_MERGE_ENGINE_VERSION_COLUMN.key(), "version"); - } TableInfo created = admin.createTableFromLake(tablePath, options).get(); assertThat(created.getProperties().toMap()).containsAllEntriesOf(options); } diff --git a/fluss-lake/fluss-lake-paimon/src/test/java/org/apache/fluss/lake/paimon/EnableFlussOnLakeTableProcedureITCase.java b/fluss-lake/fluss-lake-paimon/src/test/java/org/apache/fluss/lake/paimon/EnableFlussOnLakeTableProcedureITCase.java index 062f5f26c68..b8772ac68a6 100644 --- a/fluss-lake/fluss-lake-paimon/src/test/java/org/apache/fluss/lake/paimon/EnableFlussOnLakeTableProcedureITCase.java +++ b/fluss-lake/fluss-lake-paimon/src/test/java/org/apache/fluss/lake/paimon/EnableFlussOnLakeTableProcedureITCase.java @@ -17,13 +17,11 @@ package org.apache.fluss.lake.paimon; -import org.apache.fluss.config.ConfigOptions; import org.apache.fluss.config.Configuration; import org.apache.fluss.exception.InvalidTableException; import org.apache.fluss.exception.LakeTableSnapshotNotExistException; import org.apache.fluss.lake.paimon.testutils.FlinkPaimonTieringTestBase; import org.apache.fluss.metadata.DataLakeFormat; -import org.apache.fluss.metadata.MergeEngineType; import org.apache.fluss.metadata.TableBucket; import org.apache.fluss.metadata.TableChange; import org.apache.fluss.metadata.TableInfo; @@ -53,13 +51,12 @@ import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; import java.util.ArrayList; import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import static org.apache.fluss.config.ConfigOptions.TABLE_DATALAKE_ENABLED; import static org.apache.fluss.testutils.DataTestUtils.row; @@ -536,67 +533,38 @@ void testRejectPrimaryKeyTableWithSnapshotBeforeRegisteringOrEnabling() throws E } @ParameterizedTest - @CsvSource({ - ", false", - ", true", - "first_row, false", - "first_row, true", - "versioned, false", - "versioned, true", - "aggregation, false", - "aggregation, true" - }) - void testEnablePrimaryKeyTableWithoutSnapshot(String mergeEngine, boolean metadataExists) - throws Exception { - TablePath tablePath = - TablePath.of(DATABASE, "procedure_empty_" + mergeEngine + "_" + metadataExists); + @ValueSource(booleans = {false, true}) + void testEnablePrimaryKeyTableWithoutSnapshot(boolean metadataExists) throws Exception { + TablePath tablePath = TablePath.of(DATABASE, "procedure_empty_" + metadataExists); createPaimonTable( tablePath, Schema.newBuilder() .column("id", org.apache.paimon.types.DataTypes.BIGINT().notNull()) .column("payload", org.apache.paimon.types.DataTypes.STRING()) - .column("version", org.apache.paimon.types.DataTypes.BIGINT().notNull()) .primaryKey("id") .option(CoreOptions.BUCKET.key(), "1") - .option(CoreOptions.BUCKET_KEY.key(), "id") .option("partition.legacy-name", "false") .build()); - // Paimon stores the materialized Fluss results with deduplicate for every Fluss engine. - Map options = new HashMap<>(); - if (mergeEngine != null) { - options.put(ConfigOptions.TABLE_MERGE_ENGINE.key(), mergeEngine); - } - if ("versioned".equals(mergeEngine)) { - options.put(ConfigOptions.TABLE_MERGE_ENGINE_VERSION_COLUMN.key(), "version"); - } - String procedureOptions = - options.entrySet().stream() - .map(entry -> entry.getKey() + "=" + entry.getValue()) - .collect(Collectors.joining(",", "'", "'")); TableInfo created = null; if (metadataExists) { // Resume after metadata creation stopped before the lake was enabled. - created = admin.createTableFromLake(tablePath, options).get(); + created = admin.createTableFromLake(tablePath, Collections.emptyMap()).get(); assertThat(created.getTableConfig().isDataLakeEnabled()).isFalse(); } - TableInfo enabled = assertEnableFlussProcedureSucceeds(tablePath, procedureOptions); + TableInfo enabled = assertEnableFlussProcedureSucceeds(tablePath, null); assertThat(enabled.hasPrimaryKey()).isTrue(); - if (mergeEngine == null) { - assertThat(enabled.getTableConfig().getMergeEngineType()).isEmpty(); - } else { - assertThat(enabled.getTableConfig().getMergeEngineType()) - .contains(MergeEngineType.fromString(mergeEngine)); - } + assertThat(enabled.getTableConfig().getMergeEngineType()).isEmpty(); if (metadataExists) { assertThat(enabled.getTableId()).isEqualTo(created.getTableId()); } - assertThat(assertEnableFlussProcedureSucceeds(tablePath, procedureOptions).getTableId()) + assertThat(assertEnableFlussProcedureSucceeds(tablePath, null).getTableId()) .isEqualTo(enabled.getTableId()); FileStoreTable paimonTable = (FileStoreTable) paimonCatalog.getTable( Identifier.create(DATABASE, tablePath.getTableName())); + assertThat(paimonTable.options()).doesNotContainKey(CoreOptions.BUCKET_KEY.key()); assertThat(paimonTable.latestSnapshot()).isEmpty(); assertThat(new CoreOptions(paimonTable.options()).mergeEngine()) .isEqualTo(CoreOptions.MergeEngine.DEDUPLICATE); @@ -607,19 +575,15 @@ void testEnablePrimaryKeyTableWithoutSnapshot(String mergeEngine, boolean metada @ParameterizedTest @CsvSource({ - "first-row,true,false,first_row,", - "partial-update,true,false,aggregation,", - "partial-update,false,true,aggregation,", - "aggregation,true,false,aggregation,", - "aggregation,false,true,,aggregation.remove-record-on-delete", - "aggregation,true,true,,aggregation.remove-record-on-delete" + "first-row,true,false,BulkLoad", + "partial-update,true,false,BulkLoad", + "partial-update,false,true,BulkLoad", + "aggregation,true,false,BulkLoad", + "aggregation,false,true,aggregation.remove-record-on-delete", + "aggregation,true,true,aggregation.remove-record-on-delete" }) - void testEnableNativePrimaryKeyMergeEngine( - String engine, - boolean ignoreDelete, - boolean removeOnDelete, - String flussEngine, - String expectedError) + void testRejectNativePrimaryKeyMergeEngine( + String engine, boolean ignoreDelete, boolean removeOnDelete, String expectedError) throws Exception { TablePath tablePath = TablePath.of( @@ -652,61 +616,14 @@ void testEnableNativePrimaryKeyMergeEngine( } Map nativeOptions = createPaimonTable(tablePath, schema.build()).options(); - if (expectedError != null) { - assertThatThrownBy( - () -> - tableEnvironment - .executeSql(procedureSql(tablePath, null)) - .await()) - .rootCause() - .isInstanceOf(InvalidTableException.class) - .hasMessageContaining(expectedError); - assertThat(admin.tableExists(tablePath).get()).isFalse(); - return; - } - - TableInfo enabled = assertEnableFlussProcedureSucceeds(tablePath, null); - assertThat(enabled.getTableConfig().getMergeEngineType()) - .contains(MergeEngineType.fromString(flussEngine)); - assertThat(enabled.getCustomProperties().toMap()) - .containsEntry("paimon.merge-engine", engine); - if ("partial-update".equals(engine)) { - assertThat(enabled.getCustomProperties().toMap()) - .containsEntry( - "paimon.partial-update.remove-record-on-delete", - Boolean.toString(removeOnDelete)); - } else if ("aggregation".equals(engine)) { - assertThat(enabled.getCustomProperties().toMap()) - .containsEntry( - "paimon.aggregation.remove-record-on-delete", - Boolean.toString(removeOnDelete)); - } - - // Re-enable and subsequent schema changes must also retain the native merge settings. - admin.alterTable( - tablePath, - Collections.singletonList( - TableChange.set( - ConfigOptions.TABLE_DATALAKE_ENABLED.key(), "false")), - false) - .get(); - assertThat(assertEnableFlussProcedureSucceeds(tablePath, null).getTableId()) - .isEqualTo(enabled.getTableId()); - admin.alterTable( - tablePath, - Collections.singletonList( - TableChange.addColumn( - "extra", - org.apache.fluss.types.DataTypes.INT(), - null, - TableChange.ColumnPosition.last())), - false) - .get(); + assertThatThrownBy(() -> tableEnvironment.executeSql(procedureSql(tablePath, null)).await()) + .rootCause() + .isInstanceOf(InvalidTableException.class) + .hasMessageContaining(expectedError); + assertThat(admin.tableExists(tablePath).get()).isFalse(); Identifier identifier = Identifier.create(DATABASE, tablePath.getTableName()); paimonCatalog.invalidateTable(identifier); - FileStoreTable paimonTable = (FileStoreTable) paimonCatalog.getTable(identifier); - assertThat(paimonTable.options()).containsAllEntriesOf(nativeOptions); - assertThat(paimonTable.rowType().getFieldNames()).containsExactly("id", "amount", "extra"); + assertThat(paimonCatalog.getTable(identifier).options()).isEqualTo(nativeOptions); } private TableInfo assertEnableFlussProcedureSucceeds(TablePath tablePath, String options) diff --git a/fluss-lake/fluss-lake-paimon/src/test/java/org/apache/fluss/lake/paimon/PaimonLakeCatalogTest.java b/fluss-lake/fluss-lake-paimon/src/test/java/org/apache/fluss/lake/paimon/PaimonLakeCatalogTest.java index 26658c16ecf..19d1fdab4f3 100644 --- a/fluss-lake/fluss-lake-paimon/src/test/java/org/apache/fluss/lake/paimon/PaimonLakeCatalogTest.java +++ b/fluss-lake/fluss-lake-paimon/src/test/java/org/apache/fluss/lake/paimon/PaimonLakeCatalogTest.java @@ -37,6 +37,7 @@ import org.apache.paimon.catalog.Identifier; import org.apache.paimon.data.GenericRow; import org.apache.paimon.schema.SchemaChange; +import org.apache.paimon.schema.TableSchema; import org.apache.paimon.table.FileStoreTable; import org.apache.paimon.table.Table; import org.apache.paimon.table.sink.BatchTableCommit; @@ -51,11 +52,15 @@ import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; +import javax.annotation.Nullable; + import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Optional; import static org.apache.fluss.config.ConfigOptions.TABLE_DATALAKE_ENABLED; @@ -614,7 +619,7 @@ void testAlterTableAddColumnIgnoresPaimonCommentsAndOptions() throws Exception { @Test void testPaimonSchemaCompatibilityChecksPhysicalMetadata() { - org.apache.paimon.schema.Schema schema = + TableSchema schema = createPaimonSchema( Arrays.asList("id", "pt"), Collections.singletonList("pt"), "1", "id"); @@ -629,10 +634,14 @@ void testPaimonSchemaCompatibilityChecksPhysicalMetadata() { .isFalse(); assertThat( isPaimonSchemaCompatible( - schema, createPaimonSchema( Arrays.asList("id", "pt"), - Collections.singletonList("pt"), + Collections.emptyList(), + "1", + "id"), + createPaimonSchema( + Arrays.asList("id", "pt"), + Collections.emptyList(), "1", "pt"))) .isFalse(); @@ -674,27 +683,76 @@ void testPaimonSchemaCompatibilityChecksPhysicalMetadata() { "id"))) .isTrue(); assertThat(CoreOptions.IMMUTABLE_OPTIONS).contains(CoreOptions.BUCKET_FUNCTION_TYPE.key()); - org.apache.paimon.schema.Schema schemaWithExplicitDefault = - createPaimonSchemaBuilder( - Arrays.asList("id", "pt"), - Collections.singletonList("pt"), - "1", - "id") - .option(CoreOptions.ROW_TRACKING_ENABLED.key(), "false") - .build(); + TableSchema schemaWithExplicitDefault = + TableSchema.create( + 0, + createPaimonSchemaBuilder( + Arrays.asList("id", "pt"), + Collections.singletonList("pt"), + "1", + "id") + .option(CoreOptions.ROW_TRACKING_ENABLED.key(), "false") + .build()); assertThat(isPaimonSchemaCompatible(schemaWithExplicitDefault, schema)).isTrue(); - org.apache.paimon.schema.Schema schemaWithDifferentImmutableOption = - createPaimonSchemaBuilder( - Arrays.asList("id", "pt"), - Collections.singletonList("pt"), - "1", - "id") - .option(PARTITION_GENERATE_LEGACY_NAME_OPTION_KEY, Boolean.FALSE.toString()) - .option(CoreOptions.BUCKET_FUNCTION_TYPE.key(), "mod") - .build(); + TableSchema schemaWithDifferentImmutableOption = + TableSchema.create( + 0, + createPaimonSchemaBuilder( + Arrays.asList("id", "pt"), + Collections.singletonList("pt"), + "1", + "id") + .option( + PARTITION_GENERATE_LEGACY_NAME_OPTION_KEY, + Boolean.FALSE.toString()) + .option(CoreOptions.BUCKET_FUNCTION_TYPE.key(), "mod") + .build()); assertThat(isPaimonSchemaCompatible(schema, schemaWithDifferentImmutableOption)).isFalse(); } + @ParameterizedTest + @CsvSource({ + "id,,id,true", + "'id,pt',pt,id,true", + "'id,pt',,'id,pt',true", + "'id,pt',,id,false", + "'id,pt',,'pt,id',false" + }) + void testDefaultBucketKey( + String primaryKeys, + @Nullable String partitionKey, + String bucketKey, + boolean compatible) { + TableSchema implicit = + TableSchema.create( + 0, + org.apache.paimon.schema.Schema.newBuilder() + .column("id", org.apache.paimon.types.DataTypes.INT().notNull()) + .column("pt", org.apache.paimon.types.DataTypes.STRING().notNull()) + .primaryKey(Arrays.asList(primaryKeys.split(","))) + .partitionKeys( + partitionKey == null + ? Collections.emptyList() + : Collections.singletonList(partitionKey)) + .option(CoreOptions.BUCKET.key(), "3") + .build()); + Map options = new HashMap<>(implicit.options()); + options.put(CoreOptions.BUCKET_KEY.key(), bucketKey); + TableSchema explicit = + TableSchema.create( + 0, + new org.apache.paimon.schema.Schema( + implicit.fields(), + implicit.partitionKeys(), + implicit.primaryKeys(), + options, + implicit.comment())); + + assertThat(isPaimonSchemaCompatible(implicit, explicit)).isEqualTo(compatible); + assertThat(isPaimonSchemaCompatible(explicit, implicit)).isEqualTo(compatible); + assertThat(implicit.options()).doesNotContainKey(CoreOptions.BUCKET_KEY.key()); + } + @ParameterizedTest @CsvSource({ "merge-engine,first-row", @@ -705,52 +763,77 @@ void testPaimonSchemaCompatibilityChecksPhysicalMetadata() { void testPaimonSchemaCompatibilityWithExistingMergeOptions(String key, String value) { List primaryKeys = Arrays.asList("id", "pt"); List partitionKeys = Collections.singletonList("pt"); - org.apache.paimon.schema.Schema existingSchema = - createPaimonSchemaBuilder(primaryKeys, partitionKeys, "1", "id") - .option(key, value) - .build(); - org.apache.paimon.schema.Schema expectedSchema = - createPaimonSchemaBuilder(primaryKeys, partitionKeys, "1", "id").build(); + TableSchema existingSchema = + TableSchema.create( + 0, + createPaimonSchemaBuilder(primaryKeys, partitionKeys, "1", "id") + .option(key, value) + .build()); + TableSchema expectedSchema = + TableSchema.create( + 0, + createPaimonSchemaBuilder(primaryKeys, partitionKeys, "1", "id").build()); assertThat(isPaimonSchemaCompatible(existingSchema, expectedSchema)).isFalse(); assertThat( isPaimonSchemaCompatible( existingSchema, - createPaimonSchemaBuilder(primaryKeys, partitionKeys, "2", "id") - .option(key, value) - .build())) + TableSchema.create( + 0, + createPaimonSchemaBuilder( + primaryKeys, partitionKeys, "2", "id") + .option(key, value) + .build()))) .isFalse(); assertThat( isPaimonSchemaCompatible( existingSchema, - createPaimonSchemaBuilder(primaryKeys, partitionKeys, "1", "id") - .option(key, value) - .option(CoreOptions.BUCKET_FUNCTION_TYPE.key(), "mod") - .build())) + TableSchema.create( + 0, + createPaimonSchemaBuilder( + primaryKeys, partitionKeys, "1", "id") + .option(key, value) + .option( + CoreOptions.BUCKET_FUNCTION_TYPE.key(), + "mod") + .build()))) .isFalse(); assertThat( isPaimonSchemaCompatible( existingSchema, - createPaimonSchemaBuilder(primaryKeys, partitionKeys, "1", "id") - .option(key, value) - .column("extra", org.apache.paimon.types.DataTypes.INT()) - .build())) + TableSchema.create( + 0, + createPaimonSchemaBuilder( + primaryKeys, partitionKeys, "1", "id") + .option(key, value) + .column( + "extra", + org.apache.paimon.types.DataTypes.INT()) + .build()))) .isFalse(); } @Test void testPaimonSchemaCompatibilityWithVarCharAndVarBinary() { - org.apache.paimon.schema.Schema existingSchema = - org.apache.paimon.schema.Schema.newBuilder() - .column("name", org.apache.paimon.types.DataTypes.VARCHAR(20).notNull()) - .column("payload", org.apache.paimon.types.DataTypes.VARBINARY(128)) - .build(); - org.apache.paimon.schema.Schema convertedSchema = - org.apache.paimon.schema.Schema.newBuilder() - .column("name", org.apache.paimon.types.DataTypes.STRING().notNull()) - .column("payload", org.apache.paimon.types.DataTypes.BYTES()) - .build(); + TableSchema existingSchema = + TableSchema.create( + 0, + org.apache.paimon.schema.Schema.newBuilder() + .column( + "name", + org.apache.paimon.types.DataTypes.VARCHAR(20).notNull()) + .column("payload", org.apache.paimon.types.DataTypes.VARBINARY(128)) + .build()); + TableSchema convertedSchema = + TableSchema.create( + 0, + org.apache.paimon.schema.Schema.newBuilder() + .column( + "name", + org.apache.paimon.types.DataTypes.STRING().notNull()) + .column("payload", org.apache.paimon.types.DataTypes.BYTES()) + .build()); // Fluss loses the declared lengths, but the converted types retain nullability. assertThat(isPaimonSchemaCompatible(existingSchema, convertedSchema)).isTrue(); @@ -759,77 +842,93 @@ void testPaimonSchemaCompatibilityWithVarCharAndVarBinary() { assertThat( isPaimonSchemaCompatible( existingSchema, - org.apache.paimon.schema.Schema.newBuilder() - .column("name", org.apache.paimon.types.DataTypes.STRING()) - .column( - "payload", - org.apache.paimon.types.DataTypes.BYTES()) - .build())) + TableSchema.create( + 0, + org.apache.paimon.schema.Schema.newBuilder() + .column( + "name", + org.apache.paimon.types.DataTypes.STRING()) + .column( + "payload", + org.apache.paimon.types.DataTypes.BYTES()) + .build()))) .isFalse(); assertThat( isPaimonSchemaCompatible( existingSchema, - org.apache.paimon.schema.Schema.newBuilder() - .column( - "name", - org.apache.paimon.types.DataTypes.STRING() - .notNull()) - .column( - "payload", - org.apache.paimon.types.DataTypes.BYTES().notNull()) - .build())) + TableSchema.create( + 0, + org.apache.paimon.schema.Schema.newBuilder() + .column( + "name", + org.apache.paimon.types.DataTypes.STRING() + .notNull()) + .column( + "payload", + org.apache.paimon.types.DataTypes.BYTES() + .notNull()) + .build()))) .isFalse(); } @Test void testPaimonSchemaCompatibilityWithNestedVarCharAndVarBinary() { - org.apache.paimon.schema.Schema existingSchema = - org.apache.paimon.schema.Schema.newBuilder() - .column( - "names", - org.apache.paimon.types.DataTypes.ARRAY( - org.apache.paimon.types.DataTypes.VARCHAR(20).notNull())) - .column( - "payloads", - org.apache.paimon.types.DataTypes.ARRAY( - org.apache.paimon.types.DataTypes.VARBINARY(128))) - .column( - "attributes", - org.apache.paimon.types.DataTypes.MAP( - org.apache.paimon.types.DataTypes.VARCHAR(20), - org.apache.paimon.types.DataTypes.VARBINARY(128))) - .column( - "person", - org.apache.paimon.types.DataTypes.ROW( - org.apache.paimon.types.DataTypes.FIELD( - 0, - "name", - org.apache.paimon.types.DataTypes.VARCHAR(20)))) - .build(); - org.apache.paimon.schema.Schema convertedSchema = - org.apache.paimon.schema.Schema.newBuilder() - .column( - "names", - org.apache.paimon.types.DataTypes.ARRAY( - org.apache.paimon.types.DataTypes.STRING().notNull())) - .column( - "payloads", - org.apache.paimon.types.DataTypes.ARRAY( - org.apache.paimon.types.DataTypes.BYTES())) - .column( - "attributes", - org.apache.paimon.types.DataTypes.MAP( - org.apache.paimon.types.DataTypes.STRING().notNull(), - org.apache.paimon.types.DataTypes.BYTES())) - .column( - "person", - org.apache.paimon.types.DataTypes.ROW( - org.apache.paimon.types.DataTypes.FIELD( - 1, - "name", - org.apache.paimon.types.DataTypes.STRING()))) - .build(); + TableSchema existingSchema = + TableSchema.create( + 0, + org.apache.paimon.schema.Schema.newBuilder() + .column( + "names", + org.apache.paimon.types.DataTypes.ARRAY( + org.apache.paimon.types.DataTypes.VARCHAR(20) + .notNull())) + .column( + "payloads", + org.apache.paimon.types.DataTypes.ARRAY( + org.apache.paimon.types.DataTypes.VARBINARY(128))) + .column( + "attributes", + org.apache.paimon.types.DataTypes.MAP( + org.apache.paimon.types.DataTypes.VARCHAR(20), + org.apache.paimon.types.DataTypes.VARBINARY(128))) + .column( + "person", + org.apache.paimon.types.DataTypes.ROW( + org.apache.paimon.types.DataTypes.FIELD( + 0, + "name", + org.apache.paimon.types.DataTypes.VARCHAR( + 20)))) + .build()); + TableSchema convertedSchema = + TableSchema.create( + 0, + org.apache.paimon.schema.Schema.newBuilder() + .column( + "names", + org.apache.paimon.types.DataTypes.ARRAY( + org.apache.paimon.types.DataTypes.STRING() + .notNull())) + .column( + "payloads", + org.apache.paimon.types.DataTypes.ARRAY( + org.apache.paimon.types.DataTypes.BYTES())) + .column( + "attributes", + org.apache.paimon.types.DataTypes.MAP( + org.apache.paimon.types.DataTypes.STRING() + .notNull(), + org.apache.paimon.types.DataTypes.BYTES())) + .column( + "person", + org.apache.paimon.types.DataTypes.ROW( + org.apache.paimon.types.DataTypes.FIELD( + 1, + "name", + org.apache.paimon.types.DataTypes + .STRING()))) + .build()); // Conversion drops bounded lengths and ROW field ids; Fluss also makes MAP keys non-null. assertThat(isPaimonSchemaCompatible(existingSchema, convertedSchema)).isTrue(); @@ -873,12 +972,16 @@ void testPaimonSchemaCompatibilityWithNestedVarCharAndVarBinary() { for (DataType[] types : mismatchedTypes) { assertThat( isPaimonSchemaCompatible( - org.apache.paimon.schema.Schema.newBuilder() - .column("value", types[0]) - .build(), - org.apache.paimon.schema.Schema.newBuilder() - .column("value", types[1]) - .build())) + TableSchema.create( + 0, + org.apache.paimon.schema.Schema.newBuilder() + .column("value", types[0]) + .build()), + TableSchema.create( + 0, + org.apache.paimon.schema.Schema.newBuilder() + .column("value", types[1]) + .build()))) .isFalse(); } } @@ -1154,26 +1257,30 @@ void testAlterDataLakeEnabledMaintainsLakeStreamOptionForCleanTable() throws Exc assertThat(table.options()).doesNotContainKey(LAKESTREAM_ENABLED_OPTION_KEY); } - private org.apache.paimon.schema.Schema createPaimonSchema( + private TableSchema createPaimonSchema( List primaryKeys, List partitionKeys, String bucket, String bucketKey) { return createPaimonSchema( primaryKeys, partitionKeys, bucket, bucketKey, Boolean.FALSE.toString()); } - private org.apache.paimon.schema.Schema createPaimonSchema( + private TableSchema createPaimonSchema( List primaryKeys, List partitionKeys, String bucket, String bucketKey, String partitionLegacyName) { - return createPaimonSchemaBuilder(primaryKeys, partitionKeys, bucket, bucketKey) - .option(PARTITION_GENERATE_LEGACY_NAME_OPTION_KEY, partitionLegacyName) - .build(); + return TableSchema.create( + 0, + createPaimonSchemaBuilder(primaryKeys, partitionKeys, bucket, bucketKey) + .option(PARTITION_GENERATE_LEGACY_NAME_OPTION_KEY, partitionLegacyName) + .build()); } - private org.apache.paimon.schema.Schema createPaimonSchemaWithoutPartitionLegacyName( + private TableSchema createPaimonSchemaWithoutPartitionLegacyName( List primaryKeys, List partitionKeys, String bucket, String bucketKey) { - return createPaimonSchemaBuilder(primaryKeys, partitionKeys, bucket, bucketKey).build(); + return TableSchema.create( + 0, + createPaimonSchemaBuilder(primaryKeys, partitionKeys, bucket, bucketKey).build()); } private org.apache.paimon.schema.Schema.Builder createPaimonSchemaBuilder( diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorService.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorService.java index 9c6bd258a11..282b270c43f 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorService.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorService.java @@ -26,6 +26,7 @@ import org.apache.fluss.config.ConfigOptions; import org.apache.fluss.config.Configuration; import org.apache.fluss.config.ConfigurationUtils; +import org.apache.fluss.config.TableConfig; import org.apache.fluss.config.cluster.AlterConfig; import org.apache.fluss.config.cluster.AlterConfigOpType; import org.apache.fluss.exception.ApiException; @@ -774,6 +775,7 @@ public CompletableFuture createTableFromLake( throw new TableAlreadyExistException("Table " + tablePath + " already exists."); } + validateBulkLoadSupport(tablePath, tableDescriptor); if (!databaseExists) { metadataManager.createDatabase( databaseName, DatabaseDescriptor.builder().build(), true); @@ -796,6 +798,28 @@ public CompletableFuture createTableFromLake( new CreateTableFromLakeResponse().setTableInfo(pbTableInfo)); } + private static void validateBulkLoadSupport( + TablePath tablePath, TableDescriptor tableDescriptor) { + if (!tableDescriptor.hasPrimaryKey()) { + return; + } + TableConfig tableConfig = + new TableConfig(Configuration.fromMap(tableDescriptor.getProperties())); + if (tableConfig.getMergeEngineType().isPresent()) { + throw new InvalidTableException( + String.format( + "Cannot create primary-key table %s from Paimon: BulkLoad does not support '%s'.", + tablePath, ConfigOptions.TABLE_MERGE_ENGINE.key())); + } + if (tableConfig.getKvTTL().isPresent() + || KvValueLayout.fromTableConfig(tableConfig).hasValueTag()) { + throw new InvalidTableException( + String.format( + "Cannot create primary-key table %s from Paimon: BulkLoad requires plain KV values without row TTL ('%s').", + tablePath, ConfigOptions.TABLE_KV_TTL.key())); + } + } + private void createTableInternal( TablePath tablePath, TableDescriptor tableDescriptor,