This is an automated email from the ASF dual-hosted git repository.
yuqi1129 pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git
The following commit(s) were added to refs/heads/main by this push:
new e1c62b8959 [#14722] fix(mysql): Preserve zero-date column defaults
(#14727)
e1c62b8959 is described below
commit e1c62b8959f67a7f6cb309a68602ff1a6e64bd86
Author: jarred0214 <[email protected]>
AuthorDate: Fri Nov 13 16:39:50 2026 +0800
[#14722] fix(mysql): Preserve zero-date column defaults (#14727)
### What changes were proposed in this pull request?
Preserve MySQL zero-date DATE, TIMESTAMP and DATETIME column defaults as
quoted `UnparsedExpression` values, including fractional seconds. Add
regression tests for zero-date defaults and existing valid temporal
defaults.
### Why are the changes needed?
Loading table metadata currently fails when a legacy MySQL column has a
zero-date default that Java temporal literals cannot represent.
Fixes #14722
### Does this PR introduce _any_ user-facing change?
MySQL table metadata can be loaded when columns have zero-date defaults.
No API or configuration changes.
### How was this patch tested?
- Passed: `./gradlew :catalogs:catalog-jdbc-mysql:test
:catalogs:catalog-jdbc-mysql:spotlessCheck -PskipITs` (JDK 17).
- Ran `./gradlew spotlessApply`; the repository-wide task was blocked by
an existing x86_64/ARM mismatch in the MCP server's Python Black
environment. The changed Java files were formatted and their module's
format checks passed.
- MySQL integration tests were not run because Docker is unavailable
locally.
---------
Co-authored-by: Qi Yu <[email protected]>
---
.../MysqlColumnDefaultValueConverter.java | 37 ++++++++++---
.../TestMysqlColumnDefaultValueConverter.java | 64 ++++++++++++++++++++++
.../mysql/integration/test/CatalogMysqlIT.java | 57 ++++++++++++++++++-
.../TestMysqlTableOperationsSqlGeneration.java | 35 ++++++++++--
4 files changed, 179 insertions(+), 14 deletions(-)
diff --git
a/catalogs/catalog-jdbc-mysql/src/main/java/org/apache/gravitino/catalog/mysql/converter/MysqlColumnDefaultValueConverter.java
b/catalogs/catalog-jdbc-mysql/src/main/java/org/apache/gravitino/catalog/mysql/converter/MysqlColumnDefaultValueConverter.java
index ecdf91aa81..30ac269fdf 100644
---
a/catalogs/catalog-jdbc-mysql/src/main/java/org/apache/gravitino/catalog/mysql/converter/MysqlColumnDefaultValueConverter.java
+++
b/catalogs/catalog-jdbc-mysql/src/main/java/org/apache/gravitino/catalog/mysql/converter/MysqlColumnDefaultValueConverter.java
@@ -25,6 +25,7 @@ import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeParseException;
+import java.util.regex.Pattern;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import
org.apache.gravitino.catalog.jdbc.converter.JdbcColumnDefaultValueConverter;
@@ -38,11 +39,18 @@ import org.apache.gravitino.rel.types.Types;
public class MysqlColumnDefaultValueConverter extends
JdbcColumnDefaultValueConverter {
+ // Only quoted temporal literals may be rendered from an unparsed default.
+ private static final Pattern QUOTED_TEMPORAL_LITERAL =
+ Pattern.compile(
+ "'(?:[0-9]{4}-[0-9]{2}-[0-9]{2}(?:
[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\\.[0-9]{1,6})?)?"
+ + "|-?[0-9]{2,3}:[0-9]{2}:[0-9]{2}(?:\\.[0-9]{1,6})?)'");
+
/**
- * Renders Boolean literal defaults as numeric 1 or 0. Gravitino maps
BOOLEAN to MySQL BIT, which
- * rejects the quoted 'true' and 'false' strings. The check uses the literal
type, so a Boolean
- * default that is loaded from BIT(1) and then re-rendered by MODIFY COLUMN
keeps working after a
- * type change to a numeric column. Other defaults use the shared JDBC
rendering.
+ * Renders preserved temporal defaults as quoted SQL literals and Boolean
defaults as numeric 1 or
+ * 0. Gravitino maps BOOLEAN to MySQL BIT, which rejects the quoted 'true'
and 'false' strings.
+ * The check uses the literal type, so a Boolean default that is loaded from
BIT(1) and then
+ * re-rendered by MODIFY COLUMN keeps working after a type change to a
numeric column. Other
+ * defaults use the shared JDBC rendering.
*
* @param defaultValue the Gravitino default expression
* @return the SQL expression, or null when no default is set
@@ -51,6 +59,12 @@ public class MysqlColumnDefaultValueConverter extends
JdbcColumnDefaultValueConv
@Override
@Nullable
public String fromGravitino(Expression defaultValue) {
+ if (defaultValue instanceof UnparsedExpression) {
+ String sql = ((UnparsedExpression) defaultValue).unparsedExpression();
+ if (QUOTED_TEMPORAL_LITERAL.matcher(sql).matches()) {
+ return sql;
+ }
+ }
if (defaultValue instanceof Literal
&& ((Literal<?>) defaultValue).dataType() instanceof
Types.BooleanType) {
String value = String.valueOf(((Literal<?>)
defaultValue).value()).trim();
@@ -126,9 +140,17 @@ public class MysqlColumnDefaultValueConverter extends
JdbcColumnDefaultValueConv
return Literals.decimalLiteral(
Decimal.of(columnDefaultValue, type.getColumnSize(),
type.getScale()));
case JdbcTypeConverter.DATE:
- return Literals.dateLiteral(LocalDate.parse(columnDefaultValue,
DATE_FORMATTER));
+ try {
+ return Literals.dateLiteral(LocalDate.parse(columnDefaultValue,
DATE_FORMATTER));
+ } catch (DateTimeParseException e) {
+ return UnparsedExpression.of(quoteStringLiteral(columnDefaultValue));
+ }
case JdbcTypeConverter.TIME:
- return Literals.timeLiteral(LocalTime.parse(columnDefaultValue,
TIME_FORMATTER));
+ try {
+ return Literals.timeLiteral(LocalTime.parse(columnDefaultValue,
TIME_FORMATTER));
+ } catch (DateTimeParseException e) {
+ return UnparsedExpression.of(quoteStringLiteral(columnDefaultValue));
+ }
case JdbcTypeConverter.TIMESTAMP:
case MysqlTypeConverter.DATETIME:
if (StringUtils.startsWithIgnoreCase(columnDefaultValue,
CURRENT_TIMESTAMP)) {
@@ -138,8 +160,7 @@ public class MysqlColumnDefaultValueConverter extends
JdbcColumnDefaultValueConv
return Literals.timestampLiteral(
LocalDateTime.parse(columnDefaultValue, DATE_TIME_FORMATTER));
} catch (DateTimeParseException e) {
- throw new IllegalArgumentException(
- String.format("Unable to parse datetime value: %s",
columnDefaultValue));
+ return UnparsedExpression.of(quoteStringLiteral(columnDefaultValue));
}
case JdbcTypeConverter.VARCHAR:
return Literals.of(columnDefaultValue,
Types.VarCharType.of(type.getColumnSize()));
diff --git
a/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/converter/TestMysqlColumnDefaultValueConverter.java
b/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/converter/TestMysqlColumnDefaultValueConverter.java
index c52d0d28a1..d67d07173d 100644
---
a/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/converter/TestMysqlColumnDefaultValueConverter.java
+++
b/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/converter/TestMysqlColumnDefaultValueConverter.java
@@ -20,17 +20,81 @@ package org.apache.gravitino.catalog.mysql.converter;
import org.apache.gravitino.catalog.jdbc.converter.JdbcTypeConverter;
import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.expressions.Expression;
import org.apache.gravitino.rel.expressions.UnparsedExpression;
import org.apache.gravitino.rel.expressions.literals.Literals;
import org.apache.gravitino.rel.types.Types;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
class TestMysqlColumnDefaultValueConverter {
private final MysqlColumnDefaultValueConverter converter = new
MysqlColumnDefaultValueConverter();
+ @ParameterizedTest
+ @CsvSource({
+ "DATE, 0000-00-00",
+ "DATE, 0000-01-01",
+ "DATETIME, 0000-01-01 00:00:00",
+ "TIME, 838:59:59",
+ "TIME, -01:00:00",
+ "TIME, -838:59:59.123456",
+ "DATE, 2024-00-00",
+ "DATE, 2024-00-31",
+ "DATE, 2024-12-00",
+ "TIMESTAMP, 0000-00-00 00:00:00",
+ "DATETIME, 0000-00-00 00:00:00",
+ "DATETIME, 0000-00-00 12:34:56",
+ "DATETIME, 2024-00-00 12:34:56",
+ "DATETIME, 2024-00-31 23:59:59.123456",
+ "DATETIME, 2024-12-00 12:34:56.123",
+ "TIMESTAMP, 0000-00-00 00:00:00.0",
+ "DATETIME, 0000-00-00 00:00:00.000",
+ "TIMESTAMP, 0000-00-00 00:00:00.000000",
+ "DATETIME, 0000-00-00 00:00:00.123456"
+ })
+ void testUnrepresentableTemporalDefaultsArePreserved(String typeName, String
value) {
+ JdbcTypeConverter.JdbcTypeBean type = new
JdbcTypeConverter.JdbcTypeBean(typeName);
+ Expression result = converter.toGravitino(type, value, false, false);
+ String sql = "'" + value + "'";
+ Assertions.assertEquals(UnparsedExpression.of(sql), result);
+ Assertions.assertEquals(sql, converter.fromGravitino(result));
+ Assertions.assertEquals(result, converter.toGravitino(type, value, false,
true));
+ }
+
+ @Test
+ void testTemporalFallbackEscapesQuotesAndRejectsRawSqlOnWrite() {
+ JdbcTypeConverter.JdbcTypeBean type = new
JdbcTypeConverter.JdbcTypeBean("DATE");
+ Expression result = converter.toGravitino(type, "invalid'date", false,
false);
+ Assertions.assertEquals(UnparsedExpression.of("'invalid''date'"), result);
+ Assertions.assertThrows(IllegalArgumentException.class, () ->
converter.fromGravitino(result));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> converter.fromGravitino(UnparsedExpression.of("'0000-00-00' OR
1=1")));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"TIMESTAMP", "DATETIME"})
+ void testValidTemporalDefaults(String typeName) {
+ JdbcTypeConverter.JdbcTypeBean type = new
JdbcTypeConverter.JdbcTypeBean(typeName);
+ Assertions.assertEquals(
+ Literals.timestampLiteral("2024-01-02T03:04:05.123456"),
+ converter.toGravitino(type, "2024-01-02 03:04:05.123456", false,
false));
+ Assertions.assertEquals(
+ Column.DEFAULT_VALUE_OF_CURRENT_TIMESTAMP,
+ converter.toGravitino(type, "CURRENT_TIMESTAMP(6)", false, false));
+ }
+
+ @Test
+ void testValidDateDefault() {
+ JdbcTypeConverter.JdbcTypeBean type = new
JdbcTypeConverter.JdbcTypeBean("DATE");
+ Assertions.assertEquals(
+ Literals.dateLiteral("2024-01-02"),
+ converter.toGravitino(type, "2024-01-02", false, false));
+ }
+
@ParameterizedTest
@ValueSource(strings = {"true", "TRUE", "1"})
void testTrueDefaultsAreUnquoted(String value) {
diff --git
a/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/integration/test/CatalogMysqlIT.java
b/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/integration/test/CatalogMysqlIT.java
index 7f3d993b2c..fdf69b5cc6 100644
---
a/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/integration/test/CatalogMysqlIT.java
+++
b/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/integration/test/CatalogMysqlIT.java
@@ -87,6 +87,8 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.api.condition.EnabledIf;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
@Tag("gravitino-docker-test")
@TestInstance(Lifecycle.PER_CLASS)
@@ -182,6 +184,10 @@ public class CatalogMysqlIT extends BaseIT {
}
private Catalog createCatalog(String catalogName) throws SQLException {
+ return createCatalog(catalogName, "");
+ }
+
+ private Catalog createCatalog(String catalogName, String jdbcOptions) throws
SQLException {
Map<String, String> catalogProperties = Maps.newHashMap();
catalogProperties.put(
@@ -190,7 +196,8 @@ public class CatalogMysqlIT extends BaseIT {
MYSQL_CONTAINER.getJdbcUrl(TEST_DB_NAME),
0,
MYSQL_CONTAINER.getJdbcUrl(TEST_DB_NAME).lastIndexOf("/"))
- + "?useSSL=false&allowPublicKeyRetrieval=true");
+ + "?useSSL=false&allowPublicKeyRetrieval=true"
+ + jdbcOptions);
catalogProperties.put(
JdbcConfig.JDBC_DRIVER.getKey(),
MYSQL_CONTAINER.getDriverClassName(TEST_DB_NAME));
catalogProperties.put(JdbcConfig.USERNAME.getKey(),
MYSQL_CONTAINER.getUsername());
@@ -597,6 +604,54 @@ public class CatalogMysqlIT extends BaseIT {
assertBooleanDefaultInsert(ident, false, true);
}
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void testZeroDateDefaultsSurviveLoadAndAlter(boolean useInformationSchema)
throws SQLException {
+ String legacyCatalogName =
GravitinoITUtils.genRandomName("mysql_zero_date_catalog");
+ Catalog legacyCatalog =
+ createCatalog(
+ legacyCatalogName,
+ "&useInformationSchema=" + useInformationSchema +
"&sessionVariables=sql_mode=%27%27");
+ TableCatalog tables = legacyCatalog.asTableCatalog();
+ NameIdentifier ident = NameIdentifier.of(schemaName, tableName);
+ try {
+ try (Connection connection =
+ DriverManager.getConnection(
+ MYSQL_CONTAINER.getJdbcUrl(TEST_DB_NAME),
+ MYSQL_CONTAINER.getUsername(),
+ MYSQL_CONTAINER.getPassword());
+ Statement statement = connection.createStatement()) {
+ statement.execute("SET SESSION sql_mode = ''");
+ statement.execute(
+ "CREATE TABLE "
+ + schemaName
+ + "."
+ + tableName
+ + " (d DATE DEFAULT '0000-00-00', "
+ + "dt DATETIME(6) DEFAULT '0000-00-00 12:34:56.123456', "
+ + "ts TIMESTAMP NULL DEFAULT '0000-00-00 00:00:00')");
+ }
+
+ Table loaded = tables.loadTable(ident);
+ Assertions.assertEquals(
+ UnparsedExpression.of("'0000-00-00'"),
loaded.columns()[0].defaultValue());
+ Assertions.assertEquals(
+ UnparsedExpression.of("'0000-00-00 12:34:56.123456'"),
+ loaded.columns()[1].defaultValue());
+ Assertions.assertEquals(
+ UnparsedExpression.of("'0000-00-00 00:00:00'"),
loaded.columns()[2].defaultValue());
+
+ tables.alterTable(ident, TableChange.updateColumnComment(new String[]
{"d"}, "legacy"));
+ Table altered = tables.loadTable(ident);
+ Assertions.assertEquals("legacy", altered.columns()[0].comment());
+ Assertions.assertEquals(
+ loaded.columns()[0].defaultValue(),
altered.columns()[0].defaultValue());
+ } finally {
+ metalake.disableCatalog(legacyCatalogName);
+ metalake.dropCatalog(legacyCatalogName, true);
+ }
+ }
+
@Test
void testColumnDefaultValueWithDatetimePrecision() {
// MySQL rejects `DATETIME(6) DEFAULT CURRENT_TIMESTAMP`: once a column
declares a fractional
diff --git
a/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/operation/TestMysqlTableOperationsSqlGeneration.java
b/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/operation/TestMysqlTableOperationsSqlGeneration.java
index f0328ad591..dd7c3dd6a5 100644
---
a/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/operation/TestMysqlTableOperationsSqlGeneration.java
+++
b/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/operation/TestMysqlTableOperationsSqlGeneration.java
@@ -23,9 +23,10 @@ import java.util.Map;
import java.util.stream.Stream;
import org.apache.gravitino.catalog.jdbc.JdbcColumn;
import org.apache.gravitino.catalog.jdbc.JdbcTable;
-import
org.apache.gravitino.catalog.jdbc.converter.JdbcColumnDefaultValueConverter;
import org.apache.gravitino.catalog.jdbc.converter.JdbcExceptionConverter;
+import org.apache.gravitino.catalog.jdbc.converter.JdbcTypeConverter;
import org.apache.gravitino.catalog.jdbc.utils.ConnectionCountingDataSource;
+import
org.apache.gravitino.catalog.mysql.converter.MysqlColumnDefaultValueConverter;
import org.apache.gravitino.catalog.mysql.converter.MysqlTypeConverter;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.TableChange;
@@ -44,10 +45,12 @@ import org.junit.jupiter.params.provider.MethodSource;
public class TestMysqlTableOperationsSqlGeneration {
private static class TestableMysqlTableOperations extends
MysqlTableOperations {
+ private JdbcColumn[] columns = new JdbcColumn[0];
+
public TestableMysqlTableOperations() {
super.exceptionMapper = new JdbcExceptionConverter();
super.typeConverter = new MysqlTypeConverter();
- super.columnDefaultValueConverter = new
JdbcColumnDefaultValueConverter();
+ super.columnDefaultValueConverter = new
MysqlColumnDefaultValueConverter();
}
private TestableMysqlTableOperations(ConnectionCountingDataSource
connections) {
@@ -77,10 +80,32 @@ public class TestMysqlTableOperationsSqlGeneration {
@Override
protected JdbcTable getOrCreateTable(
String databaseName, String tableName, JdbcTable lazyLoadCreateTable) {
- return JdbcTable.builder().withName(tableName).build();
+ return
JdbcTable.builder().withName(tableName).withColumns(columns).build();
}
}
+ @Test
+ void testAlterColumnCommentPreservesLoadedZeroDateDefault() {
+ TestableMysqlTableOperations ops = new TestableMysqlTableOperations();
+ ops.columns =
+ new JdbcColumn[] {
+ JdbcColumn.builder()
+ .withName("legacy_date")
+ .withType(Types.DateType.get())
+ .withDefaultValue(
+ new MysqlColumnDefaultValueConverter()
+ .toGravitino(
+ new JdbcTypeConverter.JdbcTypeBean("DATE"),
"0000-00-00", false, true))
+ .build()
+ };
+
+ String sql =
+ ops.alterTableSql(
+ "test_table",
+ TableChange.updateColumnComment(new String[] {"legacy_date"},
"legacy default"));
+ Assertions.assertTrue(sql.contains("DEFAULT '0000-00-00' COMMENT 'legacy
default'"), sql);
+ }
+
@ParameterizedTest
@MethodSource("invalidTableOptions")
void testInvalidOptionsAreRejectedBeforeCreateAndAlterSql(String key, String
value) {
@@ -161,7 +186,7 @@ public class TestMysqlTableOperationsSqlGeneration {
.build();
String sql = ops.createTableSql(tableName, new JdbcColumn[] {col1});
- JdbcColumnDefaultValueConverter converter = new
JdbcColumnDefaultValueConverter();
+ MysqlColumnDefaultValueConverter converter = new
MysqlColumnDefaultValueConverter();
Assertions.assertTrue(
sql.contains("DEFAULT " +
converter.fromGravitino(col1.defaultValue())),
"Should contain DEFAULT '' but was: " + sql);
@@ -180,7 +205,7 @@ public class TestMysqlTableOperationsSqlGeneration {
.build();
String sql = ops.createTableSql(tableName, new JdbcColumn[] {col1});
- JdbcColumnDefaultValueConverter converter = new
JdbcColumnDefaultValueConverter();
+ MysqlColumnDefaultValueConverter converter = new
MysqlColumnDefaultValueConverter();
Assertions.assertTrue(
sql.contains("DEFAULT " +
converter.fromGravitino(col1.defaultValue())),
"Should contain DEFAULT value but was: " + sql);