JingsongLi commented on code in PR #10675:
URL: https://github.com/apache/paimon/pull/10675#discussion_r4374361187


##########
paimon-python/pypaimon/schema/default_value.py:
##########
@@ -0,0 +1,320 @@
+# 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.
+
+"""Validate a scalar column default before it is stored.
+
+The stored value is still the original string. Scalar checks follow the Java
+string casts used by ``DefaultValueUtils`` for booleans, numbers, dates, times
+and timestamps. ARRAY, MAP and ROW defaults are accepted by Java's
+``StringToArrayCastRule``, ``StringToMapCastRule`` and ``StringToRowCastRule``;
+Python does not parse those forms yet and rejects them explicitly.
+"""
+
+import re
+from calendar import monthrange
+from datetime import time
+from typing import Optional
+
+from pypaimon.schema.data_types import AtomicType
+
+_TRUE = {"t", "true", "y", "yes", "1"}
+_FALSE = {"f", "false", "n", "no", "0"}
+_INT_MIN = -2147483648
+_INT_MAX = 2147483647
+_INT_RANGES = {
+    "TINYINT": (-128, 127),
+    "SMALLINT": (-32768, 32767),
+    "INT": (_INT_MIN, _INT_MAX),
+    "INTEGER": (_INT_MIN, _INT_MAX),
+    "BIGINT": (-9223372036854775808, 9223372036854775807),
+}
+_INTEGRAL = set(_INT_RANGES)
+_APPROXIMATE = {"FLOAT", "DOUBLE"}
+_CHARACTER = {"STRING", "CHAR", "VARCHAR"}
+_BINARY = {"BINARY", "VARBINARY", "BYTES"}
+_UNSIGNED_INTEGER_RE = re.compile(r"[0-9]+")
+# StringUtils.isNumeric guards the epoch fast path of DATE, TIME and TIMESTAMP.
+# It allows a leading '-' but not '+', and only ASCII digits after it.
+_JAVA_NUMERIC_RE = re.compile(r"-?[0-9]+")
+_INTEGRAL_RE = re.compile(r"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]*)")
+# BigDecimal(String) reads digits with Character.digit, so Unicode digits are
+# valid here, unlike the other numeric casts.
+_DECIMAL_RE = re.compile(
+    r"[+-]?(?:(\d+)(?:\.(\d*))?|\.(\d+))(?:[eE]([+-]?\d+))?")
+_DECIMAL_SCALE_RE = re.compile(r"\(\s*\d+\s*(?:,\s*(\d+)\s*)?\)")
+# Decimal.fromBigDecimal rescales with BigDecimal.setScale, which needs
+# BigInteger.TEN.pow(raise). pow rejects any raise where
+# bitLength(10) * raise / 32 exceeds BigInteger.MAX_MAG_LENGTH (2^26 + 1).
+_MAX_TEN_POWER = 8 * ((1 << 26) + 1)
+# Float.parseFloat / Double.parseDouble accept hexadecimal literals and type
+# suffixes, but not Python's underscores or case-insensitive special values.
+_FLOAT_RE = re.compile(
+    r"[+-]?(?:NaN|Infinity|"
+    r"(?:(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?|"
+    r"0[xX](?:[0-9a-fA-F]+(?:\.[0-9a-fA-F]*)?|\.[0-9a-fA-F]+)"
+    r"[pP][+-]?[0-9]+)[fFdD]?)")
+_JAVA_TRIM_CHARS = "".join(chr(i) for i in range(33))
+# DateTimeUtils.DEFAULT_TIMESTAMP_FORMATTER: the time is optional, a space
+# requires hour:minute:second, and 'T' requires hour:minute with optional
+# seconds. appendFraction has a minimum width of 0, so a bare '.' is allowed.
+# 'yyyy' is SignStyle.EXCEEDS_PAD: exactly four digits, or '+' and five to
+# nineteen digits. The formatter only accepts ASCII digits, so use [0-9], not
+# \d. Anchor with \Z, not $, so a trailing newline does not slip through.
+_TIMESTAMP_DATE = r"^(\+[0-9]{5,19}|[0-9]{4})-([0-9]{1,2})-([0-9]{1,2})"
+_TIMESTAMP_SPACE_RE = re.compile(
+    _TIMESTAMP_DATE
+    + r"(?: ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})(?:\.([0-9]{0,9}))?)?\Z")
+_TIMESTAMP_T_RE = re.compile(
+    _TIMESTAMP_DATE
+    + r"T([0-9]{1,2}):([0-9]{1,2})(?::([0-9]{1,2})(?:\.([0-9]{0,9}))?)?\Z")
+_MAX_YEAR = 999999999
+
+
+def validate_default_value(data_type, default_value: Optional[str]) -> None:
+    """Raise if ``default_value`` cannot be cast to ``data_type``.
+
+    ``None`` clears the default and is always accepted.
+    """
+    if default_value is None:
+        return
+    if not isinstance(data_type, AtomicType):
+        raise RuntimeError(
+            "Unsupported default value `{}` for type {}. Python currently "
+            "validates scalar defaults only; ARRAY, MAP and ROW defaults "
+            "are not supported.".format(default_value, data_type))
+    try:
+        _convert(data_type, _unquote(default_value))
+    except Exception as cause:
+        raise RuntimeError(
+            "Unsupported default value `{}` for type {}".format(
+                default_value, data_type)
+        ) from cause
+
+
+def _unquote(value: str) -> str:
+    if len(value) >= 2 and value.startswith("'") and value.endswith("'"):

