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

diqiu50 pushed a commit to branch branch-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git


The following commit(s) were added to refs/heads/branch-1.3 by this push:
     new f26cd95f29 [Cherry-pick to branch-1.3] [#14858] 
fix(catalog-jdbc-clickhouse): Fix column default value escaping and validation 
(#14859) (#14912)
f26cd95f29 is described below

commit f26cd95f29b6a6b5bcd684ab5ae8c3e0c9757d5a
Author: github-actions[bot] 
<41898282+github-actions[bot]@users.noreply.github.com>
AuthorDate: Thu Nov 12 10:00:55 2026 +0800

    [Cherry-pick to branch-1.3] [#14858] fix(catalog-jdbc-clickhouse): Fix 
column default value escaping and validation (#14859) (#14912)
    
    **Cherry-pick Information:**
    - Original commit: 707a0ca427894ec49dec3716064d911ec81b06f8
    - Target branch: `branch-1.3`
    - Status: ✅ Conflicts resolved
    
    ---------
    
    Co-authored-by: Yuhui <[email protected]>
    Co-authored-by: diqiu50 <[email protected]>
---
 .../ClickHouseColumnDefaultValueConverter.java     | 203 ++++++++++++++++++-
 .../converter/ClickHouseTypeConverter.java         |   2 +-
 .../operations/ClickHouseTableOperations.java      |  22 ++
 .../TestClickHouseColumnDefaultValueConverter.java | 199 ++++++++++++++++++
 .../converter/TestClickHouseTypeConverter.java     |   2 +-
 .../operations/TestClickHouseTableOperations.java  | 223 +++++++++++++++++++++
 .../converter/JdbcColumnDefaultValueConverter.java |  10 +-
 docs/jdbc-clickhouse-catalog.md                    |   9 +
 8 files changed, 661 insertions(+), 9 deletions(-)

diff --git 
a/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/converter/ClickHouseColumnDefaultValueConverter.java
 
b/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/converter/ClickHouseColumnDefaultValueConverter.java
index a9458b1289..8889dd3139 100644
--- 
a/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/converter/ClickHouseColumnDefaultValueConverter.java
+++ 
b/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/converter/ClickHouseColumnDefaultValueConverter.java
@@ -22,8 +22,12 @@ import static 
org.apache.gravitino.rel.Column.DEFAULT_VALUE_NOT_SET;
 import static 
org.apache.gravitino.rel.Column.DEFAULT_VALUE_OF_CURRENT_TIMESTAMP;
 
 import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.math.BigInteger;
 import java.time.LocalDate;
 import java.time.LocalDateTime;
+import java.time.format.DateTimeParseException;
+import java.util.regex.Pattern;
 import org.apache.commons.lang3.StringUtils;
 import 
org.apache.gravitino.catalog.clickhouse.operations.ClickHouseClusterUtils;
 import 
org.apache.gravitino.catalog.jdbc.converter.JdbcColumnDefaultValueConverter;
@@ -42,6 +46,47 @@ public class ClickHouseColumnDefaultValueConverter extends 
JdbcColumnDefaultValu
   protected static final String NOW = "now";
   protected static final Expression DEFAULT_VALUE_OF_NOW = 
FunctionExpression.of(NOW);
 
+  // ClickHouse Date stores days since 1970-01-01 as UInt16, so its range is 
fixed.
+  private static final LocalDate MIN_DATE = LocalDate.of(1970, 1, 1);
+  private static final LocalDate MAX_DATE = LocalDate.of(2149, 6, 6);
+  private static final Pattern NON_FINITE_PATTERN = 
Pattern.compile("(?i)-?(nan|inf|infinity)");
+  private static final Pattern UUID_PATTERN =
+      Pattern.compile(
+          
"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}");
+
+  /**
+   * Checks that a literal default value fits the column type. ClickHouse does 
not validate DEFAULT
+   * literals when a table is created or altered, and silently wraps or clamps 
out-of-range values
+   * on insert. Only the following column types are checked:
+   *
+   * <ul>
+   *   <li>Integer types (signed and unsigned): the value, truncated toward 
zero as ClickHouse does,
+   *       must be within the type range.
+   *   <li>Decimal: the value, with excess fractional digits discarded as 
ClickHouse does, must fit
+   *       the precision.
+   *   <li>Date: the value must be a {@code yyyy-MM-dd} date between 
1970-01-01 and 2149-06-06.
+   *   <li>UUID: the value must be a valid UUID string.
+   *   <li>Float and Double: the value must be a number, NaN or infinity. The 
range is not checked.
+   * </ul>
+   *
+   * <p>Other column types such as DateTime, and non-literal or NULL defaults, 
are not checked.
+   *
+   * @param columnType the Gravitino type of the column
+   * @param defaultValue the default value of the column
+   * @throws IllegalArgumentException if the literal value is not valid for 
the column type
+   */
+  public void checkDefaultValue(Type columnType, Expression defaultValue) {
+    if (!(defaultValue instanceof Literal<?> literal) || literal.value() == 
null) {
+      return;
+    }
+    String value = literal.value().toString();
+    // Validate the same value that fromGravitino writes, which drops 
caller-supplied quotes.
+    if (value.length() >= 2 && value.startsWith("'") && value.endsWith("'")) {
+      value = ClickHouseClusterUtils.unescapeSingleQuotes(value.substring(1, 
value.length() - 1));
+    }
+    checkLiteralFitsType(columnType, value);
+  }
+
   public String fromGravitino(Expression defaultValue) {
     if (DEFAULT_VALUE_NOT_SET.equals(defaultValue)) {
       return null;
@@ -56,7 +101,14 @@ public class ClickHouseColumnDefaultValueConverter extends 
JdbcColumnDefaultValu
       if (defaultValue.equals(Literals.NULL)) {
         return NULL;
       } else if (type instanceof Type.NumericType) {
-        return literal.value().toString();
+        // Numeric values are written without quotes, so anything other than a 
number must be
+        // rejected. ClickHouse also accepts NaN and infinity literals for 
floating-point columns.
+        String value = literal.value().toString().trim();
+        // Drop caller-supplied quotes the same way checkDefaultValue does, 
then write the number.
+        if (value.length() >= 2 && value.startsWith("'") && 
value.endsWith("'")) {
+          value = value.substring(1, value.length() - 1).trim();
+        }
+        return NON_FINITE_PATTERN.matcher(value).matches() ? value : 
validateNumericLiteral(value);
       } else {
         Object value = literal.value();
         Preconditions.checkArgument(
@@ -72,7 +124,10 @@ public class ClickHouseColumnDefaultValueConverter extends 
JdbcColumnDefaultValu
           value = ClickHouseClusterUtils.unescapeSingleQuotes(str.substring(1, 
str.length() - 1));
         }
 
-        return String.format("'%s'", 
ClickHouseClusterUtils.escapeSingleQuotes(value.toString()));
+        // ClickHouse treats backslash as an escape character in string 
literals, so escape it
+        // first to keep the value unchanged on round-trip.
+        String escaped = value.toString().replace("\\", "\\\\");
+        return String.format("'%s'", 
ClickHouseClusterUtils.escapeSingleQuotes(escaped));
       }
     }
 
@@ -117,10 +172,15 @@ public class ClickHouseColumnDefaultValueConverter 
extends JdbcColumnDefaultValu
     }
 
     // need exclude begin and end "'"
-    String reallyValue =
-        columnDefaultValue.startsWith("'")
+    boolean quoted =
+        columnDefaultValue.length() >= 2
+            && columnDefaultValue.startsWith("'")
+            && columnDefaultValue.endsWith("'");
+    String rawValue =
+        quoted
             ? columnDefaultValue.substring(1, columnDefaultValue.length() - 1)
             : columnDefaultValue;
+    String reallyValue = quoted ? unescapeStringLiteral(rawValue) : rawValue;
 
     try {
       switch (realType) {
@@ -164,10 +224,141 @@ public class ClickHouseColumnDefaultValueConverter 
extends JdbcColumnDefaultValu
         case ClickHouseTypeConverter.FIXEDSTRING:
           return Literals.of(reallyValue, 
Types.FixedCharType.of(type.getColumnSize()));
         default:
-          return UnparsedExpression.of(reallyValue);
+          return UnparsedExpression.of(rawValue);
       }
     } catch (Exception ex) {
-      return UnparsedExpression.of(reallyValue);
+      return UnparsedExpression.of(rawValue);
+    }
+  }
+
+  private static void checkLiteralFitsType(Type columnType, String value) {
+    try {
+      if (columnType instanceof Types.ByteType byteType) {
+        checkIntegralRange(value, 8, byteType.signed(), columnType);
+      } else if (columnType instanceof Types.ShortType shortType) {
+        checkIntegralRange(value, 16, shortType.signed(), columnType);
+      } else if (columnType instanceof Types.IntegerType integerType) {
+        checkIntegralRange(value, 32, integerType.signed(), columnType);
+      } else if (columnType instanceof Types.LongType longType) {
+        checkIntegralRange(value, 64, longType.signed(), columnType);
+      } else if (columnType instanceof Types.FloatType || columnType 
instanceof Types.DoubleType) {
+        if (!NON_FINITE_PATTERN.matcher(value).matches()) {
+          new BigDecimal(value);
+        }
+      } else if (columnType instanceof Types.DecimalType decimalType) {
+        // ClickHouse discards excess fractional digits, so the value fits as 
long as its integer
+        // part has at most (precision - scale) digits.
+        BigDecimal limit =
+            BigDecimal.ONE.scaleByPowerOfTen(decimalType.precision() - 
decimalType.scale());
+        Preconditions.checkArgument(
+            new BigDecimal(value).abs().compareTo(limit) < 0,
+            "Default value %s is out of range for column type %s",
+            value,
+            columnType.simpleString());
+      } else if (columnType instanceof Types.DateType) {
+        LocalDate date = LocalDate.parse(value);
+        Preconditions.checkArgument(
+            !date.isBefore(MIN_DATE) && !date.isAfter(MAX_DATE),
+            "Default value %s is out of range for column type %s, ClickHouse 
Date supports [%s, %s]",
+            value,
+            columnType.simpleString(),
+            MIN_DATE,
+            MAX_DATE);
+      } else if (columnType instanceof Types.UUIDType) {
+        Preconditions.checkArgument(
+            UUID_PATTERN.matcher(value).matches(), "Default value %s is not a 
valid UUID", value);
+      }
+    } catch (NumberFormatException | DateTimeParseException e) {
+      throw new IllegalArgumentException(
+          String.format(
+              "Default value %s is not a valid value of column type %s",
+              value, columnType.simpleString()),
+          e);
+    }
+  }
+
+  private static void checkIntegralRange(String value, int bits, boolean 
signed, Type columnType) {
+    BigInteger min = signed ? BigInteger.ONE.shiftLeft(bits - 1).negate() : 
BigInteger.ZERO;
+    BigInteger max =
+        signed
+            ? BigInteger.ONE.shiftLeft(bits - 1).subtract(BigInteger.ONE)
+            : BigInteger.ONE.shiftLeft(bits).subtract(BigInteger.ONE);
+    // ClickHouse converts a fractional or exponent literal to an integer by 
truncating toward
+    // zero (1.9 becomes 1, 1e3 becomes 1000), so the value fits when min - 1 
< value < max + 1.
+    BigDecimal number = new BigDecimal(value);
+    Preconditions.checkArgument(
+        number.compareTo(new BigDecimal(min.subtract(BigInteger.ONE))) > 0
+            && number.compareTo(new BigDecimal(max.add(BigInteger.ONE))) < 0,
+        "Default value %s is out of range for column type %s, valid range is 
[%s, %s]",
+        value,
+        columnType.simpleString(),
+        min,
+        max);
+  }
+
+  /**
+   * Unescapes the content of a ClickHouse single-quoted string literal. 
ClickHouse reports string
+   * defaults with backslash escapes (for example {@code 'a\'b'}), and also 
accepts a doubled single
+   * quote.
+   */
+  private static String unescapeStringLiteral(String text) {
+    if (text.indexOf('\\') < 0 && !text.contains("''")) {
+      return text;
     }
+    StringBuilder result = new StringBuilder(text.length());
+    for (int i = 0; i < text.length(); i++) {
+      char c = text.charAt(i);
+      if (c == '\\' && i + 1 < text.length()) {
+        char next = text.charAt(++i);
+        switch (next) {
+          case 'n':
+            result.append('\n');
+            break;
+          case 't':
+            result.append('\t');
+            break;
+          case 'r':
+            result.append('\r');
+            break;
+          case '0':
+            result.append('\0');
+            break;
+          case 'b':
+            result.append('\b');
+            break;
+          case 'f':
+            result.append('\f');
+            break;
+          case 'a':
+            result.append('\u0007');
+            break;
+          case 'v':
+            result.append('\u000B');
+            break;
+          case 'x':
+            if (i + 2 < text.length()
+                && isHexDigit(text.charAt(i + 1))
+                && isHexDigit(text.charAt(i + 2))) {
+              result.append((char) Integer.parseInt(text.substring(i + 1, i + 
3), 16));
+              i += 2;
+            } else {
+              result.append(next);
+            }
+            break;
+          default:
+            result.append(next);
+        }
+      } else if (c == '\'' && i + 1 < text.length() && text.charAt(i + 1) == 
'\'') {
+        result.append('\'');
+        i++;
+      } else {
+        result.append(c);
+      }
+    }
+    return result.toString();
+  }
+
+  private static boolean isHexDigit(char c) {
+    return Character.digit(c, 16) >= 0;
   }
 }
diff --git 
a/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/converter/ClickHouseTypeConverter.java
 
b/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/converter/ClickHouseTypeConverter.java
index 2672b2b8f4..c2e977426e 100644
--- 
a/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/converter/ClickHouseTypeConverter.java
+++ 
b/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/converter/ClickHouseTypeConverter.java
@@ -212,7 +212,7 @@ public class ClickHouseTypeConverter extends 
JdbcTypeConverter {
     } else if (type instanceof Types.VarCharType) {
       throw new IllegalArgumentException(
           "ClickHouse does not support varchar(n) length limits; use string 
for unlimited text "
-              + "or fixedchar(n) for a fixed-length value");
+              + "or char(n) for a fixed-length value");
     } else if (type instanceof Types.FixedCharType fixedCharType) {
       return FIXEDSTRING + "(" + fixedCharType.length() + ")";
     } else if (type instanceof Types.BooleanType) {
diff --git 
a/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseTableOperations.java
 
b/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseTableOperations.java
index 398d11316b..b1fe760756 100644
--- 
a/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseTableOperations.java
+++ 
b/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseTableOperations.java
@@ -66,6 +66,7 @@ import 
org.apache.gravitino.catalog.clickhouse.ClickHouseConstants.DistributedTa
 import 
org.apache.gravitino.catalog.clickhouse.ClickHouseConstants.TableConstants;
 import 
org.apache.gravitino.catalog.clickhouse.ClickHouseTablePropertiesMetadata;
 import 
org.apache.gravitino.catalog.clickhouse.ClickHouseTablePropertiesMetadata.ENGINE;
+import 
org.apache.gravitino.catalog.clickhouse.converter.ClickHouseColumnDefaultValueConverter;
 import org.apache.gravitino.catalog.jdbc.JdbcColumn;
 import org.apache.gravitino.catalog.jdbc.JdbcTable;
 import org.apache.gravitino.catalog.jdbc.bean.JdbcIndexBean;
@@ -625,6 +626,7 @@ public class ClickHouseTableOperations extends 
JdbcTableOperations {
       JdbcColumn column = columns[i];
       sqlBuilder.append("  %s".formatted(quoteIdentifier(column.name())));
 
+      checkDefaultValue(column.dataType(), column.defaultValue());
       appendColumnDefinition(column, sqlBuilder);
       // Add a comma for the next column, unless it's the last one
       if (i < columns.length - 1) {
@@ -1386,6 +1388,7 @@ public class ClickHouseTableOperations extends 
JdbcTableOperations {
 
     // Append default value if available
     if (!Column.DEFAULT_VALUE_NOT_SET.equals(addColumn.getDefaultValue())) {
+      checkDefaultValue(addColumn.getDataType(), addColumn.getDefaultValue());
       columnDefinition.append(
           "DEFAULT %s "
               
.formatted(columnDefaultValueConverter.fromGravitino(addColumn.getDefaultValue())));
@@ -1477,6 +1480,7 @@ public class ClickHouseTableOperations extends 
JdbcTableOperations {
     JdbcColumn column = getJdbcColumnFromTable(jdbcTable, col);
     StringBuilder sqlBuilder = new StringBuilder(MODIFY_COLUMN + 
quoteIdentifier(col));
     JdbcColumn newColumn = withPendingDefaultValueAndNullability(column, 
changes);
+    checkDefaultValue(newColumn.dataType(), 
updateColumnDefaultValue.getNewDefaultValue());
 
     return appendColumnDefinition(newColumn, sqlBuilder).toString();
   }
@@ -1501,6 +1505,15 @@ public class ClickHouseTableOperations extends 
JdbcTableOperations {
             .withNullable(column.nullable())
             .withAutoIncrement(column.autoIncrement())
             .build();
+    // The existing default is kept when the type changes, so it must also fit 
the new type.
+    try {
+      checkDefaultValue(newColumn.dataType(), newColumn.defaultValue());
+    } catch (IllegalArgumentException e) {
+      throw new IllegalArgumentException(
+          "The existing default value of column %s is not compatible with the 
new type %s: %s"
+              .formatted(col, newColumn.dataType().simpleString(), 
e.getMessage()),
+          e);
+    }
     return appendColumnDefinition(newColumn, sqlBuilder).toString();
   }
 
@@ -2105,6 +2118,15 @@ public class ClickHouseTableOperations extends 
JdbcTableOperations {
     return -1;
   }
 
+  private void checkDefaultValue(Type columnType, Expression defaultValue) {
+    Preconditions.checkState(
+        columnDefaultValueConverter instanceof 
ClickHouseColumnDefaultValueConverter,
+        "ClickHouse table operations require 
ClickHouseColumnDefaultValueConverter, but got %s",
+        columnDefaultValueConverter.getClass().getName());
+    ((ClickHouseColumnDefaultValueConverter) columnDefaultValueConverter)
+        .checkDefaultValue(columnType, defaultValue);
+  }
+
   private StringBuilder appendColumnDefinition(JdbcColumn column, 
StringBuilder sqlBuilder) {
     // Add Nullable data type
     String dataType = typeConverter.fromGravitino(column.dataType());
diff --git 
a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/converter/TestClickHouseColumnDefaultValueConverter.java
 
b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/converter/TestClickHouseColumnDefaultValueConverter.java
new file mode 100644
index 0000000000..0c8b8e0587
--- /dev/null
+++ 
b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/converter/TestClickHouseColumnDefaultValueConverter.java
@@ -0,0 +1,199 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.catalog.clickhouse.converter;
+
+import org.apache.gravitino.catalog.jdbc.converter.JdbcTypeConverter;
+import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.expressions.FunctionExpression;
+import org.apache.gravitino.rel.expressions.UnparsedExpression;
+import org.apache.gravitino.rel.expressions.literals.Literals;
+import org.apache.gravitino.rel.types.Decimal;
+import org.apache.gravitino.rel.types.Type;
+import org.apache.gravitino.rel.types.Types;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestClickHouseColumnDefaultValueConverter {
+
+  private static final ClickHouseColumnDefaultValueConverter CONVERTER =
+      new ClickHouseColumnDefaultValueConverter();
+
+  @Test
+  void testStringDefaultRoundTrip() {
+    String[] values = {"a'b", "a\\b", "it''s", ""};
+    for (String value : values) {
+      String sql = CONVERTER.fromGravitino(Literals.stringLiteral(value));
+      // ClickHouse reports string defaults with backslash escapes.
+      String reported = "'" + sql.substring(1, sql.length() - 1).replace("''", 
"\\'") + "'";
+      Assertions.assertEquals(
+          Literals.stringLiteral(value),
+          CONVERTER.toGravitino(
+              new JdbcTypeConverter.JdbcTypeBean("String"), reported, false, 
true),
+          "Round trip failed for " + value);
+    }
+  }
+
+  @Test
+  void testStringDefaultUnescape() {
+    JdbcTypeConverter.JdbcTypeBean stringType = new 
JdbcTypeConverter.JdbcTypeBean("String");
+    Assertions.assertEquals(
+        Literals.stringLiteral("a'b"), CONVERTER.toGravitino(stringType, 
"'a\\'b'", false, true));
+    Assertions.assertEquals(
+        Literals.stringLiteral("a'b"), CONVERTER.toGravitino(stringType, 
"'a''b'", false, true));
+    Assertions.assertEquals(
+        Literals.stringLiteral("a\\b"), CONVERTER.toGravitino(stringType, 
"'a\\\\b'", false, true));
+    Assertions.assertEquals(
+        Literals.stringLiteral("a\n\t\r\0\b\f\u0007\u000Bz"),
+        CONVERTER.toGravitino(stringType, "'a\\n\\t\\r\\0\\b\\f\\a\\v\\x7a'", 
false, true));
+    Assertions.assertEquals(
+        Literals.stringLiteral("xg1"), CONVERTER.toGravitino(stringType, 
"'\\xg1'", false, true));
+  }
+
+  @Test
+  void testUnparsedDefaultKeepsServerText() {
+    JdbcTypeConverter.JdbcTypeBean intType = new 
JdbcTypeConverter.JdbcTypeBean("Int32");
+    Assertions.assertEquals(
+        UnparsedExpression.of("a\\'b"), CONVERTER.toGravitino(intType, 
"'a\\'b'", false, true));
+  }
+
+  @Test
+  void testValidDefaultValues() {
+    assertAccepted(Types.ByteType.get(), "-128");
+    assertAccepted(Types.ByteType.get(), "127");
+    assertAccepted(Types.ByteType.unsigned(), "255");
+    assertAccepted(Types.ShortType.unsigned(), "65535");
+    assertAccepted(Types.IntegerType.get(), "-2147483648");
+    assertAccepted(Types.IntegerType.unsigned(), "4294967295");
+    assertAccepted(Types.LongType.unsigned(), "18446744073709551615");
+    assertAccepted(Types.DecimalType.of(3, 2), "9.99");
+    assertAccepted(Types.DateType.get(), "1970-01-01");
+    assertAccepted(Types.DateType.get(), "2149-06-06");
+    assertAccepted(Types.UUIDType.get(), 
"61f0c404-5cb3-11e7-907b-a6006ad3dba0");
+    assertAccepted(Types.DecimalType.of(3, 2), "-9.99");
+    // ClickHouse discards excess fractional digits and truncates integers 
toward zero.
+    assertAccepted(Types.DecimalType.of(3, 2), "9.995");
+    assertAccepted(Types.DecimalType.of(3, 2), "-9.999");
+    assertAccepted(Types.DecimalType.of(3, 2), "1e0");
+    assertAccepted(Types.IntegerType.get(), "1.0");
+    assertAccepted(Types.IntegerType.get(), "-1.9");
+    assertAccepted(Types.IntegerType.get(), "1e3");
+    assertAccepted(Types.IntegerType.get(), "2147483647.5");
+    assertAccepted(Types.IntegerType.get(), "-2147483648.9");
+    assertAccepted(Types.ByteType.get(), "127.9");
+    assertAccepted(Types.ByteType.unsigned(), "-0.5");
+    assertAccepted(Types.UUIDType.get(), 
"61F0C404-5CB3-11E7-907B-A6006AD3DBA0");
+    assertAccepted(Types.DoubleType.get(), "1.5");
+    assertAccepted(Types.DoubleType.get(), "-1e10");
+    assertAccepted(Types.DoubleType.get(), "nan");
+    assertAccepted(Types.FloatType.get(), "-inf");
+    assertAccepted(Types.FloatType.get(), "'1.5'");
+    // Callers may wrap the value in single quotes.
+    assertAccepted(Types.DateType.get(), "'2024-01-01'");
+    assertAccepted(Types.UUIDType.get(), 
"'61f0c404-5cb3-11e7-907b-a6006ad3dba0'");
+    assertAccepted(Types.IntegerType.get(), "'5'");
+  }
+
+  @Test
+  void testTypedLiteralDefaultValues() {
+    Assertions.assertDoesNotThrow(
+        () ->
+            CONVERTER.checkDefaultValue(
+                Types.DecimalType.of(3, 2), 
Literals.decimalLiteral(Decimal.of("9.995"))));
+    Assertions.assertDoesNotThrow(
+        () -> CONVERTER.checkDefaultValue(Types.IntegerType.get(), 
Literals.doubleLiteral(1.0)));
+    Assertions.assertThrows(
+        IllegalArgumentException.class,
+        () -> CONVERTER.checkDefaultValue(Types.ByteType.get(), 
Literals.integerLiteral(128)));
+  }
+
+  @Test
+  void testNumericLiteralMustBeNumber() {
+    Assertions.assertThrows(
+        IllegalArgumentException.class,
+        () -> CONVERTER.fromGravitino(Literals.of("1, x String", 
Types.IntegerType.get())));
+    Assertions.assertThrows(
+        IllegalArgumentException.class,
+        () -> CONVERTER.fromGravitino(Literals.of("", 
Types.IntegerType.get())));
+    Assertions.assertEquals("1.0E10", 
CONVERTER.fromGravitino(Literals.doubleLiteral(1.0E10)));
+    Assertions.assertEquals(
+        "5", CONVERTER.fromGravitino(Literals.of("'5'", 
Types.IntegerType.get())));
+    Assertions.assertThrows(
+        IllegalArgumentException.class,
+        () -> CONVERTER.fromGravitino(Literals.of("'1, x String'", 
Types.IntegerType.get())));
+    Assertions.assertEquals("NaN", 
CONVERTER.fromGravitino(Literals.doubleLiteral(Double.NaN)));
+    Assertions.assertEquals(
+        "-Infinity", 
CONVERTER.fromGravitino(Literals.doubleLiteral(Double.NEGATIVE_INFINITY)));
+  }
+
+  @Test
+  void testNonLiteralDefaultValuesSkipValidation() {
+    Assertions.assertDoesNotThrow(
+        () -> CONVERTER.checkDefaultValue(Types.IntegerType.get(), 
Literals.NULL));
+    Assertions.assertDoesNotThrow(
+        () -> CONVERTER.checkDefaultValue(Types.DateType.get(), 
FunctionExpression.of("today")));
+    Assertions.assertDoesNotThrow(
+        () ->
+            CONVERTER.checkDefaultValue(
+                Types.TimestampType.withoutTimeZone(), 
Column.DEFAULT_VALUE_OF_CURRENT_TIMESTAMP));
+    Assertions.assertDoesNotThrow(
+        () ->
+            CONVERTER.checkDefaultValue(
+                Types.UUIDType.get(), 
UnparsedExpression.of("generateUUIDv4()")));
+  }
+
+  @Test
+  void testInvalidDefaultValues() {
+    assertRejected(Types.ByteType.get(), "-129");
+    assertRejected(Types.ByteType.get(), "128");
+    assertRejected(Types.ByteType.unsigned(), "-1");
+    assertRejected(Types.ByteType.unsigned(), "256");
+    assertRejected(Types.ShortType.get(), "32768");
+    assertRejected(Types.IntegerType.get(), "2147483648");
+    assertRejected(Types.IntegerType.unsigned(), "4294967296");
+    assertRejected(Types.LongType.get(), "9223372036854775808");
+    assertRejected(Types.IntegerType.get(), "abc");
+    assertRejected(Types.DecimalType.of(3, 2), "99.999");
+    assertRejected(Types.DecimalType.of(3, 2), "10");
+    assertRejected(Types.DecimalType.of(3, 2), "-10.001");
+    assertRejected(Types.DecimalType.of(3, 2), "1e999999999");
+    assertRejected(Types.IntegerType.get(), "2147483648.0");
+    assertRejected(Types.IntegerType.get(), "-2147483649");
+    assertRejected(Types.IntegerType.get(), "1e999999999");
+    assertRejected(Types.ByteType.unsigned(), "-1.0");
+    assertRejected(Types.DateType.get(), "'2150-01-01'");
+    assertRejected(Types.DateType.get(), "1969-12-31");
+    assertRejected(Types.DateType.get(), "2150-01-01");
+    assertRejected(Types.DateType.get(), "2024-13-01");
+    assertRejected(Types.UUIDType.get(), "not-a-uuid");
+    assertRejected(Types.DoubleType.get(), "abc");
+    assertRejected(Types.FloatType.get(), "1, x String");
+  }
+
+  private static void assertAccepted(Type type, String value) {
+    Assertions.assertDoesNotThrow(
+        () -> CONVERTER.checkDefaultValue(type, Literals.of(value, type)));
+  }
+
+  private static void assertRejected(Type type, String value) {
+    Assertions.assertThrows(
+        IllegalArgumentException.class,
+        () -> CONVERTER.checkDefaultValue(type, Literals.of(value, type)),
+        "Expected rejection of " + value + " for " + type.simpleString());
+  }
+}
diff --git 
a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/converter/TestClickHouseTypeConverter.java
 
b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/converter/TestClickHouseTypeConverter.java
index 6440d3d0f1..d3a59df874 100644
--- 
a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/converter/TestClickHouseTypeConverter.java
+++ 
b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/converter/TestClickHouseTypeConverter.java
@@ -205,7 +205,7 @@ public class TestClickHouseTypeConverter {
     Assertions.assertTrue(exception.getMessage().contains("ClickHouse"));
     Assertions.assertTrue(exception.getMessage().contains("varchar(n)"));
     Assertions.assertTrue(exception.getMessage().contains("string"));
-    Assertions.assertTrue(exception.getMessage().contains("fixedchar(n)"));
+    Assertions.assertTrue(exception.getMessage().contains("char(n)"));
   }
 
   protected void checkGravitinoTypeToJdbcType(String jdbcTypeName, Type 
gravitinoType) {
diff --git 
a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperations.java
 
b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperations.java
index c184258ba5..f565ee748a 100644
--- 
a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperations.java
+++ 
b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperations.java
@@ -25,6 +25,7 @@ import static 
org.apache.gravitino.rel.Column.DEFAULT_VALUE_NOT_SET;
 
 import java.sql.Connection;
 import java.sql.DriverManager;
+import java.sql.ResultSet;
 import java.sql.Statement;
 import java.time.LocalDateTime;
 import java.util.ArrayList;
@@ -213,6 +214,155 @@ public class TestClickHouseTableOperations extends 
TestClickHouse {
         "dropping non-existent table should return false");
   }
 
+  @Test
+  public void testStringDefaultValueWithSpecialCharsRoundTrip() {
+    String tableName = RandomStringUtils.randomAlphabetic(16) + "_str_default";
+    String[] values = {"a'b", "a\\b", "a\\'b"};
+    List<JdbcColumn> columns = new ArrayList<>();
+    columns.add(
+        JdbcColumn.builder()
+            .withName("id")
+            .withType(Types.IntegerType.get())
+            .withNullable(false)
+            .build());
+    for (int i = 0; i < values.length; i++) {
+      columns.add(
+          JdbcColumn.builder()
+              .withName("c" + i)
+              .withType(Types.StringType.get())
+              .withNullable(true)
+              .withDefaultValue(Literals.stringLiteral(values[i]))
+              .build());
+    }
+
+    TABLE_OPERATIONS.create(
+        TEST_DB_NAME.toString(),
+        tableName,
+        columns.toArray(new JdbcColumn[0]),
+        null,
+        new HashMap<>(),
+        null,
+        Distributions.NONE,
+        null,
+        getSortOrders("id"));
+    JdbcTable load = TABLE_OPERATIONS.load(TEST_DB_NAME.toString(), tableName);
+    for (int i = 0; i < values.length; i++) {
+      String columnName = "c" + i;
+      Column column =
+          Arrays.stream(load.columns())
+              .filter(c -> c.name().equals(columnName))
+              .findFirst()
+              .orElseThrow();
+      Assertions.assertEquals(Literals.stringLiteral(values[i]), 
column.defaultValue());
+    }
+
+    Assertions.assertThrows(
+        IllegalArgumentException.class,
+        () ->
+            TABLE_OPERATIONS.alterTable(
+                TEST_DB_NAME.toString(),
+                tableName,
+                TableChange.addColumn(
+                    new String[] {"c_invalid"},
+                    Types.ByteType.get(),
+                    Literals.of("128", Types.ByteType.get()))));
+  }
+
+  @Test
+  public void testNumericDefaultValueTruncationOnClickHouse() throws Exception 
{
+    String tableName = RandomStringUtils.randomAlphabetic(16) + "_num_default";
+    JdbcColumn[] columns = {
+      JdbcColumn.builder()
+          .withName("id")
+          .withType(Types.IntegerType.get())
+          .withNullable(false)
+          .build(),
+      JdbcColumn.builder()
+          .withName("dec_col")
+          .withType(Types.DecimalType.of(3, 2))
+          .withNullable(false)
+          .withDefaultValue(Literals.decimalLiteral(Decimal.of("9.995")))
+          .build(),
+      JdbcColumn.builder()
+          .withName("int_col")
+          .withType(Types.IntegerType.get())
+          .withNullable(false)
+          .withDefaultValue(Literals.doubleLiteral(1.9))
+          .build(),
+      JdbcColumn.builder()
+          .withName("byte_col")
+          .withType(Types.ByteType.get())
+          .withNullable(false)
+          .withDefaultValue(Literals.of("-128.9", Types.ByteType.get()))
+          .build()
+    };
+
+    TABLE_OPERATIONS.create(
+        TEST_DB_NAME.toString(),
+        tableName,
+        columns,
+        null,
+        new HashMap<>(),
+        null,
+        Distributions.NONE,
+        null,
+        getSortOrders("id"));
+
+    String jdbcUrl = 
containerSuite.getClickHouseContainer().getJdbcUrl(TEST_DB_NAME);
+    try (Connection conn =
+            DriverManager.getConnection(
+                jdbcUrl,
+                containerSuite.getClickHouseContainer().getUsername(),
+                containerSuite.getClickHouseContainer().getPassword());
+        Statement stmt = conn.createStatement()) {
+      stmt.execute(
+          "INSERT INTO `%s`.`%s` (id) VALUES 
(1)".formatted(TEST_DB_NAME.toString(), tableName));
+      try (ResultSet rs =
+          stmt.executeQuery(
+              "SELECT toString(dec_col), int_col, byte_col FROM `%s`.`%s`"
+                  .formatted(TEST_DB_NAME.toString(), tableName))) {
+        Assertions.assertTrue(rs.next());
+        Assertions.assertEquals("9.99", rs.getString(1));
+        Assertions.assertEquals(1, rs.getInt(2));
+        Assertions.assertEquals(-128, rs.getInt(3));
+      }
+    }
+  }
+
+  @Test
+  public void testNumericDefaultValueCannotInjectDdl() {
+    String tableName = RandomStringUtils.randomAlphabetic(16) + 
"_inject_default";
+    JdbcColumn[] columns = {
+      JdbcColumn.builder()
+          .withName("id")
+          .withType(Types.IntegerType.get())
+          .withNullable(false)
+          .build(),
+      JdbcColumn.builder()
+          .withName("v")
+          .withType(Types.StringType.get())
+          .withNullable(true)
+          .withDefaultValue(Literals.of("1, x String", 
Types.IntegerType.get()))
+          .build()
+    };
+
+    Assertions.assertThrows(
+        IllegalArgumentException.class,
+        () ->
+            TABLE_OPERATIONS.create(
+                TEST_DB_NAME.toString(),
+                tableName,
+                columns,
+                null,
+                new HashMap<>(),
+                null,
+                Distributions.NONE,
+                null,
+                getSortOrders("id")));
+    Assertions.assertFalse(
+        
TABLE_OPERATIONS.listTables(TEST_DB_NAME.toString()).contains(tableName));
+  }
+
   @Test
   public void testAlterTable() {
     String tableName = RandomStringUtils.randomAlphabetic(16) + "_al_table";
@@ -2056,6 +2206,79 @@ public class TestClickHouseTableOperations extends 
TestClickHouse {
         .build();
   }
 
+  @Test
+  public void testAlterTableDefaultValueValidation() {
+    StubClickHouseTableOperations ops = new StubClickHouseTableOperations();
+    ops.initialize(
+        null,
+        new ClickHouseExceptionConverter(),
+        new ClickHouseTypeConverter(),
+        new ClickHouseColumnDefaultValueConverter(),
+        new HashMap<>());
+    JdbcColumn c1 =
+        JdbcColumn.builder()
+            .withName("c1")
+            .withType(Types.IntegerType.get())
+            .withDefaultValue(Literals.of("300", Types.IntegerType.get()))
+            .build();
+    // A default that does not fit its type can exist when the table was 
created outside Gravitino.
+    JdbcColumn c2 =
+        JdbcColumn.builder()
+            .withName("c2")
+            .withType(Types.ByteType.get())
+            .withDefaultValue(Literals.of("200", Types.ByteType.get()))
+            .build();
+    ops.setTable(
+        JdbcTable.builder()
+            .withName("tbl")
+            .withColumns(new JdbcColumn[] {c1, c2})
+            .withTableOperation(null)
+            .build());
+
+    Assertions.assertThrows(
+        IllegalArgumentException.class,
+        () ->
+            ops.buildAlterSql(
+                "db",
+                "tbl",
+                new TableChange[] {
+                  TableChange.updateColumnDefaultValue(
+                      new String[] {"c1"}, Literals.of("2147483648", 
Types.IntegerType.get()))
+                }));
+
+    IllegalArgumentException typeChange =
+        Assertions.assertThrows(
+            IllegalArgumentException.class,
+            () ->
+                ops.buildAlterSql(
+                    "db",
+                    "tbl",
+                    new TableChange[] {
+                      TableChange.updateColumnType(new String[] {"c1"}, 
Types.ByteType.get())
+                    }));
+    Assertions.assertTrue(
+        typeChange.getMessage().contains("existing default value of column 
c1"),
+        typeChange.getMessage());
+    Assertions.assertDoesNotThrow(
+        () ->
+            ops.buildAlterSql(
+                "db",
+                "tbl",
+                new TableChange[] {
+                  TableChange.updateColumnType(new String[] {"c1"}, 
Types.LongType.get())
+                }));
+
+    // Changes that keep the existing default do not validate it again.
+    Assertions.assertDoesNotThrow(
+        () ->
+            ops.buildAlterSql(
+                "db",
+                "tbl",
+                new TableChange[] {
+                  TableChange.updateColumnComment(new String[] {"c2"}, "new 
comment")
+                }));
+  }
+
   private static JdbcTable buildStubTableWithNullDefault() {
     JdbcColumn c1 = 
JdbcColumn.builder().withName("c1").withType(Types.IntegerType.get()).build();
     JdbcColumn c2 = 
JdbcColumn.builder().withName("c2").withType(Types.StringType.get()).build();
diff --git 
a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/converter/JdbcColumnDefaultValueConverter.java
 
b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/converter/JdbcColumnDefaultValueConverter.java
index 9f457a7286..eef03e7641 100644
--- 
a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/converter/JdbcColumnDefaultValueConverter.java
+++ 
b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/converter/JdbcColumnDefaultValueConverter.java
@@ -178,7 +178,15 @@ public class JdbcColumnDefaultValueConverter {
     return "X'" + BaseEncoding.base16().lowerCase().encode(value) + "'";
   }
 
-  private static String validateNumericLiteral(String value) {
+  /**
+   * Checks that a numeric default value is a plain number, so it can be 
written into the DDL
+   * without quotes.
+   *
+   * @param value the numeric default value text
+   * @return the trimmed value
+   * @throws IllegalArgumentException if the value is not a valid number
+   */
+  protected static String validateNumericLiteral(String value) {
     String trimmed = value.trim();
     try {
       new BigDecimal(trimmed);
diff --git a/docs/jdbc-clickhouse-catalog.md b/docs/jdbc-clickhouse-catalog.md
index fdc7be7a56..bfd3738fa1 100644
--- a/docs/jdbc-clickhouse-catalog.md
+++ b/docs/jdbc-clickhouse-catalog.md
@@ -202,6 +202,15 @@ See [Manage Catalogs and 
Schemas](./manage-catalogs-and-schemas.md#schema-operat
 Other ClickHouse types are exposed as [External 
Type](./tables-and-views.md#external-type).
 `VarChar(n)` is rejected when creating or adding a column because ClickHouse 
cannot enforce its length limit.
 Use `String` for unlimited text or `FixedChar(n)` for fixed-length values.
+In the REST API and JSON payloads, `FixedChar(n)` is written as `char(n)`, for 
example `"type": "char(10)"`.
+By default, ClickHouse rejects `FixedString(n)` with `n` greater than 256 
unless the server setting
+`allow_suspicious_fixed_string_types` is set to `1`.
+
+Literal column default values are checked against the column type before the 
DDL is sent, because
+ClickHouse does not validate them when creating or altering a table. Integer 
defaults must be in the
+range of the type, `Decimal(p,s)` defaults must fit the precision, `Date` 
defaults must be between
+`1970-01-01` and `2149-06-06`, `UUID` defaults must be valid UUID strings, and 
`Float`/`Double`
+defaults must be numbers. Default values of other types, such as `Timestamp`, 
are not checked.
 
 ### Table Properties
 

Reply via email to