World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#14430] fix(iceberg): Expose Iceberg v3 column defaults on table load (#14659)
MaSaidc104ab0c790
diff --git a/api/src/main/java/org/apache/gravitino/rel/Column.java b/api/src/main/java/org/apache/gravitino/rel/Column.javaindex 9503d4ca0b..888751b483 100644--- a/api/src/main/java/org/apache/gravitino/rel/Column.java+++ b/api/src/main/java/org/apache/gravitino/rel/Column.java@@ -46,6 +46,12 @@ public interface Column {*/Expression DEFAULT_VALUE_NOT_SET = () -> Expression.EMPTY_EXPRESSION;+ /**+ * A default value that indicates the initial default value is not set. This is used in {@link+ * #initialDefaultValue()}.+ */+ Expression INITIAL_DEFAULT_VALUE_NOT_SET = () -> Expression.EMPTY_EXPRESSION;+/*** A default value that indicates the default value will be set to the current timestamp. This is* used in {@link #defaultValue()}.@@ -78,10 +84,35 @@ public interface Column {boolean autoIncrement();/**+ * Returns the default value used for new records that omit this column.+ *+ * <p>Catalogs that do not support column defaults leave this unset ({@link+ * Column#DEFAULT_VALUE_NOT_SET}).+ *+ * <p>For example, for Iceberg format-version 3 this maps to {@code write-default}: the value+ * writers fill in when a field is not supplied.+ ** @return The default value of this column, {@link Column#DEFAULT_VALUE_NOT_SET} if not specified*/Expression defaultValue();+ /**+ * Returns the default value used when reading stored records that lack this column, such as+ * records written before the column was added.+ *+ * <p>Catalogs that do not distinguish an initial default leave this unset ({@link+ * Column#INITIAL_DEFAULT_VALUE_NOT_SET}).+ *+ * <p>For example, for Iceberg format-version 3 this maps to {@code initial-default}: the value+ * assumed for rows written before the field was added.+ *+ * @return The initial default value, {@link Column#INITIAL_DEFAULT_VALUE_NOT_SET} if not+ * specified+ */+ default Expression initialDefaultValue() {+ return INITIAL_DEFAULT_VALUE_NOT_SET;+ }+/*** @return the {@link SupportsTags} if the column supports tag operations.* @throws UnsupportedOperationException if the column does not support tag operations.@@ -146,13 +177,46 @@ public interface Column {boolean nullable,boolean autoIncrement,Expression defaultValue) {+ return of(+ name,+ dataType,+ comment,+ nullable,+ autoIncrement,+ defaultValue,+ INITIAL_DEFAULT_VALUE_NOT_SET);+ }++ /**+ * Create a {@link Column} instance.+ *+ * @param name The name of the column.+ * @param dataType The data type of the column.+ * @param comment The comment of the column.+ * @param nullable True if the column may produce null values.+ * @param autoIncrement True if the column is an auto-increment column.+ * @param defaultValue The write-time default value of the column. {@link+ * Column#DEFAULT_VALUE_NOT_SET} if null.+ * @param initialDefaultValue The initial default value of the column. {@link+ * Column#INITIAL_DEFAULT_VALUE_NOT_SET} if null.+ * @return A {@link Column} instance.+ */+ static ColumnImpl of(+ String name,+ Type dataType,+ String comment,+ boolean nullable,+ boolean autoIncrement,+ Expression defaultValue,+ Expression initialDefaultValue) {return new ColumnImpl(name,dataType,comment,nullable,autoIncrement,- defaultValue == null ? DEFAULT_VALUE_NOT_SET : defaultValue);+ defaultValue == null ? DEFAULT_VALUE_NOT_SET : defaultValue,+ initialDefaultValue == null ? INITIAL_DEFAULT_VALUE_NOT_SET : initialDefaultValue);}/** The implementation of {@link Column} for users to use API. */@@ -163,6 +227,7 @@ public interface Column {private boolean nullable;private boolean autoIncrement;private Expression defaultValue;+ private Expression initialDefaultValue;private ColumnImpl(String name,@@ -170,7 +235,8 @@ public interface Column {String comment,boolean nullable,boolean autoIncrement,- Expression defaultValue) {+ Expression defaultValue,+ Expression initialDefaultValue) {Preconditions.checkArgument(!Strings.isNullOrEmpty(name), "Column name cannot be null");Preconditions.checkArgument(dataType != null, "Column data type cannot be null");this.name = name;@@ -179,6 +245,7 @@ public interface Column {this.nullable = nullable;this.autoIncrement = autoIncrement;this.defaultValue = defaultValue;+ this.initialDefaultValue = initialDefaultValue;}@Override@@ -211,6 +278,11 @@ public interface Column {return defaultValue;}+ @Override+ public Expression initialDefaultValue() {+ return initialDefaultValue;+ }+@Overridepublic boolean equals(Object o) {if (this == o) {@@ -225,12 +297,14 @@ public interface Column {&& Objects.equals(name, column.name)&& Objects.equals(dataType, column.dataType)&& Objects.equals(comment, column.comment)- && Objects.equals(defaultValue, column.defaultValue);+ && Objects.equals(defaultValue, column.defaultValue)+ && Objects.equals(initialDefaultValue, column.initialDefaultValue);}@Overridepublic int hashCode() {- return Objects.hash(name, dataType, comment, nullable, autoIncrement, defaultValue);+ return Objects.hash(+ name, dataType, comment, nullable, autoIncrement, defaultValue, initialDefaultValue);}}}diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueColumn.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueColumn.javaindex 038d3d0779..1f90cbfd08 100644--- a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueColumn.java+++ b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueColumn.java@@ -68,6 +68,8 @@ public class GlueColumn extends BaseColumn {col.nullable = nullable;col.autoIncrement = autoIncrement;col.defaultValue = defaultValue == null ? DEFAULT_VALUE_NOT_SET : defaultValue;+ col.initialDefaultValue =+ initialDefaultValue == null ? INITIAL_DEFAULT_VALUE_NOT_SET : initialDefaultValue;return col;}}diff --git a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcColumn.java b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcColumn.javaindex 300889c341..d6771b754f 100644--- a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcColumn.java+++ b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcColumn.java@@ -47,6 +47,8 @@ public class JdbcColumn extends BaseColumn {// DEFAULT_VALUE_NOT_SET if it is null in JSONSerde. But in case of the JdbcColumn is created// by other ways(e.g. integration test), we still need to handle the null case.jdbcColumn.defaultValue = defaultValue == null ? DEFAULT_VALUE_NOT_SET : defaultValue;+ jdbcColumn.initialDefaultValue =+ initialDefaultValue == null ? INITIAL_DEFAULT_VALUE_NOT_SET : initialDefaultValue;jdbcColumn.autoIncrement = autoIncrement;return jdbcColumn;}diff --git a/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/converter/TestJdbcColumnDefaultValueConverter.java b/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/converter/TestJdbcColumnDefaultValueConverter.javaindex 9733d67ef6..9a32164c0a 100644--- a/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/converter/TestJdbcColumnDefaultValueConverter.java+++ b/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/converter/TestJdbcColumnDefaultValueConverter.java@@ -23,6 +23,8 @@ import static org.apache.gravitino.rel.Column.DEFAULT_VALUE_NOT_SET;import com.google.common.io.BaseEncoding;import java.time.LocalDateTime;import java.time.OffsetDateTime;+import org.apache.gravitino.dto.rel.expressions.LiteralDTO;+import org.apache.gravitino.dto.util.DTOConverters;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.expressions.Expression;import org.apache.gravitino.rel.expressions.FunctionExpression;@@ -96,6 +98,22 @@ public class TestJdbcColumnDefaultValueConverter {"X'00ff'", converter.fromGravitino(Literals.of("0x00FF", Types.BinaryType.get())));}+ @Test+ void testSharedDtoBinaryDecodeStillRendersJdbcSql() {+ // Shared DTOConverters decodes 0x-prefixed binary for every catalog (#14609 / Iceberg load).+ // JDBC must still emit dialect binary SQL for that path, and keep unprefixed strings as+ // provider-specific quoted literals (e.g. PostgreSQL DEFAULT 'AB').+ Expression fromHex =+ DTOConverters.fromFunctionArg(+ LiteralDTO.builder().withDataType(Types.BinaryType.get()).withValue("0x4142").build());+ Assertions.assertEquals("X'4142'", converter.fromGravitino(fromHex));++ Expression fromUnprefixed =+ DTOConverters.fromFunctionArg(+ LiteralDTO.builder().withDataType(Types.BinaryType.get()).withValue("AB").build());+ Assertions.assertEquals("'AB'", converter.fromGravitino(fromUnprefixed));+ }+@ParameterizedTest@ValueSource(strings = {"0x0", "0xzz", "0x41'); DROP TABLE t; --"})void testMalformedBinaryDefaultsAreRejected(String value) {diff --git a/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/converter/TestPostgreSqlColumnDefaultValueConverter.java b/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/converter/TestPostgreSqlColumnDefaultValueConverter.javaindex c6a9b74d67..21c9d3c726 100644--- a/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/converter/TestPostgreSqlColumnDefaultValueConverter.java+++ b/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/converter/TestPostgreSqlColumnDefaultValueConverter.java@@ -22,6 +22,8 @@ import static org.apache.gravitino.rel.Column.DEFAULT_VALUE_OF_CURRENT_TIMESTAMPimport com.google.common.io.BaseEncoding;import org.apache.gravitino.catalog.jdbc.converter.JdbcTypeConverter;+import org.apache.gravitino.dto.rel.expressions.LiteralDTO;+import org.apache.gravitino.dto.util.DTOConverters;import org.apache.gravitino.rel.expressions.UnparsedExpression;import org.apache.gravitino.rel.expressions.literals.Literals;import org.apache.gravitino.rel.types.Types;@@ -47,6 +49,14 @@ public class TestPostgreSqlColumnDefaultValueConverter {converter.fromGravitino(Literals.of("0x" + hex, Types.BinaryType.get())));}+ @Test+ void testUnprefixedBinaryDefaultKeepsProviderInterpretation() {+ // Shared DTO decoder must not reject unprefixed binary strings; PostgreSQL quotes them.+ LiteralDTO dto =+ LiteralDTO.builder().withDataType(Types.BinaryType.get()).withValue("AB").build();+ Assertions.assertEquals("'AB'", converter.fromGravitino(DTOConverters.fromFunctionArg(dto)));+ }+@Testvoid testNullDefaultsAllowNativeCastsWithoutSwallowingExpressions() {JdbcTypeConverter.JdbcTypeBean type = new JdbcTypeConverter.JdbcTypeBean("uuid");diff --git a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/HudiColumn.java b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/HudiColumn.javaindex 540561c4d3..6674500fa6 100644--- a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/HudiColumn.java+++ b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/HudiColumn.java@@ -55,6 +55,8 @@ public class HudiColumn extends BaseColumn {hudiColumn.dataType = dataType;hudiColumn.nullable = nullable;hudiColumn.defaultValue = defaultValue == null ? DEFAULT_VALUE_NOT_SET : defaultValue;+ hudiColumn.initialDefaultValue =+ initialDefaultValue == null ? INITIAL_DEFAULT_VALUE_NOT_SET : initialDefaultValue;return hudiColumn;}}diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergColumn.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergColumn.javaindex 5056b77cf1..dce49a189f 100644--- a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergColumn.java+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergColumn.java@@ -44,6 +44,8 @@ public class IcebergColumn extends BaseColumn {icebergColumn.dataType = dataType;icebergColumn.nullable = nullable;icebergColumn.defaultValue = defaultValue == null ? DEFAULT_VALUE_NOT_SET : defaultValue;+ icebergColumn.initialDefaultValue =+ initialDefaultValue == null ? INITIAL_DEFAULT_VALUE_NOT_SET : initialDefaultValue;return icebergColumn;}}diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/ConvertUtil.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/ConvertUtil.javaindex 3443c5782e..6441667d82 100644--- a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/ConvertUtil.java+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/ConvertUtil.java@@ -19,16 +19,29 @@package org.apache.gravitino.catalog.lakehouse.iceberg.converter;import com.google.common.base.Preconditions;+import java.math.BigDecimal;+import java.nio.ByteBuffer;import java.util.Arrays;+import java.util.UUID;import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergColumn;import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergTable;import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.expressions.Expression;+import org.apache.gravitino.rel.expressions.literals.Literals;+import org.apache.gravitino.rel.types.Decimal;import org.apache.iceberg.Schema;+import org.apache.iceberg.expressions.Literal;import org.apache.iceberg.types.Type;import org.apache.iceberg.types.Types;+import org.apache.iceberg.util.ByteBuffers;+import org.apache.iceberg.util.DateTimeUtil;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;public class ConvertUtil {+ private static final Logger LOG = LoggerFactory.getLogger(ConvertUtil.class);+/*** Convert an Apache Iceberg Table to the corresponding schema information in the Iceberg.*@@ -67,6 +80,10 @@ public class ConvertUtil {/*** Convert the nested field of Iceberg to the Iceberg column.*+ * <p>For format-version 3 fields, Iceberg {@code write-default} maps to {@link+ * Column#defaultValue()} and {@code initial-default} maps to {@link+ * Column#initialDefaultValue()}.+ ** @param nestedField Iceberg nested field.* @return Gravitino Iceberg column*/@@ -76,9 +93,110 @@ public class ConvertUtil {.withNullable(nestedField.isOptional()).withComment(nestedField.doc()).withType(IcebergDataTypeConverter.CONVERTER.toGravitino(nestedField.type()))+ .withDefaultValue(+ fromIcebergLiteral(+ nestedField.writeDefaultLiteral(),+ nestedField.type(),+ Column.DEFAULT_VALUE_NOT_SET))+ .withInitialDefaultValue(+ fromIcebergLiteral(+ nestedField.initialDefaultLiteral(),+ nestedField.type(),+ Column.INITIAL_DEFAULT_VALUE_NOT_SET)).build();}+ private static Expression fromIcebergLiteral(+ Literal<?> icebergDefault, Type type, Expression unset) {+ if (icebergDefault == null) {+ return unset;+ }+ return toGravitinoLiteral(icebergDefault, type, unset);+ }++ private static Expression toGravitinoLiteral(+ Literal<?> icebergDefault, Type type, Expression unset) {+ Object value = icebergDefault.value();++ switch (type.typeId()) {+ case BOOLEAN:+ return Literals.booleanLiteral((Boolean) value);+ case INTEGER:+ return Literals.integerLiteral((Integer) value);+ case LONG:+ return Literals.longLiteral((Long) value);+ case FLOAT:+ return Literals.floatLiteral((Float) value);+ case DOUBLE:+ return Literals.doubleLiteral((Double) value);+ case STRING:+ return Literals.stringLiteral(value.toString());+ case DATE:+ return Literals.dateLiteral(DateTimeUtil.dateFromDays((Integer) value));+ case TIME:+ return Literals.timeLiteral(DateTimeUtil.timeFromMicros((Long) value));+ case TIMESTAMP:+ {+ Types.TimestampType timestampType = (Types.TimestampType) type;+ if (timestampType.shouldAdjustToUTC()) {+ // Iceberg timestamptz is a UTC instant (micros). Expose it as UTC LocalDateTime while+ // keeping TimestampType.withTimeZone so the type still says "with time zone".+ return Literals.of(+ DateTimeUtil.timestamptzFromMicros((Long) value).toLocalDateTime(),+ org.apache.gravitino.rel.types.Types.TimestampType.withTimeZone(+ FromIcebergType.PRECISION_MICROSECOND));+ }+ return Literals.of(+ DateTimeUtil.timestampFromMicros((Long) value),+ org.apache.gravitino.rel.types.Types.TimestampType.withoutTimeZone(+ FromIcebergType.PRECISION_MICROSECOND));+ }+ case TIMESTAMP_NANO:+ {+ Types.TimestampNanoType timestampNanoType = (Types.TimestampNanoType) type;+ if (timestampNanoType.shouldAdjustToUTC()) {+ // Same UTC-instant → LocalDateTime convention as TIMESTAMP with zone above.+ return Literals.of(+ DateTimeUtil.timestamptzFromNanos((Long) value).toLocalDateTime(),+ org.apache.gravitino.rel.types.Types.TimestampType.withTimeZone(+ FromIcebergType.PRECISION_NANOSECOND));+ }+ return Literals.of(+ DateTimeUtil.timestampFromNanos((Long) value),+ org.apache.gravitino.rel.types.Types.TimestampType.withoutTimeZone(+ FromIcebergType.PRECISION_NANOSECOND));+ }+ case DECIMAL:+ {+ Types.DecimalType decimalType = (Types.DecimalType) type;+ return Literals.decimalLiteral(+ Decimal.of((BigDecimal) value, decimalType.precision(), decimalType.scale()));+ }+ case UUID:+ return Literals.of(+ ((UUID) value).toString(), org.apache.gravitino.rel.types.Types.UUIDType.get());+ case FIXED:+ return Literals.of(+ toByteArray(value),+ org.apache.gravitino.rel.types.Types.FixedType.of(((Types.FixedType) type).length()));+ case BINARY:+ return Literals.of(+ toByteArray(value), org.apache.gravitino.rel.types.Types.BinaryType.get());+ default:+ // Nested types cannot carry non-null Iceberg defaults; other V3 types are left unset+ // rather than failing table load.+ LOG.warn("Dropping Iceberg column default of unsupported type {} as unset", type.typeId());+ return unset;+ }+ }++ private static byte[] toByteArray(Object value) {+ if (value instanceof byte[]) {+ return (byte[]) value;+ }+ return ByteBuffers.toByteArray((ByteBuffer) value);+ }+/*** Convert the Gravitino Iceberg table to the Gravitino StructType*diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestConvertUtil.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestConvertUtil.javaindex 32fd08d21f..0d9d4a87f3 100644--- a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestConvertUtil.java+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestConvertUtil.java@@ -22,6 +22,7 @@ import static org.apache.gravitino.catalog.lakehouse.iceberg.converter.IcebergDaimport com.google.common.collect.Maps;import java.time.Instant;+import java.time.LocalDateTime;import java.util.Arrays;import java.util.List;import java.util.Map;@@ -32,13 +33,16 @@ import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergColumn;import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergTable;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.expressions.literals.Literals;import org.apache.gravitino.rel.expressions.sorts.SortOrder;import org.apache.gravitino.rel.types.Types.ByteType;import org.apache.gravitino.rel.types.Types.ShortType;import org.apache.iceberg.Schema;+import org.apache.iceberg.expressions.Literal;import org.apache.iceberg.types.EdgeAlgorithm;import org.apache.iceberg.types.Type;import org.apache.iceberg.types.Types;+import org.apache.iceberg.util.DateTimeUtil;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Test;@@ -660,6 +664,170 @@ public class TestConvertUtil extends TestBaseConvert {Assertions.assertEquals(icebergColumn.comment(), doc);Assertions.assertTrue(icebergColumn.dataType() instanceof org.apache.gravitino.rel.types.Types.MapType);+ Assertions.assertEquals(Column.DEFAULT_VALUE_NOT_SET, icebergColumn.defaultValue());+ }++ @Test+ public void testFromNestedFieldMapsWriteAndInitialDefaults() {+ Types.NestedField region =+ Types.NestedField.builder()+ .withId(2)+ .withName("region")+ .asRequired()+ .ofType(Types.StringType.get())+ .withInitialDefault(Literal.of("US"))+ .withWriteDefault(Literal.of("EU"))+ .build();+ Types.NestedField n =+ Types.NestedField.builder()+ .withId(3)+ .withName("n")+ .asRequired()+ .ofType(Types.IntegerType.get())+ .withInitialDefault(Literal.of(7))+ .withWriteDefault(Literal.of(8))+ .build();++ IcebergColumn regionColumn = ConvertUtil.fromNestedField(region);+ Assertions.assertEquals(Literals.stringLiteral("EU"), regionColumn.defaultValue());+ Assertions.assertEquals(Literals.stringLiteral("US"), regionColumn.initialDefaultValue());++ IcebergColumn nColumn = ConvertUtil.fromNestedField(n);+ Assertions.assertEquals(Literals.integerLiteral(8), nColumn.defaultValue());+ Assertions.assertEquals(Literals.integerLiteral(7), nColumn.initialDefaultValue());+ }++ @Test+ public void testFromNestedFieldMapsOnlyInitialDefault() {+ Types.NestedField field =+ Types.NestedField.builder()+ .withId(1)+ .withName("region")+ .asRequired()+ .ofType(Types.StringType.get())+ .withInitialDefault(Literal.of("US"))+ .build();++ IcebergColumn column = ConvertUtil.fromNestedField(field);+ Assertions.assertEquals(Column.DEFAULT_VALUE_NOT_SET, column.defaultValue());+ Assertions.assertEquals(Literals.stringLiteral("US"), column.initialDefaultValue());+ }++ @Test+ public void testFromNestedFieldTimestamptzDefaultUsesUtcLocalDateTime() {+ // Iceberg timestamptz stores a UTC instant. ConvertUtil keeps TimestampType.withTimeZone and+ // materializes the value as that instant's UTC LocalDateTime (offset is not retained on the+ // literal value).+ long micros = 1_700_000_000_123_456L;+ Types.NestedField field =+ Types.NestedField.builder()+ .withId(1)+ .withName("event_ts")+ .asOptional()+ .ofType(Types.TimestampType.withZone())+ .withWriteDefault(Literal.of(micros).to(Types.TimestampType.withZone()))+ .withInitialDefault(Literal.of(micros).to(Types.TimestampType.withZone()))+ .build();++ IcebergColumn column = ConvertUtil.fromNestedField(field);+ Assertions.assertInstanceOf(+ org.apache.gravitino.rel.types.Types.TimestampType.class, column.dataType());+ org.apache.gravitino.rel.types.Types.TimestampType tsType =+ (org.apache.gravitino.rel.types.Types.TimestampType) column.dataType();+ Assertions.assertTrue(tsType.hasTimeZone());++ LocalDateTime expectedUtc = DateTimeUtil.timestamptzFromMicros(micros).toLocalDateTime();+ Assertions.assertEquals(+ expectedUtc,+ ((org.apache.gravitino.rel.expressions.literals.Literal<?>) column.defaultValue()).value());+ Assertions.assertEquals(+ expectedUtc,+ ((org.apache.gravitino.rel.expressions.literals.Literal<?>) column.initialDefaultValue())+ .value());+ }++ @Test+ public void testFromNestedFieldTimestamptzDefaultsRoundTripThroughDtoJson() throws Exception {+ // UTC LocalDateTime + TimestampType.withTimeZone must survive ColumnDTO JSON: clients that+ // only see the wire form still get a with-time-zone type and the UTC wall-clock value.+ long micros = 1_700_000_000_123_456L;+ Types.NestedField field =+ Types.NestedField.builder()+ .withId(1)+ .withName("event_ts")+ .asOptional()+ .ofType(Types.TimestampType.withZone())+ .withWriteDefault(Literal.of(micros).to(Types.TimestampType.withZone()))+ .withInitialDefault(Literal.of(micros).to(Types.TimestampType.withZone()))+ .build();++ IcebergColumn column = ConvertUtil.fromNestedField(field);+ LocalDateTime expectedUtc = DateTimeUtil.timestamptzFromMicros(micros).toLocalDateTime();++ org.apache.gravitino.dto.rel.ColumnDTO dto =+ org.apache.gravitino.dto.util.DTOConverters.toDTO(column);+ String json = org.apache.gravitino.json.JsonUtils.objectMapper().writeValueAsString(dto);+ Assertions.assertTrue(json.contains(expectedUtc.toString()), json);+ Assertions.assertTrue(json.contains("timestamp_tz"), json);++ org.apache.gravitino.dto.rel.ColumnDTO deser =+ org.apache.gravitino.json.JsonUtils.objectMapper()+ .readValue(json, org.apache.gravitino.dto.rel.ColumnDTO.class);+ Assertions.assertInstanceOf(+ org.apache.gravitino.rel.types.Types.TimestampType.class, deser.dataType());+ Assertions.assertTrue(+ ((org.apache.gravitino.rel.types.Types.TimestampType) deser.dataType()).hasTimeZone());+ Assertions.assertEquals(+ expectedUtc.toString(),+ ((org.apache.gravitino.dto.rel.expressions.LiteralDTO) deser.defaultValue()).value());+ Assertions.assertEquals(+ expectedUtc.toString(),+ ((org.apache.gravitino.dto.rel.expressions.LiteralDTO) deser.initialDefaultValue())+ .value());+ }++ @Test+ public void testFromNestedFieldBinaryDefaultsRoundTripThroughDtoJson() throws Exception {+ byte[] bytes = new byte[] {1, 2, 3};+ Types.NestedField field =+ Types.NestedField.builder()+ .withId(1)+ .withName("payload")+ .asOptional()+ .ofType(Types.BinaryType.get())+ .withWriteDefault(Literal.of(bytes))+ .withInitialDefault(Literal.of(bytes))+ .build();++ IcebergColumn column = ConvertUtil.fromNestedField(field);+ Assertions.assertArrayEquals(+ bytes,+ (byte[])+ ((org.apache.gravitino.rel.expressions.literals.Literal<?>) column.defaultValue())+ .value());+ Assertions.assertArrayEquals(+ bytes,+ (byte[])+ ((org.apache.gravitino.rel.expressions.literals.Literal<?>)+ column.initialDefaultValue())+ .value());++ org.apache.gravitino.dto.rel.ColumnDTO dto =+ org.apache.gravitino.dto.util.DTOConverters.toDTO(column);+ String json = org.apache.gravitino.json.JsonUtils.objectMapper().writeValueAsString(dto);+ Assertions.assertTrue(json.contains("\"0x010203\""));+ Assertions.assertFalse(json.contains("[B@"));++ org.apache.gravitino.dto.rel.ColumnDTO deser =+ org.apache.gravitino.json.JsonUtils.objectMapper()+ .readValue(json, org.apache.gravitino.dto.rel.ColumnDTO.class);+ Assertions.assertEquals(+ "0x010203",+ ((org.apache.gravitino.dto.rel.expressions.LiteralDTO) deser.defaultValue()).value());+ Assertions.assertEquals(+ "0x010203",+ ((org.apache.gravitino.dto.rel.expressions.LiteralDTO) deser.initialDefaultValue())+ .value());}private static void checkType(Type type, org.apache.gravitino.rel.types.Type expected) {diff --git a/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/GravitinoPaimonColumn.java b/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/GravitinoPaimonColumn.javaindex e69ac629f3..82dd960aae 100644--- a/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/GravitinoPaimonColumn.java+++ b/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/GravitinoPaimonColumn.java@@ -97,6 +97,8 @@ public class GravitinoPaimonColumn extends BaseColumn {paimonColumn.nullable = nullable;paimonColumn.autoIncrement = autoIncrement;paimonColumn.defaultValue = defaultValue == null ? DEFAULT_VALUE_NOT_SET : defaultValue;+ paimonColumn.initialDefaultValue =+ initialDefaultValue == null ? INITIAL_DEFAULT_VALUE_NOT_SET : initialDefaultValue;return paimonColumn;}}diff --git a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/HiveColumn.java b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/HiveColumn.javaindex 69b97abd44..418fde906e 100644--- a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/HiveColumn.java+++ b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/HiveColumn.java@@ -48,6 +48,8 @@ public class HiveColumn extends BaseColumn {hiveColumn.nullable = nullable;hiveColumn.autoIncrement = autoIncrement;hiveColumn.defaultValue = defaultValue == null ? DEFAULT_VALUE_NOT_SET : defaultValue;+ hiveColumn.initialDefaultValue =+ initialDefaultValue == null ? INITIAL_DEFAULT_VALUE_NOT_SET : initialDefaultValue;return hiveColumn;}}diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericColumn.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericColumn.javaindex 70994dcfd3..a7eb764a03 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericColumn.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericColumn.java@@ -125,6 +125,11 @@ public class GenericColumn implements Column, SupportsTags {return internalColumn.defaultValue();}+ @Override+ public Expression initialDefaultValue() {+ return internalColumn.initialDefaultValue();+ }+@Overridepublic boolean equals(Object obj) {if (this == obj) {diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestRelationalCatalog.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestRelationalCatalog.javaindex d91878994e..74c928b033 100644--- a/clients/client-java/src/test/java/org/apache/gravitino/client/TestRelationalCatalog.java+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestRelationalCatalog.java@@ -84,6 +84,7 @@ import org.apache.gravitino.rel.Table;import org.apache.gravitino.rel.TableCatalog;import org.apache.gravitino.rel.TableChange;import org.apache.gravitino.rel.expressions.distributions.Strategy;+import org.apache.gravitino.rel.expressions.literals.Literals;import org.apache.gravitino.rel.expressions.sorts.SortDirection;import org.apache.gravitino.rel.expressions.sorts.SortOrder;import org.apache.gravitino.rel.types.Type;@@ -770,10 +771,49 @@ public class TestRelationalCatalog extends TestBase {expected.columns()[i].autoIncrement(), actual.columns()[i].autoIncrement());Assertions.assertEquals(expected.columns()[i].defaultValue(), actual.columns()[i].defaultValue());+ Assertions.assertEquals(+ expected.columns()[i].initialDefaultValue(),+ actual.columns()[i].initialDefaultValue());});Assertions.assertArrayEquals(expected.partitioning(), actual.partitioning());}+ @Test+ public void testLoadTableExposesInitialDefaultValue() throws JsonProcessingException {+ NameIdentifier tableId = NameIdentifier.of("schema1", "table_with_defaults");+ Namespace fullNamespace = Namespace.of(metalakeName, catalogName, tableId.namespace().level(0));+ String tablePath =+ withSlash(RelationalCatalog.formatTableRequestPath(fullNamespace) + "/" + tableId.name());+ LiteralDTO seed =+ LiteralDTO.builder().withDataType(Types.StringType.get()).withValue("seed").build();+ ColumnDTO[] columns =+ new ColumnDTO[] {+ new ColumnDTO.Builder<>()+ .withName("col1")+ .withDataType(Types.StringType.get())+ .withComment("comment1")+ .withNullable(true)+ .withDefaultValue(seed)+ .withInitialDefaultValue(seed)+ .build()+ };+ TableDTO expectedTable =+ createMockTable(+ tableId.name(),+ columns,+ "comment",+ Collections.emptyMap(),+ new Partitioning[0],+ DistributionDTO.NONE,+ SortOrderDTO.EMPTY_SORT);+ buildMockResource(Method.GET, tablePath, null, new TableResponse(expectedTable), SC_OK);++ Table table = catalog.asTableCatalog().loadTable(tableId);+ assertTableEquals(fromDTO(expectedTable), table);+ Assertions.assertEquals(+ Literals.stringLiteral("seed"), table.columns()[0].initialDefaultValue());+ }+@Testpublic void testLoadTable() throws JsonProcessingException {NameIdentifier tableId = NameIdentifier.of("schema1", "table1");diff --git a/clients/client-python/gravitino/api/rel/column.py b/clients/client-python/gravitino/api/rel/column.pyindex 8631730e06..301dc19bf9 100644--- a/clients/client-python/gravitino/api/rel/column.py+++ b/clients/client-python/gravitino/api/rel/column.py@@ -42,6 +42,10 @@ class Column(ABC):DEFAULT_VALUE_NOT_SET = Expression.EMPTY_EXPRESSION"""A default value that indicates the default value is not set. This is used in `default_value()`"""+ INITIAL_DEFAULT_VALUE_NOT_SET = Expression.EMPTY_EXPRESSION+ """A default value that indicates the initial default value is not set. This is used in+ `initial_default_value()`"""+DEFAULT_VALUE_OF_CURRENT_TIMESTAMP: Expression = FunctionExpression.of("current_timestamp")@@ -97,7 +101,9 @@ class Column(ABC):@abstractmethoddef default_value(self) -> Expression:- """Get the default value of this column+ """Get the write-time default value of this column.++ For Iceberg format-version 3, this corresponds to ``write-default``.Returns:Expression:@@ -105,6 +111,18 @@ class Column(ABC):"""pass+ def initial_default_value(self) -> Expression:+ """Get the initial default value of this column.++ For Iceberg format-version 3, this corresponds to ``initial-default``. Catalogs that do+ not distinguish an initial default may leave this unset.++ Returns:+ Expression:+ The initial default value, `Column.INITIAL_DEFAULT_VALUE_NOT_SET` if not specified.+ """+ return Column.INITIAL_DEFAULT_VALUE_NOT_SET+def supports_tags(self) -> SupportsTags:"""Return the `SupportsTags` if the column supports tag operations.@@ -124,6 +142,7 @@ class Column(ABC):nullable: bool = True,auto_increment: bool = False,default_value: Optional[Expression] = None,+ initial_default_value: Optional[Expression] = None,) -> ColumnImpl:"""Create a `Column` instance.@@ -140,6 +159,9 @@ class Column(ABC):`True` if the column is an auto-increment column. Defaults to `False`.default_value (Optional[Expression], optional):The default value of this column, `Column.DEFAULT_VALUE_NOT_SET` if `None`. Defaults to `None`.+ initial_default_value (Optional[Expression], optional):+ The initial default value of this column, `Column.INITIAL_DEFAULT_VALUE_NOT_SET`+ if `None`. Defaults to `None`.Returns:ColumnImpl: A `Column` instance.@@ -153,6 +175,11 @@ class Column(ABC):default_value=(Column.DEFAULT_VALUE_NOT_SET if default_value is None else default_value),+ initial_default_value=(+ Column.INITIAL_DEFAULT_VALUE_NOT_SET+ if initial_default_value is None+ else initial_default_value+ ),)@@ -167,6 +194,7 @@ class ColumnImpl(Column):nullable: bool,auto_increment: bool,default_value: Optional[Expression],+ initial_default_value: Optional[Expression] = None,):Precondition.check_string_not_empty(name, "Column name cannot be null")Precondition.check_argument(@@ -178,6 +206,11 @@ class ColumnImpl(Column):self._nullable = nullableself._auto_increment = auto_incrementself._default_value = default_value+ self._initial_default_value = (+ Column.INITIAL_DEFAULT_VALUE_NOT_SET+ if initial_default_value is None+ else initial_default_value+ )def name(self) -> str:return self._name@@ -197,6 +230,9 @@ class ColumnImpl(Column):def default_value(self) -> Expression:return self._default_value+ def initial_default_value(self) -> Expression:+ return self._initial_default_value+def __eq__(self, other: ColumnImpl) -> bool:if not isinstance(other, ColumnImpl):return False@@ -208,6 +244,7 @@ class ColumnImpl(Column):self._nullable == other.nullable(),self._auto_increment == other.auto_increment(),self._default_value == other.default_value(),+ self._initial_default_value == other.initial_default_value(),])@@ -220,9 +257,15 @@ class ColumnImpl(Column):self._nullable,self._auto_increment,(- tuple(self._default_value)+ Noneif self._default_value is Column.DEFAULT_VALUE_NOT_SETelse self._default_value),+ (+ None+ if self._initial_default_value+ is Column.INITIAL_DEFAULT_VALUE_NOT_SET+ else self._initial_default_value+ ),))diff --git a/clients/client-python/gravitino/client/generic_column.py b/clients/client-python/gravitino/client/generic_column.pyindex 96995238c2..edd728f8d7 100644--- a/clients/client-python/gravitino/client/generic_column.py+++ b/clients/client-python/gravitino/client/generic_column.py@@ -70,6 +70,9 @@ class GenericColumn(Column, SupportsTags):def default_value(self) -> Expression:return self._internal_column.default_value()+ def initial_default_value(self) -> Expression:+ return self._internal_column.initial_default_value()+def __hash__(self) -> int:return hash(self._internal_column)diff --git a/clients/client-python/gravitino/dto/rel/column_dto.py b/clients/client-python/gravitino/dto/rel/column_dto.pyindex 87e30b14a4..aa642f8f32 100644--- a/clients/client-python/gravitino/dto/rel/column_dto.py+++ b/clients/client-python/gravitino/dto/rel/column_dto.py@@ -73,6 +73,20 @@ class ColumnDTO(Column, DataClassJsonMixin):)"""Whether the column is an auto-increment column."""+ # Keep after _auto_increment so positional constructors stay compatible with the+ # pre-initialDefaultValue field order (name, type, comment, default, nullable, autoIncrement).+ _initial_default_value: Optional[Union[Expression, List[Expression]]] = field(+ default_factory=lambda: Column.INITIAL_DEFAULT_VALUE_NOT_SET,+ metadata=config(+ field_name="initialDefaultValue",+ encoder=ColumnDefaultValueSerdes.serialize,+ decoder=ColumnDefaultValueSerdes.deserialize,+ exclude=lambda value: value is None+ or value is Column.INITIAL_DEFAULT_VALUE_NOT_SET,+ ),+ )+ """The initial default value of the column."""+def name(self) -> str:return self._name@@ -91,6 +105,9 @@ class ColumnDTO(Column, DataClassJsonMixin):def default_value(self) -> Union[Expression, List[Expression]]:return self._default_value+ def initial_default_value(self) -> Union[Expression, List[Expression]]:+ return self._initial_default_value+def validate(self) -> None:Precondition.check_string_not_empty(self._name, "Column name cannot be null or empty."@@ -123,6 +140,7 @@ class ColumnDTO(Column, DataClassJsonMixin):and self._nullable == other._nullableand self._auto_increment == other._auto_incrementand self._default_value == other._default_value+ and self._initial_default_value == other._initial_default_value)def __hash__(self) -> int:@@ -138,6 +156,12 @@ class ColumnDTO(Column, DataClassJsonMixin):if self._default_value is Column.DEFAULT_VALUE_NOT_SETelse self._default_value),+ (+ None+ if self._initial_default_value+ is Column.INITIAL_DEFAULT_VALUE_NOT_SET+ else self._initial_default_value+ ),))@@ -149,6 +173,7 @@ class ColumnDTO(Column, DataClassJsonMixin):self._nullable: bool = Trueself._auto_increment: bool = Falseself._default_value = None+ self._initial_default_value = Nonedef with_name(self, name: str) -> ColumnDTO.Builder:"""Sets the name of the column.@@ -222,6 +247,20 @@ class ColumnDTO(Column, DataClassJsonMixin):self._default_value = default_valuereturn self+ def with_initial_default_value(+ self, initial_default_value: Expression+ ) -> ColumnDTO.Builder:+ """Sets the initial default value of the column.++ Args:+ initial_default_value (Expression): The initial default value of the column.++ Returns:+ ColumnDTO.Builder: The builder instance.+ """+ self._initial_default_value = initial_default_value+ return self+def build(self) -> ColumnDTO:"""Builds a Column DTO based on the provided builder parameters.@@ -248,4 +287,9 @@ class ColumnDTO(Column, DataClassJsonMixin):if self._default_value is Noneelse self._default_value),+ _initial_default_value=(+ Column.INITIAL_DEFAULT_VALUE_NOT_SET+ if self._initial_default_value is None+ else self._initial_default_value+ ),)diff --git a/clients/client-python/gravitino/dto/rel/expressions/json_serdes/column_default_value_serdes.py b/clients/client-python/gravitino/dto/rel/expressions/json_serdes/column_default_value_serdes.pyindex 541eeaaf7d..3710976f56 100644--- a/clients/client-python/gravitino/dto/rel/expressions/json_serdes/column_default_value_serdes.py+++ b/clients/client-python/gravitino/dto/rel/expressions/json_serdes/column_default_value_serdes.py@@ -51,5 +51,9 @@ class ColumnDefaultValueSerdes(JsonSerializable[Expression]):@classmethoddef is_empty(cls, value):if isinstance(value, (Expression, list)):- return value is None or value is Column.DEFAULT_VALUE_NOT_SET+ return (+ value is None+ or value is Column.DEFAULT_VALUE_NOT_SET+ or value is Column.INITIAL_DEFAULT_VALUE_NOT_SET+ )return value is Nonediff --git a/clients/client-python/gravitino/dto/util/dto_converters.py b/clients/client-python/gravitino/dto/util/dto_converters.pyindex 9aedba7f40..902bb5f386 100644--- a/clients/client-python/gravitino/dto/util/dto_converters.py+++ b/clients/client-python/gravitino/dto/util/dto_converters.py@@ -126,7 +126,12 @@ class DTOConverters:dto = cast(LiteralDTO, arg)if dto.value() is None or dto.data_type() == Types.NullType.get():return Literals.NULL- return Literals.of(dto.value(), dto.data_type())+ data_type = dto.data_type()+ if DTOConverters._is_binary_or_fixed(data_type):+ return Literals.of(+ DTOConverters._decode_binary_hex(dto.value(), data_type), data_type+ )+ return Literals.of(dto.value(), data_type)if arg_type is FunctionArg.ArgType.FIELD:dto = cast(FieldReferenceDTO, arg)return NamedReference.field(dto.field_name())@@ -220,15 +225,29 @@ class DTOConverters:Returns:Column: The column."""- if dto.default_value() == Column.DEFAULT_VALUE_NOT_SET:+ if (+ dto.default_value() == Column.DEFAULT_VALUE_NOT_SET+ and dto.initial_default_value() == Column.INITIAL_DEFAULT_VALUE_NOT_SET+ ):return dto+ default_value = (+ Column.DEFAULT_VALUE_NOT_SET+ if dto.default_value() == Column.DEFAULT_VALUE_NOT_SET+ else DTOConverters.from_function_arg(dto.default_value())+ )+ initial_default_value = (+ Column.INITIAL_DEFAULT_VALUE_NOT_SET+ if dto.initial_default_value() == Column.INITIAL_DEFAULT_VALUE_NOT_SET+ else DTOConverters.from_function_arg(dto.initial_default_value())+ )return Column.of(dto.name(),dto.data_type(),dto.comment(),dto.nullable(),dto.auto_increment(),- DTOConverters.from_function_arg(dto.default_value()),+ default_value,+ initial_default_value,)@from_dto.register@@ -450,7 +469,11 @@ class DTOConverters:return LiteralDTO.NULLreturn (LiteralDTO.builder()- .with_value(str(expression.value()))+ .with_value(+ DTOConverters._literal_value_to_dto_string(+ expression.value(), expression.data_type()+ )+ ).with_data_type(expression.data_type()).build())@@ -546,6 +569,12 @@ class DTOConverters:or obj.default_value() is Column.DEFAULT_VALUE_NOT_SETelse DTOConverters.to_function_arg(obj.default_value()))+ .with_initial_default_value(+ Column.INITIAL_DEFAULT_VALUE_NOT_SET+ if obj.initial_default_value() is None+ or obj.initial_default_value() is Column.INITIAL_DEFAULT_VALUE_NOT_SET+ else DTOConverters.to_function_arg(obj.initial_default_value())+ ).build())@@ -844,3 +873,41 @@ class DTOConverters:raise IllegalArgumentException(f"Unknown change type: {change.__class__.__name__}")++ @staticmethod+ def _is_binary_or_fixed(data_type) -> bool:+ return isinstance(data_type, (Types.BinaryType, Types.FixedType))++ @staticmethod+ def _literal_value_to_dto_string(value, data_type) -> Optional[str]:+ if value is None:+ return None+ # Match Java DTOConverters / #14609: 0x + lowercase hex for binary/fixed bytes.+ if DTOConverters._is_binary_or_fixed(data_type) and isinstance(+ value, (bytes, bytearray)+ ):+ return "0x" + bytes(value).hex()+ return str(value)++ @staticmethod+ def _decode_binary_hex(value: str, data_type):+ # Match Java DTOConverters: decode 0x-prefixed hex; keep unprefixed strings for+ # provider-specific interpretation (#14609).+ if not value.lower().startswith("0x"):+ return value+ hex_value = value[2:]+ try:+ decoded = bytes.fromhex(hex_value)+ except ValueError as exc:+ raise IllegalArgumentException(+ "Invalid binary/fixed literal value: use 0x followed by hexadecimal byte pairs"+ ) from exc+ if (+ isinstance(data_type, Types.FixedType)+ and len(decoded) != data_type.length()+ ):+ raise IllegalArgumentException(+ f"Fixed literal length mismatch: expected {data_type.length()} bytes, "+ f"got {len(decoded)}"+ )+ return decodeddiff --git a/clients/client-python/tests/unittests/dto/rel/test_column_dto.py b/clients/client-python/tests/unittests/dto/rel/test_column_dto.pyindex 30b4159b37..642c9ec2cd 100644--- a/clients/client-python/tests/unittests/dto/rel/test_column_dto.py+++ b/clients/client-python/tests/unittests/dto/rel/test_column_dto.py@@ -77,6 +77,30 @@ class TestColumnDTO(unittest.TestCase):for idx in range(3)]+ def test_positional_constructor_preserves_nullable_and_auto_increment(self):+ # Pre-initialDefaultValue positional order must stay:+ # name, type, comment, default, nullable, autoIncrement.+ dto = ColumnDTO(+ "id",+ Types.IntegerType.get(),+ None,+ Column.DEFAULT_VALUE_NOT_SET,+ False,+ True,+ )+ self.assertEqual("id", dto.name())+ self.assertEqual(Types.IntegerType.get(), dto.data_type())+ self.assertIsNone(dto.comment())+ self.assertIs(Column.DEFAULT_VALUE_NOT_SET, dto.default_value())+ self.assertFalse(dto.nullable())+ self.assertTrue(dto.auto_increment())+ self.assertIs(Column.INITIAL_DEFAULT_VALUE_NOT_SET, dto.initial_default_value())+ # Serialization must not see a bool where an Expression is expected.+ parsed = json.loads(dto.to_json())+ self.assertFalse(parsed["nullable"])+ self.assertTrue(parsed["autoIncrement"])+ self.assertNotIn("initialDefaultValue", parsed)+def test_column_dto_equality(self):column_dto_1 = self._string_columns[1]column_dto_2 = self._string_columns[2]diff --git a/clients/client-python/tests/unittests/dto/util/test_dto_converters.py b/clients/client-python/tests/unittests/dto/util/test_dto_converters.pyindex fb7a0dd492..cdf3994a34 100644--- a/clients/client-python/tests/unittests/dto/util/test_dto_converters.py+++ b/clients/client-python/tests/unittests/dto/util/test_dto_converters.py@@ -127,8 +127,17 @@ class TestDTOConverters(unittest.TestCase):def test_from_function_arg_literal_dto(self):for data_type, value in TestDTOConverters.literals.items():expected = Literals.of(value=value, data_type=data_type)+ wire_value = value+ if isinstance(+ data_type, (Types.BinaryType, Types.FixedType)+ ) and isinstance(value, (bytes, bytearray)):+ # Wire form is 0x + lowercase hex (#14609 / Iceberg Appendix D).+ wire_value = "0x" + bytes(value).hex()literal_dto = (- LiteralDTO.builder().with_data_type(data_type).with_value(value).build()+ LiteralDTO.builder()+ .with_data_type(data_type)+ .with_value(wire_value)+ .build())self.assertTrue(DTOConverters.from_function_arg(literal_dto) == expected)@@ -527,10 +536,19 @@ class TestDTOConverters(unittest.TestCase):for data_type, value in TestDTOConverters.literals.items():literal = Literals.of(value=value, data_type=data_type)+ if value is None:+ expected_value = None+ elif isinstance(+ data_type, (Types.BinaryType, Types.FixedType)+ ) and isinstance(value, (bytes, bytearray)):+ # Wire form is 0x + lowercase hex (#14609 / Iceberg Appendix D).+ expected_value = "0x" + bytes(value).hex()+ else:+ expected_value = str(value)expected = (LiteralDTO.builder().with_data_type(data_type)- .with_value(str(value))+ .with_value(expected_value).build())self.assertTrue(DTOConverters.to_function_arg(literal) == expected)@@ -566,6 +584,52 @@ class TestDTOConverters(unittest.TestCase):):DTOConverters.to_function_arg(DistributionDTO.NONE)+ def test_binary_and_fixed_literal_hex_round_trip(self):+ bytes_value = bytes([0x01, 0x02, 0x03])+ for data_type in (Types.BinaryType.get(), Types.FixedType.of(3)):+ literal = Literals.of(value=bytes_value, data_type=data_type)+ dto = DTOConverters.to_function_arg(literal)+ self.assertIsInstance(dto, LiteralDTO)+ self.assertEqual("0x010203", cast(LiteralDTO, dto).value())+ round_trip = DTOConverters.from_function_arg(dto)+ self.assertEqual(literal, round_trip)++ # Uppercase hex after 0x must also decode.+ upper = (+ LiteralDTO.builder()+ .with_data_type(Types.BinaryType.get())+ .with_value("0x0A1B2C")+ .build()+ )+ decoded = DTOConverters.from_function_arg(upper)+ self.assertEqual(+ Literals.of(+ value=bytes([0x0A, 0x1B, 0x2C]), data_type=Types.BinaryType.get()+ ),+ decoded,+ )++ # Unprefixed wire values keep provider-specific string interpretation (#14609).+ unprefixed = (+ LiteralDTO.builder()+ .with_data_type(Types.BinaryType.get())+ .with_value("AB")+ .build()+ )+ self.assertEqual(+ Literals.of(value="AB", data_type=Types.BinaryType.get()),+ DTOConverters.from_function_arg(unprefixed),+ )+ self.assertEqual(+ "legacy",+ cast(+ LiteralDTO,+ DTOConverters.to_function_arg(+ Literals.of(value="legacy", data_type=Types.BinaryType.get())+ ),+ ).value(),+ )+def test_to_dto_raise_exception(self):with self.assertRaisesRegex(IllegalArgumentException, "Unsupported type"):DTOConverters.to_dto("test")diff --git a/common/src/main/java/org/apache/gravitino/dto/rel/ColumnDTO.java b/common/src/main/java/org/apache/gravitino/dto/rel/ColumnDTO.javaindex 8f13201a3d..403e631d3b 100644--- a/common/src/main/java/org/apache/gravitino/dto/rel/ColumnDTO.java+++ b/common/src/main/java/org/apache/gravitino/dto/rel/ColumnDTO.java@@ -65,6 +65,13 @@ public class ColumnDTO implements Column {@JsonDeserialize(using = JsonUtils.ColumnDefaultValueDeserializer.class)private Expression defaultValue = Column.DEFAULT_VALUE_NOT_SET;+ @JsonProperty("initialDefaultValue")+ @JsonSetter(nulls = Nulls.SKIP)+ @JsonInclude(JsonInclude.Include.NON_EMPTY)+ @JsonSerialize(using = JsonUtils.ColumnDefaultValueSerializer.class)+ @JsonDeserialize(using = JsonUtils.ColumnInitialDefaultValueDeserializer.class)+ private Expression initialDefaultValue = Column.INITIAL_DEFAULT_VALUE_NOT_SET;+private ColumnDTO() {}/**@@ -76,6 +83,7 @@ public class ColumnDTO implements Column {* @param nullable Whether the column value can be null.* @param autoIncrement Whether the column is an auto-increment column.* @param defaultValue The default value of the column.+ * @param initialDefaultValue The initial default value of the column.*/private ColumnDTO(String name,@@ -83,13 +91,16 @@ public class ColumnDTO implements Column {String comment,boolean nullable,boolean autoIncrement,- Expression defaultValue) {+ Expression defaultValue,+ Expression initialDefaultValue) {this.name = name;this.dataType = dataType;this.comment = comment;this.nullable = nullable;this.autoIncrement = autoIncrement;this.defaultValue = defaultValue == null ? Column.DEFAULT_VALUE_NOT_SET : defaultValue;+ this.initialDefaultValue =+ initialDefaultValue == null ? Column.INITIAL_DEFAULT_VALUE_NOT_SET : initialDefaultValue;}@Override@@ -122,6 +133,11 @@ public class ColumnDTO implements Column {return defaultValue;}+ @Override+ public Expression initialDefaultValue() {+ return initialDefaultValue;+ }+/*** Creates a new Builder to build a Column DTO.*@@ -156,6 +172,9 @@ public class ColumnDTO implements Column {/** The default value of the column. */protected Expression defaultValue;+ /** The initial default value of the column. */+ protected Expression initialDefaultValue;+/** Constructs a new Builder. */public Builder() {}@@ -225,6 +244,17 @@ public class ColumnDTO implements Column {return (S) this;}+ /**+ * Sets the initial default value of the column.+ *+ * @param initialDefaultValue The initial default value of the column.+ * @return The Builder instance.+ */+ public S withInitialDefaultValue(Expression initialDefaultValue) {+ this.initialDefaultValue = initialDefaultValue;+ return (S) this;+ }+/*** Builds a Column DTO based on the provided builder parameters.*@@ -234,7 +264,8 @@ public class ColumnDTO implements Column {public ColumnDTO build() {Preconditions.checkArgument(name != null, "Column name cannot be null");Preconditions.checkArgument(dataType != null, "Column data type cannot be null");- return new ColumnDTO(name, dataType, comment, nullable, autoIncrement, defaultValue);+ return new ColumnDTO(+ name, dataType, comment, nullable, autoIncrement, defaultValue, initialDefaultValue);}}diff --git a/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.java b/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.javaindex 0dc26c5e51..848846926a 100644--- a/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.java+++ b/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.java@@ -21,8 +21,10 @@ package org.apache.gravitino.dto.util;import static org.apache.gravitino.rel.expressions.transforms.Transforms.NAME_OF_IDENTITY;import com.fasterxml.jackson.core.JsonProcessingException;+import com.google.common.base.Preconditions;import com.google.common.io.BaseEncoding;import java.util.Arrays;+import java.util.Locale;import java.util.Map;import java.util.Optional;import org.apache.commons.lang3.ArrayUtils;@@ -140,6 +142,7 @@ import org.apache.gravitino.rel.partitions.ListPartition;import org.apache.gravitino.rel.partitions.Partition;import org.apache.gravitino.rel.partitions.Partitions;import org.apache.gravitino.rel.partitions.RangePartition;+import org.apache.gravitino.rel.types.Type;import org.apache.gravitino.rel.types.Types;import org.apache.gravitino.semantic.SemanticModel;import org.apache.gravitino.stats.Statistic;@@ -149,6 +152,15 @@ import org.apache.gravitino.tag.TagValueConstraint;/** Utility class for converting between DTOs and domain objects. */public class DTOConverters {+ /**+ * Gravitino's string-valued literal wire API encodes {@code binary}/{@code fixed} {@code byte[]}+ * values as {@code 0x} plus lowercase hex pairs (see #14609). This is a reversible encoding of+ * the same bytes Iceberg stores as unprefixed hex in Appendix D / REST OpenAPI.+ */+ private static final BaseEncoding BINARY_HEX = BaseEncoding.base16().lowerCase();++ private static final String BINARY_HEX_PREFIX = "0x";+private DTOConverters() {}/**@@ -286,6 +298,11 @@ public class DTOConverters {|| column.defaultValue().equals(Column.DEFAULT_VALUE_NOT_SET))? Column.DEFAULT_VALUE_NOT_SET: toFunctionArg(column.defaultValue()))+ .withInitialDefaultValue(+ (column.initialDefaultValue() == null+ || column.initialDefaultValue().equals(Column.INITIAL_DEFAULT_VALUE_NOT_SET))+ ? Column.INITIAL_DEFAULT_VALUE_NOT_SET+ : toFunctionArg(column.initialDefaultValue())).build();}@@ -807,16 +824,11 @@ public class DTOConverters {return LiteralDTO.NULL;}- Object value = ((Literal) expression).value();- // Binary literals use an explicit hexadecimal representation on the string-valued wire API.- // byte[].toString() is an object identity and cannot preserve the literal's bytes.- if (((Literal) expression).dataType() instanceof Types.BinaryType- && value instanceof byte[]) {- value = "0x" + BaseEncoding.base16().lowerCase().encode((byte[]) value);- }+ Literal<?> literal = (Literal<?>) expression;+ Object value = literal.value();return LiteralDTO.builder()- .withValue(value == null ? null : value.toString())- .withDataType(((Literal) expression).dataType())+ .withValue(value == null ? null : literalValueToDtoString(value, literal.dataType()))+ .withDataType(literal.dataType()).build();} else if (expression instanceof NamedReference.FieldReference) {return FieldReferenceDTO.builder()@@ -1142,11 +1154,13 @@ public class DTOConverters {public static Expression fromFunctionArg(FunctionArg arg) {switch (arg.argType()) {case LITERAL:- if (((LiteralDTO) arg).value() == null- || ((LiteralDTO) arg).dataType().equals(Types.NullType.get())) {+ LiteralDTO literalDTO = (LiteralDTO) arg;+ if (literalDTO.value() == null || literalDTO.dataType().equals(Types.NullType.get())) {return Literals.NULL;}- return Literals.of(((LiteralDTO) arg).value(), ((LiteralDTO) arg).dataType());+ Type dataType = literalDTO.dataType();+ Object value = literalValueFromDtoString(literalDTO.value(), dataType);+ return Literals.of(value, dataType);case FIELD:return NamedReference.field(((FieldReferenceDTO) arg).fieldName());case FUNCTION:@@ -1311,7 +1325,10 @@ public class DTOConverters {* @return The column.*/public static Column fromDTO(ColumnDTO column) {- if (column.defaultValue().equals(Column.DEFAULT_VALUE_NOT_SET)) {+ boolean defaultUnset = column.defaultValue().equals(Column.DEFAULT_VALUE_NOT_SET);+ boolean initialUnset =+ column.initialDefaultValue().equals(Column.INITIAL_DEFAULT_VALUE_NOT_SET);+ if (defaultUnset && initialUnset) {return column;}return Column.of(@@ -1320,7 +1337,12 @@ public class DTOConverters {column.comment(),column.nullable(),column.autoIncrement(),- fromFunctionArg((FunctionArg) column.defaultValue()));+ defaultUnset+ ? Column.DEFAULT_VALUE_NOT_SET+ : fromFunctionArg((FunctionArg) column.defaultValue()),+ initialUnset+ ? Column.INITIAL_DEFAULT_VALUE_NOT_SET+ : fromFunctionArg((FunctionArg) column.initialDefaultValue()));}/**@@ -1651,4 +1673,47 @@ public class DTOConverters {throw new IllegalArgumentException("Unsupported policy content type: " + policyContentDTO.getClass());}++ private static boolean isBinaryOrFixed(Type dataType) {+ return dataType instanceof Types.BinaryType || dataType instanceof Types.FixedType;+ }++ private static String literalValueToDtoString(Object value, Type dataType) {+ // byte[].toString() is an object identity and cannot preserve the literal's bytes.+ if (isBinaryOrFixed(dataType) && value instanceof byte[]) {+ return BINARY_HEX_PREFIX + BINARY_HEX.encode((byte[]) value);+ }+ return value.toString();+ }++ /**+ * Decodes {@code 0x}-prefixed hex for binary/fixed. Unprefixed values keep their previous string+ * interpretation for provider-specific handling (#14609).+ */+ private static Object literalValueFromDtoString(String value, Type dataType) {+ if (!isBinaryOrFixed(dataType) || value == null) {+ return value;+ }+ if (!value.regionMatches(true, 0, BINARY_HEX_PREFIX, 0, BINARY_HEX_PREFIX.length())) {+ // Retain unprefixed wire values for JDBC and other providers (e.g. DEFAULT 'AB').+ return value;+ }+ String hex = value.substring(BINARY_HEX_PREFIX.length());+ byte[] bytes;+ try {+ bytes = BINARY_HEX.decode(hex.toLowerCase(Locale.ROOT));+ } catch (IllegalArgumentException e) {+ throw new IllegalArgumentException(+ "Invalid binary/fixed literal value: use 0x followed by hexadecimal byte pairs", e);+ }+ if (dataType instanceof Types.FixedType) {+ int expected = ((Types.FixedType) dataType).length();+ Preconditions.checkArgument(+ bytes.length == expected,+ "Fixed literal length mismatch: expected %s bytes, got %s",+ expected,+ bytes.length);+ }+ return bytes;+ }}diff --git a/common/src/main/java/org/apache/gravitino/json/JsonUtils.java b/common/src/main/java/org/apache/gravitino/json/JsonUtils.javaindex 4757df5e14..5ca0baec5c 100644--- a/common/src/main/java/org/apache/gravitino/json/JsonUtils.java+++ b/common/src/main/java/org/apache/gravitino/json/JsonUtils.java@@ -1382,7 +1382,9 @@ public class JsonUtils {@Overridepublic void serialize(Expression value, JsonGenerator gen, SerializerProvider serializers)throws IOException {- if (value == null || value.equals(Column.DEFAULT_VALUE_NOT_SET)) {+ if (value == null+ || value.equals(Column.DEFAULT_VALUE_NOT_SET)+ || value.equals(Column.INITIAL_DEFAULT_VALUE_NOT_SET)) {return;}writeFunctionArg((FunctionArg) value, gen);@@ -1390,7 +1392,9 @@ public class JsonUtils {@Overridepublic boolean isEmpty(SerializerProvider provider, Expression value) {- return value == null || value.equals(Column.DEFAULT_VALUE_NOT_SET);+ return value == null+ || value.equals(Column.DEFAULT_VALUE_NOT_SET)+ || value.equals(Column.INITIAL_DEFAULT_VALUE_NOT_SET);}}@@ -1406,6 +1410,18 @@ public class JsonUtils {}}+ /** Custom JSON deserializer for Column initial default value. */+ public static class ColumnInitialDefaultValueDeserializer extends JsonDeserializer<Expression> {+ @Override+ public Expression deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {+ JsonNode node = p.getCodec().readTree(p);+ if (node == null || node.isNull()) {+ return Column.INITIAL_DEFAULT_VALUE_NOT_SET;+ }+ return readFunctionArg(node);+ }+ }+/** Custom JSON deserializer for StatisticValue objects. */public static class StatisticValueDeserializer extends JsonDeserializer<StatisticValue> {@Overridediff --git a/common/src/test/java/org/apache/gravitino/dto/util/TestDTOConverters.java b/common/src/test/java/org/apache/gravitino/dto/util/TestDTOConverters.javaindex 500be36570..3e43f08523 100644--- a/common/src/test/java/org/apache/gravitino/dto/util/TestDTOConverters.java+++ b/common/src/test/java/org/apache/gravitino/dto/util/TestDTOConverters.java@@ -33,6 +33,8 @@ import org.apache.gravitino.dto.job.JobTemplateDTO;import org.apache.gravitino.dto.job.ShellJobTemplateDTO;import org.apache.gravitino.dto.job.SparkJobTemplateDTO;import org.apache.gravitino.dto.policy.PolicyContentDTO;+import org.apache.gravitino.dto.rel.ColumnDTO;+import org.apache.gravitino.dto.rel.expressions.FunctionArg;import org.apache.gravitino.dto.rel.expressions.LiteralDTO;import org.apache.gravitino.dto.rel.partitioning.ListPartitioningDTO;import org.apache.gravitino.dto.rel.partitioning.RangePartitioningDTO;@@ -43,9 +45,12 @@ import org.apache.gravitino.dto.rel.partitions.RangePartitionDTO;import org.apache.gravitino.job.JobTemplate;import org.apache.gravitino.job.ShellJobTemplate;import org.apache.gravitino.job.SparkJobTemplate;+import org.apache.gravitino.json.JsonUtils;import org.apache.gravitino.policy.AccessControlContent;import org.apache.gravitino.policy.PolicyContent;import org.apache.gravitino.policy.PolicyContents;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.expressions.Expression;import org.apache.gravitino.rel.expressions.literals.Literal;import org.apache.gravitino.rel.expressions.literals.Literals;import org.apache.gravitino.rel.expressions.transforms.Transform;@@ -66,13 +71,30 @@ public class TestDTOConverters {@ParameterizedTest@ValueSource(strings = {"4142", "0080ff", ""})void testBinaryLiteralBytesUseHex(String hex) {+ byte[] bytes = BaseEncoding.base16().lowerCase().decode(hex);LiteralDTO dto =- (LiteralDTO)- DTOConverters.toFunctionArg(- Literals.of(BaseEncoding.base16().lowerCase().decode(hex), Types.BinaryType.get()));+ (LiteralDTO) DTOConverters.toFunctionArg(Literals.of(bytes, Types.BinaryType.get()));Assertions.assertEquals(Types.BinaryType.get(), dto.dataType());Assertions.assertEquals("0x" + hex, dto.value());- Assertions.assertEquals("0x" + hex, ((Literal<?>) DTOConverters.fromFunctionArg(dto)).value());+ Assertions.assertArrayEquals(+ bytes, (byte[]) ((Literal<?>) DTOConverters.fromFunctionArg(dto)).value());+ }++ @Test+ void testBinaryOrFixedLiteralKeepsUnprefixedWireValue() {+ LiteralDTO unprefixedBinary =+ LiteralDTO.builder().withDataType(Types.BinaryType.get()).withValue("AB").build();+ Literal<?> binaryLiteral = (Literal<?>) DTOConverters.fromFunctionArg(unprefixedBinary);+ Assertions.assertEquals(Types.BinaryType.get(), binaryLiteral.dataType());+ Assertions.assertEquals("AB", binaryLiteral.value());++ LiteralDTO unprefixedFixed =+ LiteralDTO.builder().withDataType(Types.FixedType.of(3)).withValue("legacy").build();+ Literal<?> fixedLiteral = (Literal<?>) DTOConverters.fromFunctionArg(unprefixedFixed);+ Assertions.assertEquals(Types.FixedType.of(3), fixedLiteral.dataType());+ Assertions.assertEquals("legacy", fixedLiteral.value());++ // byte[] still round-trips through the 0x wire form.Assertions.assertEquals("legacy",((LiteralDTO) DTOConverters.toFunctionArg(Literals.of("legacy", Types.BinaryType.get())))@@ -415,4 +437,43 @@ public class TestDTOConverters {Assertions.assertInstanceOf(AccessControlContent.class, roundTripped);Assertions.assertEquals(content, roundTripped);}++ @Test+ void testBinaryAndFixedLiteralsUseHexEncoding() throws Exception {+ byte[] bytes = new byte[] {1, 2, 3};+ Expression binaryLiteral = Literals.of(bytes, Types.BinaryType.get());+ Expression fixedLiteral = Literals.of(bytes, Types.FixedType.of(3));++ FunctionArg binaryArg = DTOConverters.toFunctionArg(binaryLiteral);+ FunctionArg fixedArg = DTOConverters.toFunctionArg(fixedLiteral);+ Assertions.assertInstanceOf(LiteralDTO.class, binaryArg);+ Assertions.assertInstanceOf(LiteralDTO.class, fixedArg);+ // Wire format: 0x + lowercase hex (#14609); reversible encoding of Iceberg-style bytes.+ Assertions.assertEquals("0x010203", ((LiteralDTO) binaryArg).value());+ Assertions.assertEquals("0x010203", ((LiteralDTO) fixedArg).value());+ Assertions.assertFalse(((LiteralDTO) binaryArg).value().contains("[B@"));++ Literal<?> roundTripBinary = (Literal<?>) DTOConverters.fromFunctionArg(binaryArg);+ Literal<?> roundTripFixed = (Literal<?>) DTOConverters.fromFunctionArg(fixedArg);+ Assertions.assertArrayEquals(bytes, (byte[]) roundTripBinary.value());+ Assertions.assertArrayEquals(bytes, (byte[]) roundTripFixed.value());++ // Uppercase hex after 0x must also parse.+ byte[] mixedCaseBytes = new byte[] {0x0a, 0x1b, (byte) 0x2c};+ LiteralDTO uppercase =+ LiteralDTO.builder().withDataType(Types.BinaryType.get()).withValue("0x0A1B2C").build();+ Assertions.assertArrayEquals(+ mixedCaseBytes, (byte[]) ((Literal<?>) DTOConverters.fromFunctionArg(uppercase)).value());++ ColumnDTO viaConverters =+ DTOConverters.toDTO(+ Column.of(+ "bin_col", Types.BinaryType.get(), null, true, false, binaryLiteral, fixedLiteral));+ String json = JsonUtils.objectMapper().writeValueAsString(viaConverters);+ Assertions.assertTrue(json.contains("\"0x010203\""));+ Assertions.assertFalse(json.contains("[B@"));+ ColumnDTO deser = JsonUtils.objectMapper().readValue(json, ColumnDTO.class);+ Assertions.assertEquals("0x010203", ((LiteralDTO) deser.defaultValue()).value());+ Assertions.assertEquals("0x010203", ((LiteralDTO) deser.initialDefaultValue()).value());+ }}diff --git a/core/src/main/java/org/apache/gravitino/catalog/CapabilityHelpers.java b/core/src/main/java/org/apache/gravitino/catalog/CapabilityHelpers.javaindex 31aa3820ae..cff86e212e 100644--- a/core/src/main/java/org/apache/gravitino/catalog/CapabilityHelpers.java+++ b/core/src/main/java/org/apache/gravitino/catalog/CapabilityHelpers.java@@ -19,6 +19,7 @@package org.apache.gravitino.catalog;import static org.apache.gravitino.rel.Column.DEFAULT_VALUE_NOT_SET;+import static org.apache.gravitino.rel.Column.INITIAL_DEFAULT_VALUE_NOT_SET;import static org.apache.gravitino.rel.expressions.transforms.Transforms.NAME_OF_IDENTITY;import static org.apache.gravitino.utils.NameIdentifierUtil.getCatalogIdentifier;@@ -668,7 +669,8 @@ public class CapabilityHelpers {column.comment(),column.nullable(),column.autoIncrement(),- column.defaultValue());+ column.defaultValue(),+ column.initialDefaultValue());}static String applyCapabilitiesOnName(@@ -716,6 +718,7 @@ public class CapabilityHelpers {private static void applyColumnDefaultValue(Column column, Capability capabilities) {applyColumnDefaultValue(column.name(), column.defaultValue(), capabilities);+ applyColumnInitialDefaultValue(column.name(), column.initialDefaultValue());}private static void applyColumnDefaultValue(@@ -725,6 +728,23 @@ public class CapabilityHelpers {capabilities.columnDefaultValue().unsupportedMessage() + " Illegal column: " + columnName);}+ /**+ * Rejects setting {@code initialDefaultValue} on create/add-column. Catalogs that support write+ * defaults (e.g. MySQL) still do not apply Iceberg-style initial defaults, so reusing {@link+ * Capability#columnDefaultValue()} would accept a value the catalog silently drops. Until a+ * catalog can write initial defaults, require unset ({@code null} or {@link+ * Column#INITIAL_DEFAULT_VALUE_NOT_SET}).+ */+ private static void applyColumnInitialDefaultValue(+ String columnName, Expression initialDefaultValue) {+ Preconditions.checkArgument(+ initialDefaultValue == null || INITIAL_DEFAULT_VALUE_NOT_SET.equals(initialDefaultValue),+ "Column initial default value is read-only for now: catalogs may return it on load "+ + "(e.g. Iceberg v3), but setting it on create/add-column is not supported by any "+ + "catalog capability yet. Illegal column: "+ + columnName);+ }+private static void applyNameSpecification(Capability.Scope scope, String name, Capability capabilities) {Preconditions.checkArgument(diff --git a/core/src/main/java/org/apache/gravitino/connector/BaseColumn.java b/core/src/main/java/org/apache/gravitino/connector/BaseColumn.javaindex ec1d7d6547..5ff47aac71 100644--- a/core/src/main/java/org/apache/gravitino/connector/BaseColumn.java+++ b/core/src/main/java/org/apache/gravitino/connector/BaseColumn.java@@ -45,6 +45,8 @@ public abstract class BaseColumn implements Column {protected Expression defaultValue;+ protected Expression initialDefaultValue = Column.INITIAL_DEFAULT_VALUE_NOT_SET;+/*** Returns the name of the column.*@@ -98,6 +100,15 @@ public abstract class BaseColumn implements Column {return defaultValue;}+ /**+ * @return The initial default value of this column, {@link Column#INITIAL_DEFAULT_VALUE_NOT_SET}+ * if not specified+ */+ @Override+ public Expression initialDefaultValue() {+ return initialDefaultValue;+ }+/*** Builder interface for creating instances of {@link BaseColumn}.*@@ -118,6 +129,8 @@ public abstract class BaseColumn implements Column {SELF withDefaultValue(Expression defaultValue);+ SELF withInitialDefaultValue(Expression initialDefaultValue);+T build();}@@ -137,6 +150,8 @@ public abstract class BaseColumn implements Column {protected boolean autoIncrement = false;protected Expression defaultValue;+ protected Expression initialDefaultValue;+/*** Sets the name of the column.*@@ -209,6 +224,18 @@ public abstract class BaseColumn implements Column {return self();}+ /**+ * Sets the initial default value of the column.+ *+ * @param initialDefaultValue The initial default value of the column.+ * @return The builder instance.+ */+ @Override+ public SELF withInitialDefaultValue(Expression initialDefaultValue) {+ this.initialDefaultValue = initialDefaultValue;+ return self();+ }+/*** Builds the instance of the column with the provided attributes.*diff --git a/core/src/main/java/org/apache/gravitino/connector/GenericColumn.java b/core/src/main/java/org/apache/gravitino/connector/GenericColumn.javaindex 7cf435c81d..98c22cf059 100644--- a/core/src/main/java/org/apache/gravitino/connector/GenericColumn.java+++ b/core/src/main/java/org/apache/gravitino/connector/GenericColumn.java@@ -54,6 +54,8 @@ public class GenericColumn extends BaseColumn {column.dataType = dataType;column.nullable = nullable;column.defaultValue = defaultValue == null ? DEFAULT_VALUE_NOT_SET : defaultValue;+ column.initialDefaultValue =+ initialDefaultValue == null ? INITIAL_DEFAULT_VALUE_NOT_SET : initialDefaultValue;column.autoIncrement = autoIncrement;return column;}diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestCapabilityHelpers.java b/core/src/test/java/org/apache/gravitino/catalog/TestCapabilityHelpers.javaindex 6cff282079..0ea204f93b 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestCapabilityHelpers.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestCapabilityHelpers.java@@ -32,6 +32,7 @@ import org.apache.gravitino.exceptions.NoSuchCatalogException;import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.meta.ColumnEntity;import org.apache.gravitino.meta.TableEntity;+import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.TableChange;import org.apache.gravitino.rel.expressions.literals.Literal;import org.apache.gravitino.rel.expressions.literals.Literals;@@ -273,6 +274,134 @@ public class TestCapabilityHelpers {Capability.DEFAULT.managedStorage(Capability.Scope.SEMANTIC_MODEL).supported());}+ @Test+ void testApplyCapabilitiesRejectsInitialDefaultEvenWhenWriteDefaultSupported() {+ // Capability.DEFAULT supports write-default (like MySQL), but catalogs do not apply+ // Iceberg-style initial defaults. Create must reject a set initialDefaultValue rather than+ // accept a value the backend would silently drop.+ Assertions.assertTrue(Capability.DEFAULT.columnDefaultValue().supported());++ Column withInitialOnly =+ Column.of(+ "country",+ Types.StringType.get(),+ null,+ true,+ false,+ Column.DEFAULT_VALUE_NOT_SET,+ Literals.stringLiteral("US"));++ IllegalArgumentException thrown =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ CapabilityHelpers.applyCapabilities(+ new Column[] {withInitialOnly}, Capability.DEFAULT));+ Assertions.assertTrue(+ thrown.getMessage().contains("initial default value is read-only"), thrown.getMessage());+ Assertions.assertTrue(thrown.getMessage().contains("catalog capability"), thrown.getMessage());+ Assertions.assertTrue(thrown.getMessage().contains("country"), thrown.getMessage());++ Column unsetInitial =+ Column.of(+ "country",+ Types.StringType.get(),+ null,+ true,+ false,+ Literals.stringLiteral("US"),+ Column.INITIAL_DEFAULT_VALUE_NOT_SET);+ Column[] applied =+ CapabilityHelpers.applyCapabilities(new Column[] {unsetInitial}, Capability.DEFAULT);+ Assertions.assertEquals(1, applied.length);+ Assertions.assertEquals(Column.INITIAL_DEFAULT_VALUE_NOT_SET, applied[0].initialDefaultValue());+ Assertions.assertEquals(Literals.stringLiteral("US"), applied[0].defaultValue());+ }++ @Test+ void testApplyCapabilitiesTreatsNullInitialDefaultAsUnset() {+ // Third-party Column implementations may return null instead of the unset sentinel.+ Column nullInitial = Mockito.mock(Column.class);+ Mockito.when(nullInitial.name()).thenReturn("country");+ Mockito.when(nullInitial.dataType()).thenReturn(Types.StringType.get());+ Mockito.when(nullInitial.comment()).thenReturn(null);+ Mockito.when(nullInitial.nullable()).thenReturn(true);+ Mockito.when(nullInitial.autoIncrement()).thenReturn(false);+ Mockito.when(nullInitial.defaultValue()).thenReturn(Column.DEFAULT_VALUE_NOT_SET);+ Mockito.when(nullInitial.initialDefaultValue()).thenReturn(null);++ Column[] applied =+ CapabilityHelpers.applyCapabilities(new Column[] {nullInitial}, Capability.DEFAULT);+ Assertions.assertEquals(1, applied.length);+ Assertions.assertEquals(Column.INITIAL_DEFAULT_VALUE_NOT_SET, applied[0].initialDefaultValue());+ }++ @Test+ void testLoadThenCreateRejectsColumnsCarryingInitialDefault() {+ // Iceberg v3 load exposes write-default and initial-default on columns. Feeding those columns+ // straight into create/add-column (copy-table / load-then-create) must fail: Gravitino create+ // still rejects initial defaults, and Iceberg create still rejects write defaults via+ // capability for catalogs that do not support them. Document the failure rather than silently+ // dropping.+ Column loadedLikeIcebergV3 =+ Column.of(+ "region",+ Types.StringType.get(),+ "loaded from Iceberg",+ true,+ false,+ Literals.stringLiteral("EU"),+ Literals.stringLiteral("US"));++ IllegalArgumentException thrown =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ CapabilityHelpers.applyCapabilities(+ new Column[] {loadedLikeIcebergV3}, Capability.DEFAULT));+ Assertions.assertTrue(+ thrown.getMessage().contains("initial default value is read-only"), thrown.getMessage());+ Assertions.assertTrue(thrown.getMessage().contains("catalog capability"), thrown.getMessage());+ Assertions.assertTrue(thrown.getMessage().contains("region"), thrown.getMessage());+ }++ @Test+ void testUpdateColumnDefaultValueDoesNotCheckInitialDefault() {+ // Alter update-default only validates write-default capability; it must not reject because a+ // previously loaded Iceberg v3 column carried initialDefaultValue (that field is not on the+ // TableChange).+ TableChange[] applied =+ CapabilityHelpers.applyCapabilities(+ Capability.DEFAULT,+ TableChange.updateColumnDefaultValue(+ new String[] {"region"}, Literals.stringLiteral("EU")));+ Assertions.assertEquals(1, applied.length);+ Assertions.assertInstanceOf(TableChange.UpdateColumnDefaultValue.class, applied[0]);+ Assertions.assertEquals(+ Literals.stringLiteral("EU"),+ ((TableChange.UpdateColumnDefaultValue) applied[0]).getNewDefaultValue());+ }++ @Test+ void testAddColumnDoesNotCarryInitialDefault() {+ // AddColumn has no initialDefaultValue; capability apply must succeed and leave initial unset.+ TableChange[] applied =+ CapabilityHelpers.applyCapabilities(+ Capability.DEFAULT,+ TableChange.addColumn(+ new String[] {"region"},+ Types.StringType.get(),+ "comment",+ TableChange.ColumnPosition.defaultPos(),+ true,+ false,+ Literals.stringLiteral("EU")));+ Assertions.assertEquals(1, applied.length);+ Assertions.assertInstanceOf(TableChange.AddColumn.class, applied[0]);+ Assertions.assertEquals(+ Literals.stringLiteral("EU"), ((TableChange.AddColumn) applied[0]).getDefaultValue());+ }+@Testvoid testNormalizeMetadataIdentifierKeepsExactStoredColumnName() throws IOException {CatalogManager catalogManager = foldingCatalogManager();diff --git a/docs/lakehouse-iceberg-catalog.md b/docs/lakehouse-iceberg-catalog.mdindex dfd5137633..5e7a610bbf 100644--- a/docs/lakehouse-iceberg-catalog.md+++ b/docs/lakehouse-iceberg-catalog.md@@ -374,7 +374,19 @@ children: List[str] = catalog.as_schemas().list_schemas(parent_schema="a:b")### Table Capabilities-- Doesn't support column default value.+- For format-version 3 tables, Iceberg column defaults in table metadata are+ reported when the table is loaded:++ | Iceberg field | Column field |+ |-------------------|------------------------|+ | `write-default` | `defaultValue` |+ | `initial-default` | `initialDefaultValue` |++ Iceberg `timestamptz` defaults are exposed as a UTC `LocalDateTime` with+ Gravitino type `timestamp_tz`. Clients should treat those `LocalDateTime`+ fields as UTC when recovering the instant.++- Setting column default values through the Gravitino API is not supported yet.### Table Partitionsdiff --git a/docs/open-api/tables.yaml b/docs/open-api/tables.yamlindex 9327387cd0..801edef5db 100644--- a/docs/open-api/tables.yaml+++ b/docs/open-api/tables.yaml@@ -366,7 +366,9 @@ components:ColumnDefaultValue:allOf:- $ref: "./expression.yaml#/components/schemas/FunctionArg"- description: The default value of the column+ description: >+ A column default expression. See Column.defaultValue and+ Column.initialDefaultValue for the two public meanings.Column:type: object@@ -389,7 +391,22 @@ components:nullable: truedefault: truedefaultValue:- $ref: "#/components/schemas/ColumnDefaultValue"+ allOf:+ - $ref: "#/components/schemas/ColumnDefaultValue"+ description: >+ Default used for new records that omit this column. Unset when the+ catalog does not support column defaults. For example, for Iceberg+ format-version 3 this maps to write-default.+ initialDefaultValue:+ allOf:+ - $ref: "#/components/schemas/ColumnDefaultValue"+ description: >+ Default used when reading stored records that lack this column, such+ as records written before the column was added. Unset when the catalog+ does not distinguish an initial default. Setting this through create+ or alter is not supported yet; it is exposed on load when the catalog+ provides it. For example, for Iceberg format-version 3 this maps to+ initial-default.autoIncrement:type: booleandescription: Whether the column is auto incrementdiff --git a/docs/tables-and-views.md b/docs/tables-and-views.mdindex 939de8ffea..49619cc2ea 100644--- a/docs/tables-and-views.md+++ b/docs/tables-and-views.md@@ -142,9 +142,24 @@ String unparsedValue = ((UnparsedType) type).unparsedType();#### Table Column Default Value-A column default can be a [literal](./expression.md#literal) or an-[expression](./expression.md). The underlying catalog applies it to new rows, and support depends-on the catalog provider.+A column may expose two defaults. Either value can be a [literal](./expression.md#literal) or an+[expression](./expression.md). Support depends on the catalog provider; when a catalog does not+support a given default, the corresponding field is unset (`DEFAULT_VALUE_NOT_SET` /+`INITIAL_DEFAULT_VALUE_NOT_SET`).++| Field | Meaning |+|------------------------|--------------------------------------------------------------------------------------------------|+| `defaultValue` | Applied to new records that omit the column |+| `initialDefaultValue` | Assumed when reading stored records that lack the column, such as rows written before it existed |++Setting `initialDefaultValue` through create or alter is not supported yet. Gravitino currently+exposes it on load when the underlying catalog provides it. Setting `defaultValue` remains+provider-specific as below.++For example, Iceberg format-version 3 maps `write-default` to `defaultValue` and+`initial-default` to `initialDefaultValue`. An Iceberg `timestamptz` default is exposed as a+UTC `LocalDateTime` with type `timestamp_tz` (with time zone): clients should treat the+`LocalDateTime` fields as UTC when recovering the instant.PostgreSQL, MySQL, Doris, StarRocks, OceanBase, and Hologres share function-default writevalidation: function names must be unquoted identifiers (optionally qualified), and arguments