Review Comment:
   [P2] Reject a lone quote before persisting a string default
   
   A one-character apostrophe passes this length guard unchanged and is 
accepted as a STRING default. UpdateColumnDefaultValue(["name"], "'") therefore 
commits successfully, but opening a Java writer on that persisted schema throws 
StringIndexOutOfBoundsException in DefaultValueUtils.convertDefaultValue: Java 
treats the value as quoted and attempts substring(1, 0). Actual quoted "hello" 
and a correctly wrapped apostrophe (three quote characters) both initialize the 
writer successfully. Reject the lone-quote form before publishing the schema, 
rather than accepting a value the JVM cannot cast, and add an alteration 
followed by Java writer initialization test.



##########
paimon-python/pypaimon/schema/default_value.py:
##########
@@ -0,0 +1,320 @@
+# 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.
+
+"""Validate a scalar column default before it is stored.
+
+The stored value is still the original string. Scalar checks follow the Java
+string casts used by ``DefaultValueUtils`` for booleans, numbers, dates, times
+and timestamps. ARRAY, MAP and ROW defaults are accepted by Java's
+``StringToArrayCastRule``, ``StringToMapCastRule`` and ``StringToRowCastRule``;
+Python does not parse those forms yet and rejects them explicitly.
+"""
+
+import re
+from calendar import monthrange
+from datetime import time
+from typing import Optional
+
+from pypaimon.schema.data_types import AtomicType
+
+_TRUE = {"t", "true", "y", "yes", "1"}
+_FALSE = {"f", "false", "n", "no", "0"}
+_INT_MIN = -2147483648
+_INT_MAX = 2147483647
+_INT_RANGES = {
+    "TINYINT": (-128, 127),
+    "SMALLINT": (-32768, 32767),
+    "INT": (_INT_MIN, _INT_MAX),
+    "INTEGER": (_INT_MIN, _INT_MAX),
+    "BIGINT": (-9223372036854775808, 9223372036854775807),
+}
+_INTEGRAL = set(_INT_RANGES)
+_APPROXIMATE = {"FLOAT", "DOUBLE"}
+_CHARACTER = {"STRING", "CHAR", "VARCHAR"}
+_BINARY = {"BINARY", "VARBINARY", "BYTES"}
+_UNSIGNED_INTEGER_RE = re.compile(r"[0-9]+")
+# StringUtils.isNumeric guards the epoch fast path of DATE, TIME and TIMESTAMP.
+# It allows a leading '-' but not '+', and only ASCII digits after it.
+_JAVA_NUMERIC_RE = re.compile(r"-?[0-9]+")
+_INTEGRAL_RE = re.compile(r"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]*)")
+# BigDecimal(String) reads digits with Character.digit, so Unicode digits are
+# valid here, unlike the other numeric casts.
+_DECIMAL_RE = re.compile(
+    r"[+-]?(?:(\d+)(?:\.(\d*))?|\.(\d+))(?:[eE]([+-]?\d+))?")
+_DECIMAL_SCALE_RE = re.compile(r"\(\s*\d+\s*(?:,\s*(\d+)\s*)?\)")
+# Decimal.fromBigDecimal rescales with BigDecimal.setScale, which needs
+# BigInteger.TEN.pow(raise). pow rejects any raise where
+# bitLength(10) * raise / 32 exceeds BigInteger.MAX_MAG_LENGTH (2^26 + 1).
+_MAX_TEN_POWER = 8 * ((1 << 26) + 1)
+# Float.parseFloat / Double.parseDouble accept hexadecimal literals and type
+# suffixes, but not Python's underscores or case-insensitive special values.
+_FLOAT_RE = re.compile(
+    r"[+-]?(?:NaN|Infinity|"
+    r"(?:(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?|"
+    r"0[xX](?:[0-9a-fA-F]+(?:\.[0-9a-fA-F]*)?|\.[0-9a-fA-F]+)"
+    r"[pP][+-]?[0-9]+)[fFdD]?)")
+_JAVA_TRIM_CHARS = "".join(chr(i) for i in range(33))
+# DateTimeUtils.DEFAULT_TIMESTAMP_FORMATTER: the time is optional, a space
+# requires hour:minute:second, and 'T' requires hour:minute with optional
+# seconds. appendFraction has a minimum width of 0, so a bare '.' is allowed.
+# 'yyyy' is SignStyle.EXCEEDS_PAD: exactly four digits, or '+' and five to
+# nineteen digits. The formatter only accepts ASCII digits, so use [0-9], not
+# \d. Anchor with \Z, not $, so a trailing newline does not slip through.
+_TIMESTAMP_DATE = r"^(\+[0-9]{5,19}|[0-9]{4})-([0-9]{1,2})-([0-9]{1,2})"
+_TIMESTAMP_SPACE_RE = re.compile(
+    _TIMESTAMP_DATE
+    + r"(?: ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})(?:\.([0-9]{0,9}))?)?\Z")
+_TIMESTAMP_T_RE = re.compile(
+    _TIMESTAMP_DATE
+    + r"T([0-9]{1,2}):([0-9]{1,2})(?::([0-9]{1,2})(?:\.([0-9]{0,9}))?)?\Z")
+_MAX_YEAR = 999999999
+
+
+def validate_default_value(data_type, default_value: Optional[str]) -> None:
+    """Raise if ``default_value`` cannot be cast to ``data_type``.
+
+    ``None`` clears the default and is always accepted.
+    """
+    if default_value is None:
+        return
+    if not isinstance(data_type, AtomicType):
+        raise RuntimeError(
+            "Unsupported default value `{}` for type {}. Python currently "
+            "validates scalar defaults only; ARRAY, MAP and ROW defaults "
+            "are not supported.".format(default_value, data_type))
+    try:
+        _convert(data_type, _unquote(default_value))
+    except Exception as cause:
+        raise RuntimeError(
+            "Unsupported default value `{}` for type {}".format(
+                default_value, data_type)
+        ) from cause
+
+
+def _unquote(value: str) -> str:
+    if len(value) >= 2 and value.startswith("'") and value.endswith("'"):
+        return value[1:-1]
+    return value
+
+
+def _convert(data_type, text: str) -> None:
+    root = _type_root(data_type.type)
+    if root in _CHARACTER or root in _BINARY:
+        return
+    if root == "BOOLEAN" or root == "BOOL":
+        if text.lower() not in _TRUE and text.lower() not in _FALSE:
+            raise ValueError("Cannot parse {!r} as BOOLEAN.".format(text))
+        return
+    if root in _INTEGRAL:
+        _parse_integral(text, root)
+        return
+    if root in _APPROXIMATE:
+        if _FLOAT_RE.fullmatch(text.strip(_JAVA_TRIM_CHARS)) is None:
+            raise ValueError("Invalid floating-point value {}".format(text))
+        return
+    if root == "DECIMAL" or root == "NUMERIC":
+        _parse_decimal(text, _decimal_scale(data_type.type))
+        return
+    if root == "DATE":
+        _parse_date(text)
+        return
+    if root == "TIME":
+        _parse_time(text)
+        return
+    if root == "TIMESTAMP":
+        if _JAVA_NUMERIC_RE.fullmatch(text):
+            _parse_integral(text, "BIGINT")

Review Comment:
   [P2] Check TIMESTAMP precision before accepting an epoch default
   
   For a valid TIMESTAMP(2) column, UpdateColumnDefaultValue(["ts"], 
"1700000000000") passes this BIGINT-only check and commits schema-1, but 
reopening the same schema and calling newBatchWriteBuilder().newWrite() in Java 
throws "Unsupported precision: 2" from BinaryStringUtils.fromMillisToTimestamp. 
That conversion only supports precisions 0, 3, 6 and 9; the table works with no 
default, with a calendar-string default, or after clearing it. Inspect the 
declared timestamp precision and reject unsupported epoch/precision 
combinations before committing, with a persisted Python-to-Java writer 
regression.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to