You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@paimon.apache.org by "TheR1sing3un (via GitHub)" <gi...@apache.org> on 2026/06/10 02:25:48 UTC
[PR] [python] Support schema evolution of nested struct sub-fields [paimon]
TheR1sing3un opened a new pull request, #8187:
URL: https://github.com/apache/paimon/pull/8187
Read-time schema evolution previously aligned only top-level columns by field id; sub-fields inside a ROW (and a ROW nested in an ARRAY/MAP) could not evolve: adding one silently created a top-level column, and rename/drop/update-type raised because the schema manager only handled the last path element.
- Assign globally-unique ids to nested sub-fields at create time and compute highestFieldId recursively, so nested ids never collide with top-level ones.
- Recurse schema changes along the dotted field-name path (transparently through ARRAY/MAP wrappers) for add/rename/drop/update-type/update-nullability/ update-comment, allocating new ids from the persisted highestFieldId.
- Validate update-column-type against the cast-support rules.
- Align nested sub-fields by field id at read time: reorder, pad missing with NULL, follow renames, and cast changed types, recursing into struct/array/map.
Add tests covering nested add/rename/drop/update-type round-trips (append-only and primary-key), ARRAY<ROW>/MAP<.,ROW> sub-fields, the id model, and the cast rules.
### Purpose
### Tests
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [python] Support schema evolution of nested struct sub-fields [paimon]
Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi merged PR #8187:
URL: https://github.com/apache/paimon/pull/8187
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [python] Support schema evolution of nested struct sub-fields [paimon]
Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #8187:
URL: https://github.com/apache/paimon/pull/8187#discussion_r3393438569
##########
paimon-python/pypaimon/read/reader/data_file_batch_reader.py:
##########
@@ -57,55 +122,105 @@ def __init__(self, format_reader: RecordBatchReader, index_mapping: List[int], p
self.file_io = file_io
# Per-file field-id normalization: map the physically-read columns
# (the file's own field order/names) onto the latest read target by
- # field id, padding missing ids with NULL. ``None`` when there is no
- # evolution to reconcile (identity) -- the common path stays zero-copy.
- self._normalize_positions, self._normalize_names = \
- self._build_normalize_plan(file_data_fields, target_data_fields)
+ # field id, padding missing ids with NULL and recursing into nested
+ # ROW / ARRAY<ROW> / MAP<.,ROW> sub-fields the same way. ``None`` when
+ # there is no evolution to reconcile -- the common path stays zero-copy.
+ self._normalize_plan = self._build_normalize_plan(file_data_fields, target_data_fields)
@staticmethod
def _build_normalize_plan(file_data_fields, target_data_fields):
"""Build a per-file field-id alignment plan.
- Returns ``(positions, names)`` where ``positions[i]`` is the column
- index in the physically-read batch carrying ``target_data_fields[i]``
- (matched by field id), or -1 if the file does not contain that id (pad
- NULL). ``names[i]`` is the latest target name. Returns ``(None, None)``
- when the plan is the identity (no evolution), so the caller skips
- normalization and stays zero-copy.
+ Returns a list of ``(pos, file_field, target_field)`` -- one per target
+ field, in target order -- where ``pos`` is the column index in the
+ physically-read batch carrying ``target_field`` (matched by field id),
+ or -1 if the file does not contain that id (pad NULL). Returns ``None``
+ when the file already matches the target exactly (no evolution), so the
+ caller stays zero-copy.
"""
if file_data_fields is None or target_data_fields is None:
- return None, None
+ return None
+ # Recursive equality covers nested sub-field changes too: any rename /
+ # add / drop / type change at any depth makes the file != target.
+ if file_data_fields == target_data_fields:
+ return None
file_id_to_pos = {f.id: i for i, f in enumerate(file_data_fields)}
- positions = []
- names = []
- # Identity only when every target maps to the same physical position
- # AND already carries the same name -- a rename keeps the position but
- # changes the name, which still requires a relabel pass.
- identity = len(file_data_fields) == len(target_data_fields)
- for i, target in enumerate(target_data_fields):
+ plan = []
+ for target in target_data_fields:
pos = file_id_to_pos.get(target.id, -1)
- positions.append(pos)
- names.append(target.name)
- if pos != i or (pos >= 0 and file_data_fields[pos].name != target.name):
- identity = False
- if identity:
- return None, None
- return positions, names
+ file_field = file_data_fields[pos] if pos >= 0 else None
+ plan.append((pos, file_field, target))
+ return plan
def _normalize_batch(self, record_batch: RecordBatch) -> RecordBatch:
"""Reorder/pad the physically-read batch onto the latest read target by
- field id, and relabel columns to the latest names. Missing ids become
- all-NULL columns; types are reconciled later by _align_batch_to_read_schema."""
- if self._normalize_positions is None:
+ field id, relabel columns to the latest names, and align nested ROW
+ sub-fields by id. Missing ids become typed all-NULL columns."""
+ if self._normalize_plan is None:
return record_batch
num_rows = record_batch.num_rows
arrays = []
- for pos in self._normalize_positions:
+ names = []
+ for pos, file_field, target_field in self._normalize_plan:
+ target_pa_type = PyarrowFieldParser.from_paimon_type(target_field.type)
if pos < 0:
- arrays.append(pa.nulls(num_rows))
+ arrays.append(pa.nulls(num_rows, type=target_pa_type))
else:
- arrays.append(record_batch.column(pos))
- return pa.RecordBatch.from_arrays(arrays, names=self._normalize_names)
+ arrays.append(self._align_array_by_id(
+ record_batch.column(pos), file_field.type, target_field.type))
+ names.append(target_field.name)
+ return pa.RecordBatch.from_arrays(arrays, names=names)
+
+ def _align_array_by_id(self, array, file_type, target_type):
+ """Return *array* converted to *target_type*, matching ROW sub-fields by
+ field id (reorder, pad missing with NULL, follow renames, cast changed
+ types) recursively, transparently through ARRAY/MAP wrappers."""
+ if isinstance(target_type, RowType) and isinstance(file_type, RowType):
+ n = len(array)
+ file_id_to_pos = {f.id: i for i, f in enumerate(file_type.fields)}
+ children = []
+ pa_fields = []
+ for tsub in target_type.fields:
+ p = file_id_to_pos.get(tsub.id, -1)
+ if p < 0:
+ child = pa.nulls(n, type=PyarrowFieldParser.from_paimon_type(tsub.type))
+ else:
+ child = self._align_array_by_id(
+ array.field(p), file_type.fields[p].type, tsub.type)
+ children.append(child)
+ pa_fields.append(pa.field(tsub.name, child.type, nullable=tsub.type.nullable))
+ # Preserve the struct's own null mask; child values under a null
+ # struct are irrelevant.
+ return pa.StructArray.from_arrays(
+ children, fields=pa_fields, mask=pc.is_null(array))
+ if isinstance(target_type, ArrayType) and isinstance(file_type, ArrayType):
+ aligned_values = self._align_array_by_id(
+ array.values, file_type.element, target_type.element)
+ return pa.ListArray.from_arrays(
+ array.offsets, aligned_values, mask=pc.is_null(array))
+ if isinstance(target_type, MapType) and isinstance(file_type, MapType):
+ aligned_items = self._align_array_by_id(
+ array.items, file_type.value, target_type.value)
+ # MapArray.from_arrays cannot carry a null mask (a null map would
+ # collapse to an empty one), so rebuild from buffers, reusing the
+ # original validity/offset buffers and only swapping the value child.
+ target_pa = PyarrowFieldParser.from_paimon_type(target_type)
+ entries = pa.StructArray.from_arrays(
+ [array.keys, aligned_items],
+ fields=[target_pa.key_field, target_pa.item_field])
+ return pa.Array.from_buffers(
+ target_pa, len(array), array.buffers()[:2], children=[entries])
+ # A constructed type changed to a character string: pyarrow cannot
+ # cast struct/list/map to utf8 directly, so render the engine's
+ # string form instead.
+ if (isinstance(file_type, (RowType, ArrayType, MapType))
Review Comment:
This still leaves VECTOR -> STRING accepted but unreadable. `supports_cast` includes VECTOR in `CONSTRUCTED`, so `update_column_type("embed", STRING)` succeeds for a vector column, but old files reach this fallback and PyArrow raises `ArrowNotImplementedError: Unsupported cast from fixed_size_list<...> to utf8`. I reproduced it with an inline `pa.list_(pa.float32(), 3)` vector column. Please either include `VectorType` in the read-time string rendering path (fixed-size lists do not have offsets like normal lists), or narrow the cast rule so VECTOR -> CHAR/VARCHAR is rejected until it is supported.
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [python] Support schema evolution of nested struct sub-fields [paimon]
Posted by "TheR1sing3un (via GitHub)" <gi...@apache.org>.
TheR1sing3un commented on code in PR #8187:
URL: https://github.com/apache/paimon/pull/8187#discussion_r3394325649
##########
paimon-python/pypaimon/schema/schema_manager.py:
##########
@@ -44,6 +46,108 @@ def _find_field_index(fields: List[DataField], field_name: str) -> Optional[int]
return None
+def _extract_row_data_fields(data_type, out_fields: List[DataField]) -> int:
+ """Collect the immediate sub-fields reachable from *data_type* into
+ *out_fields* and return the path depth consumed. A ROW contributes its
+ fields (depth 1); an ARRAY/MAP is transparent and descends into its
+ element/value (consuming the ``element``/``value`` path token); anything
+ else contributes nothing (depth 1)."""
+ if isinstance(data_type, RowType):
+ out_fields.extend(data_type.fields)
+ return 1
+ if isinstance(data_type, ArrayType):
+ return _extract_row_data_fields(data_type.element, out_fields) + 1
+ if isinstance(data_type, MapType):
+ return _extract_row_data_fields(data_type.value, out_fields) + 1
+ return 1
+
+
+def _wrap_new_row_type(data_type, nested_fields: List[DataField]):
+ """Rebuild *data_type* substituting *nested_fields* at its innermost ROW,
+ preserving any ARRAY/MAP wrappers."""
+ if isinstance(data_type, RowType):
+ return RowType(data_type.nullable, nested_fields)
+ if isinstance(data_type, ArrayType):
+ return ArrayType(data_type.nullable, _wrap_new_row_type(data_type.element, nested_fields))
+ if isinstance(data_type, MapType):
+ return MapType(
+ data_type.nullable, data_type.key,
+ _wrap_new_row_type(data_type.value, nested_fields))
+ return data_type
+
+
+def _get_root_type(data_type, curr_depth: int, max_depth: int):
+ """Return the type sitting at ``max_depth`` when walking ARRAY/MAP wrappers
+ from *data_type* (e.g. the INT in ARRAY<MAP<STRING, ARRAY<INT>>>)."""
+ if curr_depth == max_depth - 1:
+ return data_type
+ if isinstance(data_type, ArrayType):
+ return _get_root_type(data_type.element, curr_depth + 1, max_depth)
+ if isinstance(data_type, MapType):
+ return _get_root_type(data_type.value, curr_depth + 1, max_depth)
+ return data_type
+
+
+def _get_array_map_type_with_target_type_root(source, target, curr_depth: int, max_depth: int):
+ """Rebuild *source* with *target* substituted at ``max_depth``, keeping the
+ ARRAY/MAP wrappers around it intact."""
+ if curr_depth == max_depth - 1:
+ return target
+ if isinstance(source, ArrayType):
+ return ArrayType(
+ source.nullable,
+ _get_array_map_type_with_target_type_root(
+ source.element, target, curr_depth + 1, max_depth))
+ if isinstance(source, MapType):
+ return MapType(
+ source.nullable, source.key,
+ _get_array_map_type_with_target_type_root(
+ source.value, target, curr_depth + 1, max_depth))
+ return target
+
+
+def _update_intermediate_column(new_fields, previous_fields, depth, prev_depth,
+ field_names, update_last_fn):
+ """Walk *field_names* into nested ROW (transparently through ARRAY/MAP),
+ then run *update_last_fn(depth, fields, name)* on the field list that
+ directly contains the final path element, rebuilding parent types upward."""
+ if depth == len(field_names) - 1:
+ update_last_fn(depth, new_fields, field_names[depth])
+ return
+ if depth >= len(field_names):
+ # Path descended through ARRAY/MAP past the last ROW; operate on the
+ # field that owns the wrapper at the previous depth.
+ update_last_fn(prev_depth, previous_fields, field_names[prev_depth])
+ return
+ for i, field in enumerate(new_fields):
+ if field.name != field_names[depth]:
+ continue
+ nested_fields: List[DataField] = []
+ new_depth = depth + _extract_row_data_fields(field.type, nested_fields)
Review Comment:
fixed
##########
paimon-python/pypaimon/read/reader/data_file_batch_reader.py:
##########
@@ -57,55 +122,105 @@ def __init__(self, format_reader: RecordBatchReader, index_mapping: List[int], p
self.file_io = file_io
# Per-file field-id normalization: map the physically-read columns
# (the file's own field order/names) onto the latest read target by
- # field id, padding missing ids with NULL. ``None`` when there is no
- # evolution to reconcile (identity) -- the common path stays zero-copy.
- self._normalize_positions, self._normalize_names = \
- self._build_normalize_plan(file_data_fields, target_data_fields)
+ # field id, padding missing ids with NULL and recursing into nested
+ # ROW / ARRAY<ROW> / MAP<.,ROW> sub-fields the same way. ``None`` when
+ # there is no evolution to reconcile -- the common path stays zero-copy.
+ self._normalize_plan = self._build_normalize_plan(file_data_fields, target_data_fields)
@staticmethod
def _build_normalize_plan(file_data_fields, target_data_fields):
"""Build a per-file field-id alignment plan.
- Returns ``(positions, names)`` where ``positions[i]`` is the column
- index in the physically-read batch carrying ``target_data_fields[i]``
- (matched by field id), or -1 if the file does not contain that id (pad
- NULL). ``names[i]`` is the latest target name. Returns ``(None, None)``
- when the plan is the identity (no evolution), so the caller skips
- normalization and stays zero-copy.
+ Returns a list of ``(pos, file_field, target_field)`` -- one per target
+ field, in target order -- where ``pos`` is the column index in the
+ physically-read batch carrying ``target_field`` (matched by field id),
+ or -1 if the file does not contain that id (pad NULL). Returns ``None``
+ when the file already matches the target exactly (no evolution), so the
+ caller stays zero-copy.
"""
if file_data_fields is None or target_data_fields is None:
- return None, None
+ return None
+ # Recursive equality covers nested sub-field changes too: any rename /
+ # add / drop / type change at any depth makes the file != target.
+ if file_data_fields == target_data_fields:
+ return None
file_id_to_pos = {f.id: i for i, f in enumerate(file_data_fields)}
- positions = []
- names = []
- # Identity only when every target maps to the same physical position
- # AND already carries the same name -- a rename keeps the position but
- # changes the name, which still requires a relabel pass.
- identity = len(file_data_fields) == len(target_data_fields)
- for i, target in enumerate(target_data_fields):
+ plan = []
+ for target in target_data_fields:
pos = file_id_to_pos.get(target.id, -1)
- positions.append(pos)
- names.append(target.name)
- if pos != i or (pos >= 0 and file_data_fields[pos].name != target.name):
- identity = False
- if identity:
- return None, None
- return positions, names
+ file_field = file_data_fields[pos] if pos >= 0 else None
+ plan.append((pos, file_field, target))
+ return plan
def _normalize_batch(self, record_batch: RecordBatch) -> RecordBatch:
"""Reorder/pad the physically-read batch onto the latest read target by
- field id, and relabel columns to the latest names. Missing ids become
- all-NULL columns; types are reconciled later by _align_batch_to_read_schema."""
- if self._normalize_positions is None:
+ field id, relabel columns to the latest names, and align nested ROW
+ sub-fields by id. Missing ids become typed all-NULL columns."""
+ if self._normalize_plan is None:
return record_batch
num_rows = record_batch.num_rows
arrays = []
- for pos in self._normalize_positions:
+ names = []
+ for pos, file_field, target_field in self._normalize_plan:
+ target_pa_type = PyarrowFieldParser.from_paimon_type(target_field.type)
if pos < 0:
- arrays.append(pa.nulls(num_rows))
+ arrays.append(pa.nulls(num_rows, type=target_pa_type))
else:
- arrays.append(record_batch.column(pos))
- return pa.RecordBatch.from_arrays(arrays, names=self._normalize_names)
+ arrays.append(self._align_array_by_id(
+ record_batch.column(pos), file_field.type, target_field.type))
+ names.append(target_field.name)
+ return pa.RecordBatch.from_arrays(arrays, names=names)
+
+ def _align_array_by_id(self, array, file_type, target_type):
+ """Return *array* converted to *target_type*, matching ROW sub-fields by
+ field id (reorder, pad missing with NULL, follow renames, cast changed
+ types) recursively, transparently through ARRAY/MAP wrappers."""
+ if isinstance(target_type, RowType) and isinstance(file_type, RowType):
+ n = len(array)
+ file_id_to_pos = {f.id: i for i, f in enumerate(file_type.fields)}
+ children = []
+ pa_fields = []
+ for tsub in target_type.fields:
+ p = file_id_to_pos.get(tsub.id, -1)
+ if p < 0:
+ child = pa.nulls(n, type=PyarrowFieldParser.from_paimon_type(tsub.type))
+ else:
+ child = self._align_array_by_id(
+ array.field(p), file_type.fields[p].type, tsub.type)
+ children.append(child)
+ pa_fields.append(pa.field(tsub.name, child.type, nullable=tsub.type.nullable))
+ # Preserve the struct's own null mask; child values under a null
+ # struct are irrelevant.
+ return pa.StructArray.from_arrays(
+ children, fields=pa_fields, mask=pc.is_null(array))
+ if isinstance(target_type, ArrayType) and isinstance(file_type, ArrayType):
+ aligned_values = self._align_array_by_id(
+ array.values, file_type.element, target_type.element)
+ return pa.ListArray.from_arrays(
+ array.offsets, aligned_values, mask=pc.is_null(array))
+ if isinstance(target_type, MapType) and isinstance(file_type, MapType):
+ aligned_items = self._align_array_by_id(
+ array.items, file_type.value, target_type.value)
+ # MapArray.from_arrays cannot carry a null mask (a null map would
+ # collapse to an empty one), so rebuild from buffers, reusing the
+ # original validity/offset buffers and only swapping the value child.
+ target_pa = PyarrowFieldParser.from_paimon_type(target_type)
+ entries = pa.StructArray.from_arrays(
+ [array.keys, aligned_items],
+ fields=[target_pa.key_field, target_pa.item_field])
+ return pa.Array.from_buffers(
+ target_pa, len(array), array.buffers()[:2], children=[entries])
+ # A constructed type changed to a character string: pyarrow cannot
+ # cast struct/list/map to utf8 directly, so render the engine's
+ # string form instead.
+ if (isinstance(file_type, (RowType, ArrayType, MapType))
Review Comment:
fixed
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [python] Support schema evolution of nested struct sub-fields [paimon]
Posted by "TheR1sing3un (via GitHub)" <gi...@apache.org>.
TheR1sing3un commented on code in PR #8187:
URL: https://github.com/apache/paimon/pull/8187#discussion_r3409069933
##########
paimon-python/pypaimon/read/split_read.py:
##########
@@ -627,6 +627,33 @@ def _genarate_deletion_file_readers(self):
class RawFileSplitRead(SplitRead):
+ def __init__(
+ self,
+ table,
+ predicate: Optional[Predicate],
+ read_type: List[DataField],
+ split: Split,
+ row_tracking_enabled: bool,
+ outer_extract_name_paths: Optional[List[List[str]]] = None,
+ outer_flat_read_type: Optional[List[DataField]] = None,
+ limit: Optional[int] = None):
+ # Nested-leaf projection is NOT pushed down by name: a leaf path is
+ # only valid against the latest schema, while each data file stores
+ # its own (possibly renamed / retyped) sub-fields. Instead the read
+ # widens to the full top-level columns, which the per-file field-id
+ # normalization aligns to the latest schema, and the requested leaf
+ # paths are extracted afterwards (``outer_extract_name_paths``).
+ super().__init__(
Review Comment:
fixed
##########
paimon-python/pypaimon/casting/data_type_casts.py:
##########
@@ -0,0 +1,189 @@
+# 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.
+
+"""Type-cast support rules used to validate ``update column type`` schema
+changes.
+
+The rules mirror the engine-wide cast specification so a type change accepted
+here is one the read path can also materialize: an *implicit* cast is a safe
+widening (e.g. INT -> BIGINT, any numeric -> DECIMAL/DOUBLE), while an
+*explicit* cast covers the broader, possibly lossy conversions a user opts into
+(e.g. DOUBLE -> INT truncation, anything -> STRING). Read-time execution then
+applies the conversion leniently.
+"""
+
+from pypaimon.schema.data_types import (ArrayType, AtomicType, DataTypeParser,
+ MapType, MultisetType, RowType,
+ VectorType)
+
+# ---- Type roots --------------------------------------------------------------
+
+CHAR = "CHAR"
+VARCHAR = "VARCHAR"
+BOOLEAN = "BOOLEAN"
+BINARY = "BINARY"
+VARBINARY = "VARBINARY"
+DECIMAL = "DECIMAL"
+TINYINT = "TINYINT"
+SMALLINT = "SMALLINT"
+INTEGER = "INTEGER"
+BIGINT = "BIGINT"
+FLOAT = "FLOAT"
+DOUBLE = "DOUBLE"
+DATE = "DATE"
+TIME = "TIME"
+TIMESTAMP = "TIMESTAMP"
+TIMESTAMP_LTZ = "TIMESTAMP_LTZ"
+ARRAY = "ARRAY"
+MAP = "MAP"
+MULTISET = "MULTISET"
+ROW = "ROW"
+VECTOR = "VECTOR"
+VARIANT = "VARIANT"
+BLOB = "BLOB"
+
+# ---- Families ----------------------------------------------------------------
+
+CHARACTER_STRING = {CHAR, VARCHAR}
+BINARY_STRING = {BINARY, VARBINARY}
+INTEGER_NUMERIC = {TINYINT, SMALLINT, INTEGER, BIGINT}
+NUMERIC = INTEGER_NUMERIC | {FLOAT, DOUBLE, DECIMAL}
+TIMESTAMP_FAMILY = {TIMESTAMP, TIMESTAMP_LTZ}
+TIME_FAMILY = {TIME}
+DATETIME = {DATE, TIME, TIMESTAMP, TIMESTAMP_LTZ}
+PREDEFINED = {
+ CHAR, VARCHAR, BOOLEAN, BINARY, VARBINARY, DECIMAL,
+ TINYINT, SMALLINT, INTEGER, BIGINT, FLOAT, DOUBLE,
+ DATE, TIME, TIMESTAMP, TIMESTAMP_LTZ,
+}
+CONSTRUCTED = {ARRAY, MAP, MULTISET, ROW, VECTOR}
+# Constructed types the read path can render as a character string
+# ('{v1, v2}' / '[e1, e2]' / '{k -> v}'). VECTOR and MULTISET have no string
+# rendering, so a type change from them to CHAR/VARCHAR is rejected here
+# rather than failing when an old file is read.
+STRING_RENDERABLE_CONSTRUCTED = {ARRAY, MAP, ROW}
+
+
+def _root(data_type) -> str:
+ if isinstance(data_type, RowType):
+ return ROW
+ if isinstance(data_type, ArrayType):
+ return ARRAY
+ if isinstance(data_type, MapType):
+ return MAP
+ if isinstance(data_type, MultisetType):
+ return MULTISET
+ if isinstance(data_type, VectorType):
+ return VECTOR
+ if isinstance(data_type, AtomicType):
+ t = data_type.type.upper()
+ if t.startswith("DECIMAL") or t.startswith("NUMERIC") or t.startswith("DEC"):
+ return DECIMAL
+ if t in ("INT", "INTEGER"):
+ return INTEGER
+ if t in (TINYINT, SMALLINT, BIGINT, FLOAT, DOUBLE, BOOLEAN, DATE):
+ return t
+ if t == "STRING" or t.startswith("VARCHAR"):
+ return VARCHAR
+ if t.startswith("CHAR"):
+ return CHAR
+ if t == "BYTES" or t.startswith("VARBINARY"):
+ return VARBINARY
+ if t.startswith("BINARY"):
+ return BINARY
+ if t == "BLOB":
+ return BLOB
+ if t.startswith("TIMESTAMP_LTZ"):
+ return TIMESTAMP_LTZ
+ if t.startswith("TIMESTAMP"):
+ return TIMESTAMP
+ if t.startswith("TIME"):
+ return TIME
+ if t == "VARIANT":
+ return VARIANT
+ return None
+
+
+def _build_rules():
+ implicit = {}
+ explicit = {}
+ # Identity cast for every root.
+ for root in (PREDEFINED | CONSTRUCTED | {VARIANT, BLOB}):
+ implicit[root] = {root}
+ explicit[root] = set()
+
+ def rule(target, implicit_from=None, explicit_from=None):
+ implicit[target] |= set(implicit_from or set())
+ explicit[target] |= set(explicit_from or set())
+
+ rule(CHAR, {CHAR}, PREDEFINED | STRING_RENDERABLE_CONSTRUCTED)
+ rule(VARCHAR, CHARACTER_STRING, PREDEFINED | STRING_RENDERABLE_CONSTRUCTED)
+ rule(BOOLEAN, {BOOLEAN}, CHARACTER_STRING | INTEGER_NUMERIC)
+ rule(BINARY, {BINARY}, CHARACTER_STRING | {VARBINARY})
+ rule(VARBINARY, BINARY_STRING, CHARACTER_STRING | {BINARY})
+ rule(DECIMAL, NUMERIC, CHARACTER_STRING | {BOOLEAN, TIMESTAMP, TIMESTAMP_LTZ})
Review Comment:
fixed
##########
paimon-python/pypaimon/schema/schema_manager.py:
##########
@@ -55,49 +174,70 @@ def _get_rename_mappings(changes: List[SchemaChange]) -> dict:
def _handle_update_column_comment(
change: UpdateColumnComment, new_fields: List[DataField]
):
- field_name = change.field_names[-1]
- field_index = _find_field_index(new_fields, field_name)
- if field_index is None:
- raise ColumnNotExistException(field_name)
- field = new_fields[field_index]
- new_fields[field_index] = DataField(
- field.id, field.name, field.type, change.new_comment, field.default_value
- )
+ def update_func(field: DataField, depth: int) -> DataField:
+ return DataField(
+ field.id, field.name, field.type, change.new_comment, field.default_value
+ )
+ _update_nested_column(new_fields, change.field_names, update_func)
+
+
+def _assert_nullability_change(old_nullability: bool, new_nullability: bool,
+ field_name: str, disable_null_to_not_null: bool):
+ if disable_null_to_not_null and old_nullability and not new_nullability:
+ raise ValueError(
+ "Cannot update column type from nullable to non nullable for {}. "
+ "You can set table configuration option "
+ "'alter-column-null-to-not-null.disabled' = 'false' "
+ "to allow converting null columns to not null".format(field_name)
+ )
def _handle_update_column_nullability(
- change: UpdateColumnNullability, new_fields: List[DataField]
+ change: UpdateColumnNullability, new_fields: List[DataField],
+ disable_null_to_not_null: bool
):
- field_name = change.field_names[-1]
- field_index = _find_field_index(new_fields, field_name)
- if field_index is None:
- raise ColumnNotExistException(field_name)
- field = new_fields[field_index]
from pypaimon.schema.data_types import DataTypeParser
- field_type_dict = field.type.to_dict()
- new_type = DataTypeParser.parse_data_type(field_type_dict)
- new_type.nullable = change.new_nullability
- new_fields[field_index] = DataField(
- field.id, field.name, new_type, field.description, field.default_value
- )
+ field_names = change.field_names
+ max_depth = len(field_names)
+
+ def update_func(field: DataField, depth: int) -> DataField:
+ source_root = _get_root_type(field.type, depth, max_depth)
+ _assert_nullability_change(
+ source_root.nullable, change.new_nullability,
+ '.'.join(field_names), disable_null_to_not_null)
+ new_root = DataTypeParser.parse_data_type(source_root.to_dict())
+ new_root.nullable = change.new_nullability
+ new_type = _get_array_map_type_with_target_type_root(
+ field.type, new_root, depth, max_depth)
+ return DataField(
+ field.id, field.name, new_type, field.description, field.default_value
+ )
+ _update_nested_column(new_fields, field_names, update_func)
def _handle_update_column_type(
change: UpdateColumnType, new_fields: List[DataField]
):
- field_name = change.field_names[-1]
- field_index = _find_field_index(new_fields, field_name)
- if field_index is None:
- raise ColumnNotExistException(field_name)
- field = new_fields[field_index]
from pypaimon.schema.data_types import DataTypeParser
- new_type_dict = change.new_data_type.to_dict()
- new_type = DataTypeParser.parse_data_type(new_type_dict)
- if change.keep_nullability:
- new_type.nullable = field.type.nullable
- new_fields[field_index] = DataField(
- field.id, field.name, new_type, field.description, field.default_value
- )
+ field_names = change.field_names
+ max_depth = len(field_names)
+
+ def update_func(field: DataField, depth: int) -> DataField:
+ source_root = _get_root_type(field.type, depth, max_depth)
+ target_root = DataTypeParser.parse_data_type(change.new_data_type.to_dict())
+ if change.keep_nullability:
+ target_root.nullable = source_root.nullable
+ if not supports_cast(source_root, target_root):
Review Comment:
fixed
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [python] Support schema evolution of nested struct sub-fields [paimon]
Posted by "TheR1sing3un (via GitHub)" <gi...@apache.org>.
TheR1sing3un commented on code in PR #8187:
URL: https://github.com/apache/paimon/pull/8187#discussion_r3386423297
##########
paimon-python/pypaimon/read/reader/data_file_batch_reader.py:
##########
@@ -57,55 +59,99 @@ def __init__(self, format_reader: RecordBatchReader, index_mapping: List[int], p
self.file_io = file_io
# Per-file field-id normalization: map the physically-read columns
# (the file's own field order/names) onto the latest read target by
- # field id, padding missing ids with NULL. ``None`` when there is no
- # evolution to reconcile (identity) -- the common path stays zero-copy.
- self._normalize_positions, self._normalize_names = \
- self._build_normalize_plan(file_data_fields, target_data_fields)
+ # field id, padding missing ids with NULL and recursing into nested
+ # ROW / ARRAY<ROW> / MAP<.,ROW> sub-fields the same way. ``None`` when
+ # there is no evolution to reconcile -- the common path stays zero-copy.
+ self._normalize_plan = self._build_normalize_plan(file_data_fields, target_data_fields)
Review Comment:
> The new nested field-id normalization is skipped for dotted nested projections. SplitRead.file_reader_supplier passes file_data_fields=None and target_data_fields=None whenever has_nested is true, so with_projection(['mv.renamed_leaf']) still reads by the new physical name from old files. I reproduced rename mv.s -> ss followed by projection ['id', 'mv.ss']: the old row returned mv_ss=None instead of 'a'. A nested type change is worse: projecting the evolved leaf kept old batches as int32 and new batches as int64, causing pyarrow.lib.ArrowInvalid during concatenation.
Fixed in b4d46ecc3.
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [python] Support schema evolution of nested struct sub-fields [paimon]
Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #8187:
URL: https://github.com/apache/paimon/pull/8187#discussion_r3393444513
##########
paimon-python/pypaimon/schema/schema_manager.py:
##########
@@ -44,6 +46,108 @@ def _find_field_index(fields: List[DataField], field_name: str) -> Optional[int]
return None
+def _extract_row_data_fields(data_type, out_fields: List[DataField]) -> int:
+ """Collect the immediate sub-fields reachable from *data_type* into
+ *out_fields* and return the path depth consumed. A ROW contributes its
+ fields (depth 1); an ARRAY/MAP is transparent and descends into its
+ element/value (consuming the ``element``/``value`` path token); anything
+ else contributes nothing (depth 1)."""
+ if isinstance(data_type, RowType):
+ out_fields.extend(data_type.fields)
+ return 1
+ if isinstance(data_type, ArrayType):
+ return _extract_row_data_fields(data_type.element, out_fields) + 1
+ if isinstance(data_type, MapType):
+ return _extract_row_data_fields(data_type.value, out_fields) + 1
+ return 1
+
+
+def _wrap_new_row_type(data_type, nested_fields: List[DataField]):
+ """Rebuild *data_type* substituting *nested_fields* at its innermost ROW,
+ preserving any ARRAY/MAP wrappers."""
+ if isinstance(data_type, RowType):
+ return RowType(data_type.nullable, nested_fields)
+ if isinstance(data_type, ArrayType):
+ return ArrayType(data_type.nullable, _wrap_new_row_type(data_type.element, nested_fields))
+ if isinstance(data_type, MapType):
+ return MapType(
+ data_type.nullable, data_type.key,
+ _wrap_new_row_type(data_type.value, nested_fields))
+ return data_type
+
+
+def _get_root_type(data_type, curr_depth: int, max_depth: int):
+ """Return the type sitting at ``max_depth`` when walking ARRAY/MAP wrappers
+ from *data_type* (e.g. the INT in ARRAY<MAP<STRING, ARRAY<INT>>>)."""
+ if curr_depth == max_depth - 1:
+ return data_type
+ if isinstance(data_type, ArrayType):
+ return _get_root_type(data_type.element, curr_depth + 1, max_depth)
+ if isinstance(data_type, MapType):
+ return _get_root_type(data_type.value, curr_depth + 1, max_depth)
+ return data_type
+
+
+def _get_array_map_type_with_target_type_root(source, target, curr_depth: int, max_depth: int):
+ """Rebuild *source* with *target* substituted at ``max_depth``, keeping the
+ ARRAY/MAP wrappers around it intact."""
+ if curr_depth == max_depth - 1:
+ return target
+ if isinstance(source, ArrayType):
+ return ArrayType(
+ source.nullable,
+ _get_array_map_type_with_target_type_root(
+ source.element, target, curr_depth + 1, max_depth))
+ if isinstance(source, MapType):
+ return MapType(
+ source.nullable, source.key,
+ _get_array_map_type_with_target_type_root(
+ source.value, target, curr_depth + 1, max_depth))
+ return target
+
+
+def _update_intermediate_column(new_fields, previous_fields, depth, prev_depth,
+ field_names, update_last_fn):
+ """Walk *field_names* into nested ROW (transparently through ARRAY/MAP),
+ then run *update_last_fn(depth, fields, name)* on the field list that
+ directly contains the final path element, rebuilding parent types upward."""
+ if depth == len(field_names) - 1:
+ update_last_fn(depth, new_fields, field_names[depth])
+ return
+ if depth >= len(field_names):
+ # Path descended through ARRAY/MAP past the last ROW; operate on the
+ # field that owns the wrapper at the previous depth.
+ update_last_fn(prev_depth, previous_fields, field_names[prev_depth])
+ return
+ for i, field in enumerate(new_fields):
+ if field.name != field_names[depth]:
+ continue
+ nested_fields: List[DataField] = []
+ new_depth = depth + _extract_row_data_fields(field.type, nested_fields)
Review Comment:
This path walker does not validate the wrapper token it consumes for ARRAY/MAP. For example, on `arr ARRAY<ROW<a BIGINT, b STRING>>`, `SchemaChange.add_column(["arr", "wrong", "c"], INT)` is accepted and adds `c` to the array element exactly like `["arr", "element", "c"]`; the same applies to map values. That makes invalid column paths silently mutate the schema. Please require the consumed token to be `element` for arrays and `value` for maps (or otherwise reject unknown wrapper steps) before descending.
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [python] Support schema evolution of nested struct sub-fields [paimon]
Posted by "TheR1sing3un (via GitHub)" <gi...@apache.org>.
TheR1sing3un commented on code in PR #8187:
URL: https://github.com/apache/paimon/pull/8187#discussion_r3409397739
##########
paimon-python/pypaimon/casting/data_type_casts.py:
##########
@@ -0,0 +1,252 @@
+# 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.
+
+"""Type-cast support rules used to validate ``update column type`` schema
+changes.
+
+The rules mirror the engine-wide cast specification so a type change accepted
+here is one the read path can also materialize: an *implicit* cast is a safe
+widening (e.g. INT -> BIGINT, any numeric -> DECIMAL/DOUBLE), while an
+*explicit* cast covers the broader, possibly lossy conversions a user opts into
+(e.g. DOUBLE -> INT truncation, anything -> STRING). Read-time execution then
+applies the conversion leniently.
+"""
+
+import pyarrow as pa
+
+from pypaimon.schema.data_types import (ArrayType, AtomicType, DataTypeParser,
+ MapType, MultisetType,
+ PyarrowFieldParser, RowType,
+ VectorType)
+
+# ---- Type roots --------------------------------------------------------------
+
+CHAR = "CHAR"
+VARCHAR = "VARCHAR"
+BOOLEAN = "BOOLEAN"
+BINARY = "BINARY"
+VARBINARY = "VARBINARY"
+DECIMAL = "DECIMAL"
+TINYINT = "TINYINT"
+SMALLINT = "SMALLINT"
+INTEGER = "INTEGER"
+BIGINT = "BIGINT"
+FLOAT = "FLOAT"
+DOUBLE = "DOUBLE"
+DATE = "DATE"
+TIME = "TIME"
+TIMESTAMP = "TIMESTAMP"
+TIMESTAMP_LTZ = "TIMESTAMP_LTZ"
+ARRAY = "ARRAY"
+MAP = "MAP"
+MULTISET = "MULTISET"
+ROW = "ROW"
+VECTOR = "VECTOR"
+VARIANT = "VARIANT"
+BLOB = "BLOB"
+
+# ---- Families ----------------------------------------------------------------
+
+CHARACTER_STRING = {CHAR, VARCHAR}
+BINARY_STRING = {BINARY, VARBINARY}
+INTEGER_NUMERIC = {TINYINT, SMALLINT, INTEGER, BIGINT}
+NUMERIC = INTEGER_NUMERIC | {FLOAT, DOUBLE, DECIMAL}
+TIMESTAMP_FAMILY = {TIMESTAMP, TIMESTAMP_LTZ}
+TIME_FAMILY = {TIME}
+DATETIME = {DATE, TIME, TIMESTAMP, TIMESTAMP_LTZ}
+PREDEFINED = {
+ CHAR, VARCHAR, BOOLEAN, BINARY, VARBINARY, DECIMAL,
+ TINYINT, SMALLINT, INTEGER, BIGINT, FLOAT, DOUBLE,
+ DATE, TIME, TIMESTAMP, TIMESTAMP_LTZ,
+}
+CONSTRUCTED = {ARRAY, MAP, MULTISET, ROW, VECTOR}
+# Constructed types the read path can render as a character string
+# ('{v1, v2}' / '[e1, e2]' / '{k -> v}'). VECTOR and MULTISET have no string
+# rendering, so a type change from them to CHAR/VARCHAR is rejected here
+# rather than failing when an old file is read.
+STRING_RENDERABLE_CONSTRUCTED = {ARRAY, MAP, ROW}
+
+
+def _root(data_type) -> str:
+ if isinstance(data_type, RowType):
+ return ROW
+ if isinstance(data_type, ArrayType):
+ return ARRAY
+ if isinstance(data_type, MapType):
+ return MAP
+ if isinstance(data_type, MultisetType):
+ return MULTISET
+ if isinstance(data_type, VectorType):
+ return VECTOR
+ if isinstance(data_type, AtomicType):
+ t = data_type.type.upper()
+ if t.startswith("DECIMAL") or t.startswith("NUMERIC") or t.startswith("DEC"):
+ return DECIMAL
+ if t in ("INT", "INTEGER"):
+ return INTEGER
+ if t in (TINYINT, SMALLINT, BIGINT, FLOAT, DOUBLE, BOOLEAN, DATE):
+ return t
+ if t == "STRING" or t.startswith("VARCHAR"):
+ return VARCHAR
+ if t.startswith("CHAR"):
+ return CHAR
+ if t == "BYTES" or t.startswith("VARBINARY"):
+ return VARBINARY
+ if t.startswith("BINARY"):
+ return BINARY
+ if t == "BLOB":
+ return BLOB
+ if t.startswith("TIMESTAMP_LTZ"):
+ return TIMESTAMP_LTZ
+ if t.startswith("TIMESTAMP"):
+ return TIMESTAMP
+ if t.startswith("TIME"):
+ return TIME
+ if t == "VARIANT":
+ return VARIANT
+ return None
+
+
+def _build_rules():
+ implicit = {}
+ explicit = {}
+ # Identity cast for every root.
+ for root in (PREDEFINED | CONSTRUCTED | {VARIANT, BLOB}):
+ implicit[root] = {root}
+ explicit[root] = set()
+
+ def rule(target, implicit_from=None, explicit_from=None):
+ implicit[target] |= set(implicit_from or set())
+ explicit[target] |= set(explicit_from or set())
+
+ rule(CHAR, {CHAR}, PREDEFINED | STRING_RENDERABLE_CONSTRUCTED)
+ rule(VARCHAR, CHARACTER_STRING, PREDEFINED | STRING_RENDERABLE_CONSTRUCTED)
+ rule(BOOLEAN, {BOOLEAN}, CHARACTER_STRING | INTEGER_NUMERIC)
+ rule(BINARY, {BINARY}, CHARACTER_STRING | {VARBINARY})
+ rule(VARBINARY, BINARY_STRING, CHARACTER_STRING | {BINARY})
+ rule(DECIMAL, NUMERIC, CHARACTER_STRING | {BOOLEAN, TIMESTAMP, TIMESTAMP_LTZ})
+ int_explicit = NUMERIC | CHARACTER_STRING | {BOOLEAN, TIMESTAMP, TIMESTAMP_LTZ}
+ rule(TINYINT, {TINYINT}, int_explicit)
+ rule(SMALLINT, {TINYINT, SMALLINT}, int_explicit)
+ rule(INTEGER, {TINYINT, SMALLINT, INTEGER}, int_explicit)
+ rule(BIGINT, {TINYINT, SMALLINT, INTEGER, BIGINT}, int_explicit)
+ rule(FLOAT, {TINYINT, SMALLINT, INTEGER, BIGINT, FLOAT, DECIMAL}, int_explicit)
+ rule(DOUBLE, NUMERIC, CHARACTER_STRING | {BOOLEAN, TIMESTAMP, TIMESTAMP_LTZ})
+ rule(DATE, {DATE, TIMESTAMP}, TIMESTAMP_FAMILY | CHARACTER_STRING)
+ rule(TIME, {TIME, TIMESTAMP}, TIME_FAMILY | TIMESTAMP_FAMILY | CHARACTER_STRING)
+ rule(TIMESTAMP, {TIMESTAMP, TIMESTAMP_LTZ}, DATETIME | CHARACTER_STRING | NUMERIC)
+ rule(TIMESTAMP_LTZ, {TIMESTAMP_LTZ, TIMESTAMP}, DATETIME | CHARACTER_STRING | NUMERIC)
+ return implicit, explicit
+
+
+_IMPLICIT_RULES, _EXPLICIT_RULES = _build_rules()
+
+
+def supports_cast(source_type, target_type, allow_explicit: bool = True) -> bool:
+ """Whether ``source_type`` can be cast to ``target_type`` for a column type
+ change. ``allow_explicit`` permits the broader (possibly lossy) conversions
+ in addition to the safe widening ones."""
+ source_root = _root(source_type)
+ target_root = _root(target_type)
+ if source_root is None or target_root is None:
+ return False
+ # A NOT NULL target cannot accept a nullable source unless explicitly allowed.
+ if source_type.nullable and not target_type.nullable and not allow_explicit:
+ return False
+ if source_root == target_root:
+ if source_root in CONSTRUCTED:
+ # A constructed type is only castable to an (ignoring outer
+ # nullability) identical constructed type. Reshaping is done
+ # through sub-field / 'element' / 'value' paths instead: a whole
+ # ROW replacement would carry caller-supplied nested field ids
+ # that corrupt the id model, and there is no runtime conversion
+ # between differently-shaped constructed values.
+ return _equals_ignore_nullable(source_type, target_type)
+ return True
+ if source_root in _IMPLICIT_RULES.get(target_root, set()):
+ return True
+ if allow_explicit and source_root in _EXPLICIT_RULES.get(target_root, set()):
+ return True
+ return False
+
+
+def _equals_ignore_nullable(source_type, target_type) -> bool:
+ source_copy = DataTypeParser.parse_data_type(source_type.to_dict())
+ target_copy = DataTypeParser.parse_data_type(target_type.to_dict())
+ source_copy.nullable = True
+ target_copy.nullable = True
+ return source_copy == target_copy
+
+
+# Caches the PyArrow cast-kernel probe per (source, target) pyarrow type so the
+# alter-time check stays cheap. Keyed by the pyarrow type strings.
+_EXECUTABLE_CAST_CACHE = {}
+
+
+def can_execute_cast(source_type, target_type) -> bool:
+ """Whether the Python read path can actually *materialize* a stored
+ ``source_type`` value as ``target_type`` when reading a file written before
+ the column type change.
+
+ ``supports_cast`` only encodes the *logical* cast specification (mirroring
+ Java ``DataTypeCasts``). This is the executable-cast counterpart of Java's
+ ``CastExecutors.resolve(...) != null`` guard: some logically-valid casts
+ (e.g. ``TIMESTAMP -> DECIMAL``, ``BOOLEAN -> DECIMAL``, ``TIME ->
+ TIMESTAMP``) have no PyArrow cast kernel, so without this check the alter
+ succeeds and the read later fails with ``ArrowNotImplementedError``.
+ """
+ source_root = _root(source_type)
+ target_root = _root(target_type)
+ if source_root is None or target_root is None:
+ return False
+ # Same root: identity, or a same-shape constructed type whose value is
+ # rebuilt by the read path's field-id alignment rather than a value cast.
+ if source_root == target_root:
+ return True
+ # Constructed -> character string is rendered by the read path's custom
+ # ``_constructed_to_string_array`` (see DataFileBatchReader), not a cast.
+ if (source_root in STRING_RENDERABLE_CONSTRUCTED
+ and target_root in CHARACTER_STRING):
+ return True
+ # Any other conversion touching a constructed type has no runtime cast.
+ if source_root in CONSTRUCTED or target_root in CONSTRUCTED:
+ return False
+ # Leaf-to-leaf: defer to PyArrow's cast-kernel availability, which is the
+ # read path's actual cast executor (``array.cast(target, safe=False)``).
+ return _pyarrow_cast_supported(source_type, target_type)
+
+
+def _pyarrow_cast_supported(source_type, target_type) -> bool:
+ source_pa = PyarrowFieldParser.from_paimon_type(source_type)
+ target_pa = PyarrowFieldParser.from_paimon_type(target_type)
+ if source_pa == target_pa:
+ return True
+ cache_key = (str(source_pa), str(target_pa))
+ cached = _EXECUTABLE_CAST_CACHE.get(cache_key)
+ if cached is not None:
+ return cached
+ # An empty-array cast exercises only kernel resolution (not per-value
+ # conversion), so it reports whether PyArrow has a cast kernel for the pair
+ # without depending on any data. ``safe=False`` matches the read path.
+ try:
+ pa.array([], type=source_pa).cast(target_pa, safe=False)
Review Comment:
fixed
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [python] Support schema evolution of nested struct sub-fields [paimon]
Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #8187:
URL: https://github.com/apache/paimon/pull/8187#discussion_r3409517470
##########
paimon-python/pypaimon/schema/schema_manager.py:
##########
@@ -55,49 +174,87 @@ def _get_rename_mappings(changes: List[SchemaChange]) -> dict:
def _handle_update_column_comment(
change: UpdateColumnComment, new_fields: List[DataField]
):
- field_name = change.field_names[-1]
- field_index = _find_field_index(new_fields, field_name)
- if field_index is None:
- raise ColumnNotExistException(field_name)
- field = new_fields[field_index]
- new_fields[field_index] = DataField(
- field.id, field.name, field.type, change.new_comment, field.default_value
- )
+ def update_func(field: DataField, depth: int) -> DataField:
+ return DataField(
+ field.id, field.name, field.type, change.new_comment, field.default_value
+ )
+ _update_nested_column(new_fields, change.field_names, update_func)
+
+
+def _assert_nullability_change(old_nullability: bool, new_nullability: bool,
+ field_name: str, disable_null_to_not_null: bool):
+ if disable_null_to_not_null and old_nullability and not new_nullability:
+ raise ValueError(
+ "Cannot update column type from nullable to non nullable for {}. "
+ "You can set table configuration option "
+ "'alter-column-null-to-not-null.disabled' = 'false' "
+ "to allow converting null columns to not null".format(field_name)
+ )
def _handle_update_column_nullability(
- change: UpdateColumnNullability, new_fields: List[DataField]
+ change: UpdateColumnNullability, new_fields: List[DataField],
+ disable_null_to_not_null: bool
):
- field_name = change.field_names[-1]
- field_index = _find_field_index(new_fields, field_name)
- if field_index is None:
- raise ColumnNotExistException(field_name)
- field = new_fields[field_index]
from pypaimon.schema.data_types import DataTypeParser
- field_type_dict = field.type.to_dict()
- new_type = DataTypeParser.parse_data_type(field_type_dict)
- new_type.nullable = change.new_nullability
- new_fields[field_index] = DataField(
- field.id, field.name, new_type, field.description, field.default_value
- )
+ field_names = change.field_names
+ max_depth = len(field_names)
+
+ def update_func(field: DataField, depth: int) -> DataField:
+ source_root = _get_root_type(field.type, depth, max_depth)
+ _assert_nullability_change(
+ source_root.nullable, change.new_nullability,
+ '.'.join(field_names), disable_null_to_not_null)
+ new_root = DataTypeParser.parse_data_type(source_root.to_dict())
+ new_root.nullable = change.new_nullability
+ new_type = _get_array_map_type_with_target_type_root(
+ field.type, new_root, depth, max_depth)
+ return DataField(
+ field.id, field.name, new_type, field.description, field.default_value
+ )
+ _update_nested_column(new_fields, field_names, update_func)
def _handle_update_column_type(
- change: UpdateColumnType, new_fields: List[DataField]
+ change: UpdateColumnType, new_fields: List[DataField],
+ disable_null_to_not_null: bool
):
- field_name = change.field_names[-1]
- field_index = _find_field_index(new_fields, field_name)
- if field_index is None:
- raise ColumnNotExistException(field_name)
- field = new_fields[field_index]
from pypaimon.schema.data_types import DataTypeParser
- new_type_dict = change.new_data_type.to_dict()
- new_type = DataTypeParser.parse_data_type(new_type_dict)
- if change.keep_nullability:
- new_type.nullable = field.type.nullable
- new_fields[field_index] = DataField(
- field.id, field.name, new_type, field.description, field.default_value
- )
+ field_names = change.field_names
+ max_depth = len(field_names)
+
+ def update_func(field: DataField, depth: int) -> DataField:
+ source_root = _get_root_type(field.type, depth, max_depth)
+ target_root = DataTypeParser.parse_data_type(change.new_data_type.to_dict())
Review Comment:
This reparses `change.new_data_type.to_dict()` directly, but parameterized atomic types keep the `NOT NULL` suffix inside `AtomicType.type`. For example, `SchemaChange.update_column_type("v", AtomicType("DECIMAL(12, 2)", nullable=False))` on an existing non-null `INT` column is a valid widening, but `to_dict()` produces `DECIMAL(12, 2) NOT NULL`, the parser stores that whole string as the atomic type, and the new `can_execute_cast` check now fails during alter with `Unsupported data type: DECIMAL(12, 2) NOT NULL NOT NULL`. Could we normalize the parsed target so nullability is stored only in `nullable` (or fix the atomic parser to strip the suffix for parameterized types) before running the executable-cast check?
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [python] Support schema evolution of nested struct sub-fields [paimon]
Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #8187:
URL: https://github.com/apache/paimon/pull/8187#discussion_r3409022049
##########
paimon-python/pypaimon/schema/schema_manager.py:
##########
@@ -55,49 +174,70 @@ def _get_rename_mappings(changes: List[SchemaChange]) -> dict:
def _handle_update_column_comment(
change: UpdateColumnComment, new_fields: List[DataField]
):
- field_name = change.field_names[-1]
- field_index = _find_field_index(new_fields, field_name)
- if field_index is None:
- raise ColumnNotExistException(field_name)
- field = new_fields[field_index]
- new_fields[field_index] = DataField(
- field.id, field.name, field.type, change.new_comment, field.default_value
- )
+ def update_func(field: DataField, depth: int) -> DataField:
+ return DataField(
+ field.id, field.name, field.type, change.new_comment, field.default_value
+ )
+ _update_nested_column(new_fields, change.field_names, update_func)
+
+
+def _assert_nullability_change(old_nullability: bool, new_nullability: bool,
+ field_name: str, disable_null_to_not_null: bool):
+ if disable_null_to_not_null and old_nullability and not new_nullability:
+ raise ValueError(
+ "Cannot update column type from nullable to non nullable for {}. "
+ "You can set table configuration option "
+ "'alter-column-null-to-not-null.disabled' = 'false' "
+ "to allow converting null columns to not null".format(field_name)
+ )
def _handle_update_column_nullability(
- change: UpdateColumnNullability, new_fields: List[DataField]
+ change: UpdateColumnNullability, new_fields: List[DataField],
+ disable_null_to_not_null: bool
):
- field_name = change.field_names[-1]
- field_index = _find_field_index(new_fields, field_name)
- if field_index is None:
- raise ColumnNotExistException(field_name)
- field = new_fields[field_index]
from pypaimon.schema.data_types import DataTypeParser
- field_type_dict = field.type.to_dict()
- new_type = DataTypeParser.parse_data_type(field_type_dict)
- new_type.nullable = change.new_nullability
- new_fields[field_index] = DataField(
- field.id, field.name, new_type, field.description, field.default_value
- )
+ field_names = change.field_names
+ max_depth = len(field_names)
+
+ def update_func(field: DataField, depth: int) -> DataField:
+ source_root = _get_root_type(field.type, depth, max_depth)
+ _assert_nullability_change(
+ source_root.nullable, change.new_nullability,
+ '.'.join(field_names), disable_null_to_not_null)
+ new_root = DataTypeParser.parse_data_type(source_root.to_dict())
+ new_root.nullable = change.new_nullability
+ new_type = _get_array_map_type_with_target_type_root(
+ field.type, new_root, depth, max_depth)
+ return DataField(
+ field.id, field.name, new_type, field.description, field.default_value
+ )
+ _update_nested_column(new_fields, field_names, update_func)
def _handle_update_column_type(
change: UpdateColumnType, new_fields: List[DataField]
):
- field_name = change.field_names[-1]
- field_index = _find_field_index(new_fields, field_name)
- if field_index is None:
- raise ColumnNotExistException(field_name)
- field = new_fields[field_index]
from pypaimon.schema.data_types import DataTypeParser
- new_type_dict = change.new_data_type.to_dict()
- new_type = DataTypeParser.parse_data_type(new_type_dict)
- if change.keep_nullability:
- new_type.nullable = field.type.nullable
- new_fields[field_index] = DataField(
- field.id, field.name, new_type, field.description, field.default_value
- )
+ field_names = change.field_names
+ max_depth = len(field_names)
+
+ def update_func(field: DataField, depth: int) -> DataField:
+ source_root = _get_root_type(field.type, depth, max_depth)
+ target_root = DataTypeParser.parse_data_type(change.new_data_type.to_dict())
+ if change.keep_nullability:
+ target_root.nullable = source_root.nullable
+ if not supports_cast(source_root, target_root):
Review Comment:
This path still bypasses the new null-to-not-null guard when `update_column_type` receives a non-nullable target type. For example, `SchemaChange.update_column_type('v', AtomicType('BIGINT', nullable=False))` succeeds with the default table options and changes a nullable column to `BIGINT NOT NULL`, while Java `SchemaManager` rejects the same transition unless `alter-column-null-to-not-null.disabled=false`. Could we call `_assert_nullability_change(...)` here when `keep_nullability` is false, and add a regression test for `update_column_type(... NOT NULL)`?
##########
paimon-python/pypaimon/read/split_read.py:
##########
@@ -627,6 +627,33 @@ def _genarate_deletion_file_readers(self):
class RawFileSplitRead(SplitRead):
+ def __init__(
+ self,
+ table,
+ predicate: Optional[Predicate],
+ read_type: List[DataField],
+ split: Split,
+ row_tracking_enabled: bool,
+ outer_extract_name_paths: Optional[List[List[str]]] = None,
+ outer_flat_read_type: Optional[List[DataField]] = None,
+ limit: Optional[int] = None):
+ # Nested-leaf projection is NOT pushed down by name: a leaf path is
+ # only valid against the latest schema, while each data file stores
+ # its own (possibly renamed / retyped) sub-fields. Instead the read
+ # widens to the full top-level columns, which the per-file field-id
+ # normalization aligns to the latest schema, and the requested leaf
+ # paths are extracted afterwards (``outer_extract_name_paths``).
+ super().__init__(
Review Comment:
Widening nested projection to the top-level field changes `read_type` from e.g. `['id', 'mv_v']` to `['id', 'mv']`, so predicates built against the projected leaf are considered outside the read fields and get silently dropped. I reproduced `with_projection(['id', 'mv.v']).with_filter(mv_v > 15)` returning both `mv.v = 10` and `20` on append-only and PK raw-convertible reads. Could the predicate be applied after `NestedLeafBatchReader` / outer projection, or rewritten to the widened nested path instead of being dropped?
##########
paimon-python/pypaimon/casting/data_type_casts.py:
##########
@@ -0,0 +1,189 @@
+# 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.
+
+"""Type-cast support rules used to validate ``update column type`` schema
+changes.
+
+The rules mirror the engine-wide cast specification so a type change accepted
+here is one the read path can also materialize: an *implicit* cast is a safe
+widening (e.g. INT -> BIGINT, any numeric -> DECIMAL/DOUBLE), while an
+*explicit* cast covers the broader, possibly lossy conversions a user opts into
+(e.g. DOUBLE -> INT truncation, anything -> STRING). Read-time execution then
+applies the conversion leniently.
+"""
+
+from pypaimon.schema.data_types import (ArrayType, AtomicType, DataTypeParser,
+ MapType, MultisetType, RowType,
+ VectorType)
+
+# ---- Type roots --------------------------------------------------------------
+
+CHAR = "CHAR"
+VARCHAR = "VARCHAR"
+BOOLEAN = "BOOLEAN"
+BINARY = "BINARY"
+VARBINARY = "VARBINARY"
+DECIMAL = "DECIMAL"
+TINYINT = "TINYINT"
+SMALLINT = "SMALLINT"
+INTEGER = "INTEGER"
+BIGINT = "BIGINT"
+FLOAT = "FLOAT"
+DOUBLE = "DOUBLE"
+DATE = "DATE"
+TIME = "TIME"
+TIMESTAMP = "TIMESTAMP"
+TIMESTAMP_LTZ = "TIMESTAMP_LTZ"
+ARRAY = "ARRAY"
+MAP = "MAP"
+MULTISET = "MULTISET"
+ROW = "ROW"
+VECTOR = "VECTOR"
+VARIANT = "VARIANT"
+BLOB = "BLOB"
+
+# ---- Families ----------------------------------------------------------------
+
+CHARACTER_STRING = {CHAR, VARCHAR}
+BINARY_STRING = {BINARY, VARBINARY}
+INTEGER_NUMERIC = {TINYINT, SMALLINT, INTEGER, BIGINT}
+NUMERIC = INTEGER_NUMERIC | {FLOAT, DOUBLE, DECIMAL}
+TIMESTAMP_FAMILY = {TIMESTAMP, TIMESTAMP_LTZ}
+TIME_FAMILY = {TIME}
+DATETIME = {DATE, TIME, TIMESTAMP, TIMESTAMP_LTZ}
+PREDEFINED = {
+ CHAR, VARCHAR, BOOLEAN, BINARY, VARBINARY, DECIMAL,
+ TINYINT, SMALLINT, INTEGER, BIGINT, FLOAT, DOUBLE,
+ DATE, TIME, TIMESTAMP, TIMESTAMP_LTZ,
+}
+CONSTRUCTED = {ARRAY, MAP, MULTISET, ROW, VECTOR}
+# Constructed types the read path can render as a character string
+# ('{v1, v2}' / '[e1, e2]' / '{k -> v}'). VECTOR and MULTISET have no string
+# rendering, so a type change from them to CHAR/VARCHAR is rejected here
+# rather than failing when an old file is read.
+STRING_RENDERABLE_CONSTRUCTED = {ARRAY, MAP, ROW}
+
+
+def _root(data_type) -> str:
+ if isinstance(data_type, RowType):
+ return ROW
+ if isinstance(data_type, ArrayType):
+ return ARRAY
+ if isinstance(data_type, MapType):
+ return MAP
+ if isinstance(data_type, MultisetType):
+ return MULTISET
+ if isinstance(data_type, VectorType):
+ return VECTOR
+ if isinstance(data_type, AtomicType):
+ t = data_type.type.upper()
+ if t.startswith("DECIMAL") or t.startswith("NUMERIC") or t.startswith("DEC"):
+ return DECIMAL
+ if t in ("INT", "INTEGER"):
+ return INTEGER
+ if t in (TINYINT, SMALLINT, BIGINT, FLOAT, DOUBLE, BOOLEAN, DATE):
+ return t
+ if t == "STRING" or t.startswith("VARCHAR"):
+ return VARCHAR
+ if t.startswith("CHAR"):
+ return CHAR
+ if t == "BYTES" or t.startswith("VARBINARY"):
+ return VARBINARY
+ if t.startswith("BINARY"):
+ return BINARY
+ if t == "BLOB":
+ return BLOB
+ if t.startswith("TIMESTAMP_LTZ"):
+ return TIMESTAMP_LTZ
+ if t.startswith("TIMESTAMP"):
+ return TIMESTAMP
+ if t.startswith("TIME"):
+ return TIME
+ if t == "VARIANT":
+ return VARIANT
+ return None
+
+
+def _build_rules():
+ implicit = {}
+ explicit = {}
+ # Identity cast for every root.
+ for root in (PREDEFINED | CONSTRUCTED | {VARIANT, BLOB}):
+ implicit[root] = {root}
+ explicit[root] = set()
+
+ def rule(target, implicit_from=None, explicit_from=None):
+ implicit[target] |= set(implicit_from or set())
+ explicit[target] |= set(explicit_from or set())
+
+ rule(CHAR, {CHAR}, PREDEFINED | STRING_RENDERABLE_CONSTRUCTED)
+ rule(VARCHAR, CHARACTER_STRING, PREDEFINED | STRING_RENDERABLE_CONSTRUCTED)
+ rule(BOOLEAN, {BOOLEAN}, CHARACTER_STRING | INTEGER_NUMERIC)
+ rule(BINARY, {BINARY}, CHARACTER_STRING | {VARBINARY})
+ rule(VARBINARY, BINARY_STRING, CHARACTER_STRING | {BINARY})
+ rule(DECIMAL, NUMERIC, CHARACTER_STRING | {BOOLEAN, TIMESTAMP, TIMESTAMP_LTZ})
Review Comment:
Some casts accepted by these rules cannot actually be materialized by the Python read path. I reproduced `TIMESTAMP(3) -> DECIMAL(10, 0)`: `supports_cast` accepts it and alter succeeds, but reading old files fails in `array.cast(...)` with `ArrowNotImplementedError: Unsupported cast from timestamp[ms] to decimal128`. Java also checks `CastExecutors.resolve(...) != null`; Python needs either an equivalent executable-cast check or narrower rules that only allow casts implemented by PyArrow/custom code.
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [python] Support schema evolution of nested struct sub-fields [paimon]
Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #8187:
URL: https://github.com/apache/paimon/pull/8187#discussion_r3386258744
##########
paimon-python/pypaimon/read/reader/data_file_batch_reader.py:
##########
@@ -57,55 +59,99 @@ def __init__(self, format_reader: RecordBatchReader, index_mapping: List[int], p
self.file_io = file_io
# Per-file field-id normalization: map the physically-read columns
# (the file's own field order/names) onto the latest read target by
- # field id, padding missing ids with NULL. ``None`` when there is no
- # evolution to reconcile (identity) -- the common path stays zero-copy.
- self._normalize_positions, self._normalize_names = \
- self._build_normalize_plan(file_data_fields, target_data_fields)
+ # field id, padding missing ids with NULL and recursing into nested
+ # ROW / ARRAY<ROW> / MAP<.,ROW> sub-fields the same way. ``None`` when
+ # there is no evolution to reconcile -- the common path stays zero-copy.
+ self._normalize_plan = self._build_normalize_plan(file_data_fields, target_data_fields)
Review Comment:
The new nested field-id normalization is skipped for dotted nested projections. SplitRead.file_reader_supplier passes file_data_fields=None and target_data_fields=None whenever has_nested is true, so with_projection(['mv.renamed_leaf']) still reads by the new physical name from old files. I reproduced rename mv.s -> ss followed by projection ['id', 'mv.ss']: the old row returned mv_ss=None instead of 'a'. A nested type change is worse: projecting the evolved leaf kept old batches as int32 and new batches as int64, causing pyarrow.lib.ArrowInvalid during concatenation.
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [python] Support schema evolution of nested struct sub-fields [paimon]
Posted by "TheR1sing3un (via GitHub)" <gi...@apache.org>.
TheR1sing3un commented on code in PR #8187:
URL: https://github.com/apache/paimon/pull/8187#discussion_r3386423297
##########
paimon-python/pypaimon/read/reader/data_file_batch_reader.py:
##########
@@ -57,55 +59,99 @@ def __init__(self, format_reader: RecordBatchReader, index_mapping: List[int], p
self.file_io = file_io
# Per-file field-id normalization: map the physically-read columns
# (the file's own field order/names) onto the latest read target by
- # field id, padding missing ids with NULL. ``None`` when there is no
- # evolution to reconcile (identity) -- the common path stays zero-copy.
- self._normalize_positions, self._normalize_names = \
- self._build_normalize_plan(file_data_fields, target_data_fields)
+ # field id, padding missing ids with NULL and recursing into nested
+ # ROW / ARRAY<ROW> / MAP<.,ROW> sub-fields the same way. ``None`` when
+ # there is no evolution to reconcile -- the common path stays zero-copy.
+ self._normalize_plan = self._build_normalize_plan(file_data_fields, target_data_fields)
Review Comment:
> The new nested field-id normalization is skipped for dotted nested projections. SplitRead.file_reader_supplier passes file_data_fields=None and target_data_fields=None whenever has_nested is true, so with_projection(['mv.renamed_leaf']) still reads by the new physical name from old files. I reproduced rename mv.s -> ss followed by projection ['id', 'mv.ss']: the old row returned mv_ss=None instead of 'a'. A nested type change is worse: projecting the evolved leaf kept old batches as int32 and new batches as int64, causing pyarrow.lib.ArrowInvalid during concatenation.
Fixed.
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [python] Support schema evolution of nested struct sub-fields [paimon]
Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #8187:
URL: https://github.com/apache/paimon/pull/8187#discussion_r3392745025
##########
paimon-python/pypaimon/casting/data_type_casts.py:
##########
@@ -0,0 +1,167 @@
+# 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.
+
+"""Type-cast support rules used to validate ``update column type`` schema
+changes.
+
+The rules mirror the engine-wide cast specification so a type change accepted
+here is one the read path can also materialize: an *implicit* cast is a safe
+widening (e.g. INT -> BIGINT, any numeric -> DECIMAL/DOUBLE), while an
+*explicit* cast covers the broader, possibly lossy conversions a user opts into
+(e.g. DOUBLE -> INT truncation, anything -> STRING). Read-time execution then
+applies the conversion leniently.
+"""
+
+from pypaimon.schema.data_types import (ArrayType, AtomicType, MapType,
+ MultisetType, RowType, VectorType)
+
+# ---- Type roots --------------------------------------------------------------
+
+CHAR = "CHAR"
+VARCHAR = "VARCHAR"
+BOOLEAN = "BOOLEAN"
+BINARY = "BINARY"
+VARBINARY = "VARBINARY"
+DECIMAL = "DECIMAL"
+TINYINT = "TINYINT"
+SMALLINT = "SMALLINT"
+INTEGER = "INTEGER"
+BIGINT = "BIGINT"
+FLOAT = "FLOAT"
+DOUBLE = "DOUBLE"
+DATE = "DATE"
+TIME = "TIME"
+TIMESTAMP = "TIMESTAMP"
+TIMESTAMP_LTZ = "TIMESTAMP_LTZ"
+ARRAY = "ARRAY"
+MAP = "MAP"
+MULTISET = "MULTISET"
+ROW = "ROW"
+VECTOR = "VECTOR"
+VARIANT = "VARIANT"
+BLOB = "BLOB"
+
+# ---- Families ----------------------------------------------------------------
+
+CHARACTER_STRING = {CHAR, VARCHAR}
+BINARY_STRING = {BINARY, VARBINARY}
+INTEGER_NUMERIC = {TINYINT, SMALLINT, INTEGER, BIGINT}
+NUMERIC = INTEGER_NUMERIC | {FLOAT, DOUBLE, DECIMAL}
+TIMESTAMP_FAMILY = {TIMESTAMP, TIMESTAMP_LTZ}
+TIME_FAMILY = {TIME}
+DATETIME = {DATE, TIME, TIMESTAMP, TIMESTAMP_LTZ}
+PREDEFINED = {
+ CHAR, VARCHAR, BOOLEAN, BINARY, VARBINARY, DECIMAL,
+ TINYINT, SMALLINT, INTEGER, BIGINT, FLOAT, DOUBLE,
+ DATE, TIME, TIMESTAMP, TIMESTAMP_LTZ,
+}
+CONSTRUCTED = {ARRAY, MAP, MULTISET, ROW, VECTOR}
+
+
+def _root(data_type) -> str:
+ if isinstance(data_type, RowType):
+ return ROW
+ if isinstance(data_type, ArrayType):
+ return ARRAY
+ if isinstance(data_type, MapType):
+ return MAP
+ if isinstance(data_type, MultisetType):
+ return MULTISET
+ if isinstance(data_type, VectorType):
+ return VECTOR
+ if isinstance(data_type, AtomicType):
+ t = data_type.type.upper()
+ if t.startswith("DECIMAL") or t.startswith("NUMERIC") or t.startswith("DEC"):
+ return DECIMAL
+ if t in ("INT", "INTEGER"):
+ return INTEGER
+ if t in (TINYINT, SMALLINT, BIGINT, FLOAT, DOUBLE, BOOLEAN, DATE):
+ return t
+ if t == "STRING" or t.startswith("VARCHAR"):
+ return VARCHAR
+ if t.startswith("CHAR"):
+ return CHAR
+ if t == "BYTES" or t.startswith("VARBINARY"):
+ return VARBINARY
+ if t.startswith("BINARY"):
+ return BINARY
+ if t == "BLOB":
+ return BLOB
+ if t.startswith("TIMESTAMP_LTZ"):
+ return TIMESTAMP_LTZ
+ if t.startswith("TIMESTAMP"):
+ return TIMESTAMP
+ if t.startswith("TIME"):
+ return TIME
+ if t == "VARIANT":
+ return VARIANT
+ return None
+
+
+def _build_rules():
+ implicit = {}
+ explicit = {}
+ # Identity cast for every root.
+ for root in (PREDEFINED | CONSTRUCTED | {VARIANT, BLOB}):
+ implicit[root] = {root}
+ explicit[root] = set()
+
+ def rule(target, implicit_from=None, explicit_from=None):
+ implicit[target] |= set(implicit_from or set())
+ explicit[target] |= set(explicit_from or set())
+
+ rule(CHAR, {CHAR}, PREDEFINED | CONSTRUCTED)
+ rule(VARCHAR, CHARACTER_STRING, PREDEFINED | CONSTRUCTED)
Review Comment:
This allows constructed types to be changed to STRING, but the read-time cast cannot materialize those conversions. For example, create a table with `mv ROW<a INT>` (or ARRAY/MAP), write one file, then `update_column_type("mv", STRING)`: the alter succeeds because `supports_cast` returns true here, but reading the old file fails in `DataFileBatchReader._align_array_by_id` with `ArrowNotImplementedError: Unsupported cast from struct/list/map ... to utf8`. Please either reject constructed-type -> STRING here, or add an explicit serialization conversion in the read path and cover it with a round-trip test.
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [python] Support schema evolution of nested struct sub-fields [paimon]
Posted by "TheR1sing3un (via GitHub)" <gi...@apache.org>.
TheR1sing3un commented on code in PR #8187:
URL: https://github.com/apache/paimon/pull/8187#discussion_r3409598752
##########
paimon-python/pypaimon/schema/schema_manager.py:
##########
@@ -55,49 +174,87 @@ def _get_rename_mappings(changes: List[SchemaChange]) -> dict:
def _handle_update_column_comment(
change: UpdateColumnComment, new_fields: List[DataField]
):
- field_name = change.field_names[-1]
- field_index = _find_field_index(new_fields, field_name)
- if field_index is None:
- raise ColumnNotExistException(field_name)
- field = new_fields[field_index]
- new_fields[field_index] = DataField(
- field.id, field.name, field.type, change.new_comment, field.default_value
- )
+ def update_func(field: DataField, depth: int) -> DataField:
+ return DataField(
+ field.id, field.name, field.type, change.new_comment, field.default_value
+ )
+ _update_nested_column(new_fields, change.field_names, update_func)
+
+
+def _assert_nullability_change(old_nullability: bool, new_nullability: bool,
+ field_name: str, disable_null_to_not_null: bool):
+ if disable_null_to_not_null and old_nullability and not new_nullability:
+ raise ValueError(
+ "Cannot update column type from nullable to non nullable for {}. "
+ "You can set table configuration option "
+ "'alter-column-null-to-not-null.disabled' = 'false' "
+ "to allow converting null columns to not null".format(field_name)
+ )
def _handle_update_column_nullability(
- change: UpdateColumnNullability, new_fields: List[DataField]
+ change: UpdateColumnNullability, new_fields: List[DataField],
+ disable_null_to_not_null: bool
):
- field_name = change.field_names[-1]
- field_index = _find_field_index(new_fields, field_name)
- if field_index is None:
- raise ColumnNotExistException(field_name)
- field = new_fields[field_index]
from pypaimon.schema.data_types import DataTypeParser
- field_type_dict = field.type.to_dict()
- new_type = DataTypeParser.parse_data_type(field_type_dict)
- new_type.nullable = change.new_nullability
- new_fields[field_index] = DataField(
- field.id, field.name, new_type, field.description, field.default_value
- )
+ field_names = change.field_names
+ max_depth = len(field_names)
+
+ def update_func(field: DataField, depth: int) -> DataField:
+ source_root = _get_root_type(field.type, depth, max_depth)
+ _assert_nullability_change(
+ source_root.nullable, change.new_nullability,
+ '.'.join(field_names), disable_null_to_not_null)
+ new_root = DataTypeParser.parse_data_type(source_root.to_dict())
+ new_root.nullable = change.new_nullability
+ new_type = _get_array_map_type_with_target_type_root(
+ field.type, new_root, depth, max_depth)
+ return DataField(
+ field.id, field.name, new_type, field.description, field.default_value
+ )
+ _update_nested_column(new_fields, field_names, update_func)
def _handle_update_column_type(
- change: UpdateColumnType, new_fields: List[DataField]
+ change: UpdateColumnType, new_fields: List[DataField],
+ disable_null_to_not_null: bool
):
- field_name = change.field_names[-1]
- field_index = _find_field_index(new_fields, field_name)
- if field_index is None:
- raise ColumnNotExistException(field_name)
- field = new_fields[field_index]
from pypaimon.schema.data_types import DataTypeParser
- new_type_dict = change.new_data_type.to_dict()
- new_type = DataTypeParser.parse_data_type(new_type_dict)
- if change.keep_nullability:
- new_type.nullable = field.type.nullable
- new_fields[field_index] = DataField(
- field.id, field.name, new_type, field.description, field.default_value
- )
+ field_names = change.field_names
+ max_depth = len(field_names)
+
+ def update_func(field: DataField, depth: int) -> DataField:
+ source_root = _get_root_type(field.type, depth, max_depth)
+ target_root = DataTypeParser.parse_data_type(change.new_data_type.to_dict())
Review Comment:
fixed
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [python] Support schema evolution of nested struct sub-fields [paimon]
Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #8187:
URL: https://github.com/apache/paimon/pull/8187#discussion_r3409287158
##########
paimon-python/pypaimon/casting/data_type_casts.py:
##########
@@ -0,0 +1,252 @@
+# 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.
+
+"""Type-cast support rules used to validate ``update column type`` schema
+changes.
+
+The rules mirror the engine-wide cast specification so a type change accepted
+here is one the read path can also materialize: an *implicit* cast is a safe
+widening (e.g. INT -> BIGINT, any numeric -> DECIMAL/DOUBLE), while an
+*explicit* cast covers the broader, possibly lossy conversions a user opts into
+(e.g. DOUBLE -> INT truncation, anything -> STRING). Read-time execution then
+applies the conversion leniently.
+"""
+
+import pyarrow as pa
+
+from pypaimon.schema.data_types import (ArrayType, AtomicType, DataTypeParser,
+ MapType, MultisetType,
+ PyarrowFieldParser, RowType,
+ VectorType)
+
+# ---- Type roots --------------------------------------------------------------
+
+CHAR = "CHAR"
+VARCHAR = "VARCHAR"
+BOOLEAN = "BOOLEAN"
+BINARY = "BINARY"
+VARBINARY = "VARBINARY"
+DECIMAL = "DECIMAL"
+TINYINT = "TINYINT"
+SMALLINT = "SMALLINT"
+INTEGER = "INTEGER"
+BIGINT = "BIGINT"
+FLOAT = "FLOAT"
+DOUBLE = "DOUBLE"
+DATE = "DATE"
+TIME = "TIME"
+TIMESTAMP = "TIMESTAMP"
+TIMESTAMP_LTZ = "TIMESTAMP_LTZ"
+ARRAY = "ARRAY"
+MAP = "MAP"
+MULTISET = "MULTISET"
+ROW = "ROW"
+VECTOR = "VECTOR"
+VARIANT = "VARIANT"
+BLOB = "BLOB"
+
+# ---- Families ----------------------------------------------------------------
+
+CHARACTER_STRING = {CHAR, VARCHAR}
+BINARY_STRING = {BINARY, VARBINARY}
+INTEGER_NUMERIC = {TINYINT, SMALLINT, INTEGER, BIGINT}
+NUMERIC = INTEGER_NUMERIC | {FLOAT, DOUBLE, DECIMAL}
+TIMESTAMP_FAMILY = {TIMESTAMP, TIMESTAMP_LTZ}
+TIME_FAMILY = {TIME}
+DATETIME = {DATE, TIME, TIMESTAMP, TIMESTAMP_LTZ}
+PREDEFINED = {
+ CHAR, VARCHAR, BOOLEAN, BINARY, VARBINARY, DECIMAL,
+ TINYINT, SMALLINT, INTEGER, BIGINT, FLOAT, DOUBLE,
+ DATE, TIME, TIMESTAMP, TIMESTAMP_LTZ,
+}
+CONSTRUCTED = {ARRAY, MAP, MULTISET, ROW, VECTOR}
+# Constructed types the read path can render as a character string
+# ('{v1, v2}' / '[e1, e2]' / '{k -> v}'). VECTOR and MULTISET have no string
+# rendering, so a type change from them to CHAR/VARCHAR is rejected here
+# rather than failing when an old file is read.
+STRING_RENDERABLE_CONSTRUCTED = {ARRAY, MAP, ROW}
+
+
+def _root(data_type) -> str:
+ if isinstance(data_type, RowType):
+ return ROW
+ if isinstance(data_type, ArrayType):
+ return ARRAY
+ if isinstance(data_type, MapType):
+ return MAP
+ if isinstance(data_type, MultisetType):
+ return MULTISET
+ if isinstance(data_type, VectorType):
+ return VECTOR
+ if isinstance(data_type, AtomicType):
+ t = data_type.type.upper()
+ if t.startswith("DECIMAL") or t.startswith("NUMERIC") or t.startswith("DEC"):
+ return DECIMAL
+ if t in ("INT", "INTEGER"):
+ return INTEGER
+ if t in (TINYINT, SMALLINT, BIGINT, FLOAT, DOUBLE, BOOLEAN, DATE):
+ return t
+ if t == "STRING" or t.startswith("VARCHAR"):
+ return VARCHAR
+ if t.startswith("CHAR"):
+ return CHAR
+ if t == "BYTES" or t.startswith("VARBINARY"):
+ return VARBINARY
+ if t.startswith("BINARY"):
+ return BINARY
+ if t == "BLOB":
+ return BLOB
+ if t.startswith("TIMESTAMP_LTZ"):
+ return TIMESTAMP_LTZ
+ if t.startswith("TIMESTAMP"):
+ return TIMESTAMP
+ if t.startswith("TIME"):
+ return TIME
+ if t == "VARIANT":
+ return VARIANT
+ return None
+
+
+def _build_rules():
+ implicit = {}
+ explicit = {}
+ # Identity cast for every root.
+ for root in (PREDEFINED | CONSTRUCTED | {VARIANT, BLOB}):
+ implicit[root] = {root}
+ explicit[root] = set()
+
+ def rule(target, implicit_from=None, explicit_from=None):
+ implicit[target] |= set(implicit_from or set())
+ explicit[target] |= set(explicit_from or set())
+
+ rule(CHAR, {CHAR}, PREDEFINED | STRING_RENDERABLE_CONSTRUCTED)
+ rule(VARCHAR, CHARACTER_STRING, PREDEFINED | STRING_RENDERABLE_CONSTRUCTED)
+ rule(BOOLEAN, {BOOLEAN}, CHARACTER_STRING | INTEGER_NUMERIC)
+ rule(BINARY, {BINARY}, CHARACTER_STRING | {VARBINARY})
+ rule(VARBINARY, BINARY_STRING, CHARACTER_STRING | {BINARY})
+ rule(DECIMAL, NUMERIC, CHARACTER_STRING | {BOOLEAN, TIMESTAMP, TIMESTAMP_LTZ})
+ int_explicit = NUMERIC | CHARACTER_STRING | {BOOLEAN, TIMESTAMP, TIMESTAMP_LTZ}
+ rule(TINYINT, {TINYINT}, int_explicit)
+ rule(SMALLINT, {TINYINT, SMALLINT}, int_explicit)
+ rule(INTEGER, {TINYINT, SMALLINT, INTEGER}, int_explicit)
+ rule(BIGINT, {TINYINT, SMALLINT, INTEGER, BIGINT}, int_explicit)
+ rule(FLOAT, {TINYINT, SMALLINT, INTEGER, BIGINT, FLOAT, DECIMAL}, int_explicit)
+ rule(DOUBLE, NUMERIC, CHARACTER_STRING | {BOOLEAN, TIMESTAMP, TIMESTAMP_LTZ})
+ rule(DATE, {DATE, TIMESTAMP}, TIMESTAMP_FAMILY | CHARACTER_STRING)
+ rule(TIME, {TIME, TIMESTAMP}, TIME_FAMILY | TIMESTAMP_FAMILY | CHARACTER_STRING)
+ rule(TIMESTAMP, {TIMESTAMP, TIMESTAMP_LTZ}, DATETIME | CHARACTER_STRING | NUMERIC)
+ rule(TIMESTAMP_LTZ, {TIMESTAMP_LTZ, TIMESTAMP}, DATETIME | CHARACTER_STRING | NUMERIC)
+ return implicit, explicit
+
+
+_IMPLICIT_RULES, _EXPLICIT_RULES = _build_rules()
+
+
+def supports_cast(source_type, target_type, allow_explicit: bool = True) -> bool:
+ """Whether ``source_type`` can be cast to ``target_type`` for a column type
+ change. ``allow_explicit`` permits the broader (possibly lossy) conversions
+ in addition to the safe widening ones."""
+ source_root = _root(source_type)
+ target_root = _root(target_type)
+ if source_root is None or target_root is None:
+ return False
+ # A NOT NULL target cannot accept a nullable source unless explicitly allowed.
+ if source_type.nullable and not target_type.nullable and not allow_explicit:
+ return False
+ if source_root == target_root:
+ if source_root in CONSTRUCTED:
+ # A constructed type is only castable to an (ignoring outer
+ # nullability) identical constructed type. Reshaping is done
+ # through sub-field / 'element' / 'value' paths instead: a whole
+ # ROW replacement would carry caller-supplied nested field ids
+ # that corrupt the id model, and there is no runtime conversion
+ # between differently-shaped constructed values.
+ return _equals_ignore_nullable(source_type, target_type)
+ return True
+ if source_root in _IMPLICIT_RULES.get(target_root, set()):
+ return True
+ if allow_explicit and source_root in _EXPLICIT_RULES.get(target_root, set()):
+ return True
+ return False
+
+
+def _equals_ignore_nullable(source_type, target_type) -> bool:
+ source_copy = DataTypeParser.parse_data_type(source_type.to_dict())
+ target_copy = DataTypeParser.parse_data_type(target_type.to_dict())
+ source_copy.nullable = True
+ target_copy.nullable = True
+ return source_copy == target_copy
+
+
+# Caches the PyArrow cast-kernel probe per (source, target) pyarrow type so the
+# alter-time check stays cheap. Keyed by the pyarrow type strings.
+_EXECUTABLE_CAST_CACHE = {}
+
+
+def can_execute_cast(source_type, target_type) -> bool:
+ """Whether the Python read path can actually *materialize* a stored
+ ``source_type`` value as ``target_type`` when reading a file written before
+ the column type change.
+
+ ``supports_cast`` only encodes the *logical* cast specification (mirroring
+ Java ``DataTypeCasts``). This is the executable-cast counterpart of Java's
+ ``CastExecutors.resolve(...) != null`` guard: some logically-valid casts
+ (e.g. ``TIMESTAMP -> DECIMAL``, ``BOOLEAN -> DECIMAL``, ``TIME ->
+ TIMESTAMP``) have no PyArrow cast kernel, so without this check the alter
+ succeeds and the read later fails with ``ArrowNotImplementedError``.
+ """
+ source_root = _root(source_type)
+ target_root = _root(target_type)
+ if source_root is None or target_root is None:
+ return False
+ # Same root: identity, or a same-shape constructed type whose value is
+ # rebuilt by the read path's field-id alignment rather than a value cast.
+ if source_root == target_root:
+ return True
+ # Constructed -> character string is rendered by the read path's custom
+ # ``_constructed_to_string_array`` (see DataFileBatchReader), not a cast.
+ if (source_root in STRING_RENDERABLE_CONSTRUCTED
+ and target_root in CHARACTER_STRING):
+ return True
+ # Any other conversion touching a constructed type has no runtime cast.
+ if source_root in CONSTRUCTED or target_root in CONSTRUCTED:
+ return False
+ # Leaf-to-leaf: defer to PyArrow's cast-kernel availability, which is the
+ # read path's actual cast executor (``array.cast(target, safe=False)``).
+ return _pyarrow_cast_supported(source_type, target_type)
+
+
+def _pyarrow_cast_supported(source_type, target_type) -> bool:
+ source_pa = PyarrowFieldParser.from_paimon_type(source_type)
+ target_pa = PyarrowFieldParser.from_paimon_type(target_type)
+ if source_pa == target_pa:
+ return True
+ cache_key = (str(source_pa), str(target_pa))
+ cached = _EXECUTABLE_CAST_CACHE.get(cache_key)
+ if cached is not None:
+ return cached
+ # An empty-array cast exercises only kernel resolution (not per-value
+ # conversion), so it reports whether PyArrow has a cast kernel for the pair
+ # without depending on any data. ``safe=False`` matches the read path.
+ try:
+ pa.array([], type=source_pa).cast(target_pa, safe=False)
Review Comment:
The empty-array probe only checks whether a PyArrow kernel exists, but some kernels still reject all non-empty arrays for the target type parameters. A concrete repro is `INT` or `BIGINT` -> `DECIMAL(10, 2)`: `can_execute_cast` returns true and `alter_table` succeeds, but reading an old file with value `1` fails in the actual read path with `ArrowInvalid: Precision is not great enough for the result` (PyArrow requires precision >= 12 for INT scale 2 and >= 21 for BIGINT scale 2). Could this either probe representative values for numeric widths/scale or explicitly validate decimal precision requirements before accepting numeric -> decimal casts?
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [python] Support schema evolution of nested struct sub-fields [paimon]
Posted by "TheR1sing3un (via GitHub)" <gi...@apache.org>.
TheR1sing3un commented on code in PR #8187:
URL: https://github.com/apache/paimon/pull/8187#discussion_r3392968985
##########
paimon-python/pypaimon/casting/data_type_casts.py:
##########
@@ -0,0 +1,167 @@
+# 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.
+
+"""Type-cast support rules used to validate ``update column type`` schema
+changes.
+
+The rules mirror the engine-wide cast specification so a type change accepted
+here is one the read path can also materialize: an *implicit* cast is a safe
+widening (e.g. INT -> BIGINT, any numeric -> DECIMAL/DOUBLE), while an
+*explicit* cast covers the broader, possibly lossy conversions a user opts into
+(e.g. DOUBLE -> INT truncation, anything -> STRING). Read-time execution then
+applies the conversion leniently.
+"""
+
+from pypaimon.schema.data_types import (ArrayType, AtomicType, MapType,
+ MultisetType, RowType, VectorType)
+
+# ---- Type roots --------------------------------------------------------------
+
+CHAR = "CHAR"
+VARCHAR = "VARCHAR"
+BOOLEAN = "BOOLEAN"
+BINARY = "BINARY"
+VARBINARY = "VARBINARY"
+DECIMAL = "DECIMAL"
+TINYINT = "TINYINT"
+SMALLINT = "SMALLINT"
+INTEGER = "INTEGER"
+BIGINT = "BIGINT"
+FLOAT = "FLOAT"
+DOUBLE = "DOUBLE"
+DATE = "DATE"
+TIME = "TIME"
+TIMESTAMP = "TIMESTAMP"
+TIMESTAMP_LTZ = "TIMESTAMP_LTZ"
+ARRAY = "ARRAY"
+MAP = "MAP"
+MULTISET = "MULTISET"
+ROW = "ROW"
+VECTOR = "VECTOR"
+VARIANT = "VARIANT"
+BLOB = "BLOB"
+
+# ---- Families ----------------------------------------------------------------
+
+CHARACTER_STRING = {CHAR, VARCHAR}
+BINARY_STRING = {BINARY, VARBINARY}
+INTEGER_NUMERIC = {TINYINT, SMALLINT, INTEGER, BIGINT}
+NUMERIC = INTEGER_NUMERIC | {FLOAT, DOUBLE, DECIMAL}
+TIMESTAMP_FAMILY = {TIMESTAMP, TIMESTAMP_LTZ}
+TIME_FAMILY = {TIME}
+DATETIME = {DATE, TIME, TIMESTAMP, TIMESTAMP_LTZ}
+PREDEFINED = {
+ CHAR, VARCHAR, BOOLEAN, BINARY, VARBINARY, DECIMAL,
+ TINYINT, SMALLINT, INTEGER, BIGINT, FLOAT, DOUBLE,
+ DATE, TIME, TIMESTAMP, TIMESTAMP_LTZ,
+}
+CONSTRUCTED = {ARRAY, MAP, MULTISET, ROW, VECTOR}
+
+
+def _root(data_type) -> str:
+ if isinstance(data_type, RowType):
+ return ROW
+ if isinstance(data_type, ArrayType):
+ return ARRAY
+ if isinstance(data_type, MapType):
+ return MAP
+ if isinstance(data_type, MultisetType):
+ return MULTISET
+ if isinstance(data_type, VectorType):
+ return VECTOR
+ if isinstance(data_type, AtomicType):
+ t = data_type.type.upper()
+ if t.startswith("DECIMAL") or t.startswith("NUMERIC") or t.startswith("DEC"):
+ return DECIMAL
+ if t in ("INT", "INTEGER"):
+ return INTEGER
+ if t in (TINYINT, SMALLINT, BIGINT, FLOAT, DOUBLE, BOOLEAN, DATE):
+ return t
+ if t == "STRING" or t.startswith("VARCHAR"):
+ return VARCHAR
+ if t.startswith("CHAR"):
+ return CHAR
+ if t == "BYTES" or t.startswith("VARBINARY"):
+ return VARBINARY
+ if t.startswith("BINARY"):
+ return BINARY
+ if t == "BLOB":
+ return BLOB
+ if t.startswith("TIMESTAMP_LTZ"):
+ return TIMESTAMP_LTZ
+ if t.startswith("TIMESTAMP"):
+ return TIMESTAMP
+ if t.startswith("TIME"):
+ return TIME
+ if t == "VARIANT":
+ return VARIANT
+ return None
+
+
+def _build_rules():
+ implicit = {}
+ explicit = {}
+ # Identity cast for every root.
+ for root in (PREDEFINED | CONSTRUCTED | {VARIANT, BLOB}):
+ implicit[root] = {root}
+ explicit[root] = set()
+
+ def rule(target, implicit_from=None, explicit_from=None):
+ implicit[target] |= set(implicit_from or set())
+ explicit[target] |= set(explicit_from or set())
+
+ rule(CHAR, {CHAR}, PREDEFINED | CONSTRUCTED)
+ rule(VARCHAR, CHARACTER_STRING, PREDEFINED | CONSTRUCTED)
Review Comment:
> This allows constructed types to be changed to STRING, but the read-time cast cannot materialize those conversions. For example, create a table with `mv ROW<a INT>` (or ARRAY/MAP), write one file, then `update_column_type("mv", STRING)`: the alter succeeds because `supports_cast` returns true here, but reading the old file fails in `DataFileBatchReader._align_array_by_id` with `ArrowNotImplementedError: Unsupported cast from struct/list/map ... to utf8`. Please either reject constructed-type -> STRING here, or add an explicit serialization conversion in the read path and cover it with a round-trip test.
Nice catch! Thank you! Fixed~
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org