Stephen0421 commented on code in PR #10675: URL: https://github.com/apache/paimon/pull/10675#discussion_r4374822504
########## 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: Thanks for catching this! Fixed in 6ff715ea0a. For `TIMESTAMP` without time zone, a numeric default goes through `BinaryStringUtils.fromMillisToTimestamp`, which only supports precision 0, 3, 6 and 9. The validator now runs the same checks in the same order as Java: 1. The value must match `StringUtils.isNumeric` and fit in a BIGINT. Otherwise it is rejected as overflow. 2. The column precision must be 0, 3, 6 or 9. Otherwise it is rejected, matching `Unsupported precision: p` in Java. Notes: - A bare `TIMESTAMP` uses the default precision 6. A `NOT NULL` suffix does not affect how the precision is read. - Only the numeric path is limited. A string timestamp such as `TIMESTAMP(2)` with `'2024-01-01 12:00:00.12'` is still accepted, because that path has no precision check in Java. - `TIMESTAMP WITH LOCAL TIME ZONE` has no numeric path in Java, so numeric defaults for it are still rejected. Tests: - `test_rejects_scalar_defaults_java_rejects`: `TIMESTAMP(2)` with `1700000000000`, `TIMESTAMP(1)` with `-1`, and `TIMESTAMP(7)` with `0`. - `test_accepts_scalar_defaults_java_accepts`: `TIMESTAMP(0)`, `TIMESTAMP(9)`, bare `TIMESTAMP` and `TIMESTAMP(3) NOT NULL` with `1700000000000`, plus `TIMESTAMP(2)` with a string timestamp. - `test_invalid_defaults_do_not_commit_schema`: committing `TIMESTAMP(2)` with `1700000000000` fails and leaves the schema id unchanged. - Python-to-Java interop: Python sets a `TIMESTAMP(3)` default of `1700000000000`. `JavaPyE2ETest#testReadPythonColumnDefaultValues` then opens `newWrite()`, fills the default and reads back `2023-11-14T22:13:20`. -- 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]
