Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -194,16 +195,18 @@ public void alterTable(TablePath tablePath, List<TableChange> tableChanges, Cont
return;
}

Schema currentPaimonSchema = fileStoreTable.schema().toSchema();
TableSchema currentPaimonSchema = fileStoreTable.schema();

List<SchemaChange> 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(
Expand Down Expand Up @@ -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()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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);
}

Expand All @@ -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<DataField> 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<String, org.apache.paimon.types.DataType> 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()));
}

/**
Expand All @@ -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<DataField> 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
Expand All @@ -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<DataField> existingFields = existingSchema.fields();
List<DataField> newFields = newSchema.fields();
if (existingFields.size() != newFields.size()) {
Expand All @@ -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<String, String> existingOptions, Map<String, String> newOptions) {
Map<String, String> existingOptions, Map<String, String> 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<String> 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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<String, String> 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<String, String> 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);
Expand All @@ -176,26 +234,12 @@ void testCreatePrimaryKeyTableWithMergeSemantics(String engine, boolean ignoreDe
}
createPaimonTable(tablePath, schema.build());

TableInfo created =
admin.createTableFromLake(tablePath, Collections.<String, String>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.<String, String>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,
Expand Down Expand Up @@ -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()
Expand All @@ -332,12 +367,6 @@ void testSetPrimaryKeyOptionsNotDerivedFromLake(

Map<String, String> 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);
}
Expand Down
Loading
Loading