This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git
The following commit(s) were added to refs/heads/master by this push:
new 3bebfe2c37 [python] Reject duplicate columns and unknown or duplicate
keys in create_table and alter_table (#11028)
3bebfe2c37 is described below
commit 3bebfe2c3757f8f18f12264d14ddba81876c0d37
Author: YangJie <[email protected]>
AuthorDate: Tue Nov 10 04:14:29 2026 -0500
[python] Reject duplicate columns and unknown or duplicate keys in
create_table and alter_table (#11028)
---
paimon-python/pypaimon/schema/schema_manager.py | 30 ++++++++++
.../pypaimon/tests/schema_manager_test.py | 69 +++++++++++++++++++++-
2 files changed, 98 insertions(+), 1 deletion(-)
diff --git a/paimon-python/pypaimon/schema/schema_manager.py
b/paimon-python/pypaimon/schema/schema_manager.py
index 3e3fbf3ebe..d5338a307a 100644
--- a/paimon-python/pypaimon/schema/schema_manager.py
+++ b/paimon-python/pypaimon/schema/schema_manager.py
@@ -15,6 +15,7 @@
# specific language governing permissions and limitations
# under the License.
+from collections import Counter
from typing import List, Optional
from pypaimon.catalog.catalog_exception import (ColumnAlreadyExistException,
@@ -747,6 +748,31 @@ def _validate_primary_key_blob_fields(
)
+def _duplicates(names: List[str]) -> List[str]:
+ return sorted(name for name, count in Counter(names).items() if count > 1)
+
+
+def _validate_columns_and_keys(schema: Schema):
+ """Java's Schema checks that column names are unique and that partition
+ and primary keys do not repeat and are columns. A key that is not a column
+ is persisted otherwise, and the table can then no longer be loaded."""
+ names = [field.name for field in schema.fields]
+ if _duplicates(names):
+ raise ValueError(
+ f"Table column {names} must not contain duplicate fields. "
+ f"Found: {_duplicates(names)}")
+ for constraint, included, keys in (
+ ("Partition key", "partition fields", schema.partition_keys),
+ ("Primary key", "primary key constraint", schema.primary_keys)):
+ if _duplicates(keys):
+ raise ValueError(
+ f"{constraint} constraint {keys} must not contain duplicate "
+ f"columns. Found: {_duplicates(keys)}")
+ if not set(keys) <= set(names):
+ raise ValueError(
+ f"Table column {names} should include all {included} {keys}")
+
+
def _validate_options(options: dict):
core_options = CoreOptions(Options(options))
target_file_row_num = core_options.target_file_row_num()
@@ -959,6 +985,7 @@ class SchemaManager:
comment=schema.comment,
)
+ _validate_columns_and_keys(schema)
table_schema = TableSchema.from_schema(schema_id=0, schema=schema)
success = self.commit(table_schema)
if success:
@@ -1152,6 +1179,9 @@ class SchemaManager:
options=new_options,
comment=new_comment
)
+ # Java's Schema runs the same checks when an alter builds it, which
+ # rejects, for example, renaming a primary key twice in one alter.
+ _validate_columns_and_keys(new_schema)
return TableSchema(
version=old_table_schema.version,
diff --git a/paimon-python/pypaimon/tests/schema_manager_test.py
b/paimon-python/pypaimon/tests/schema_manager_test.py
index 31fe605974..1b0f493042 100644
--- a/paimon-python/pypaimon/tests/schema_manager_test.py
+++ b/paimon-python/pypaimon/tests/schema_manager_test.py
@@ -20,7 +20,9 @@ import tempfile
import unittest
from unittest.mock import patch
+from pypaimon import CatalogFactory
from pypaimon.branch.branch_manager import BranchManager
+from pypaimon.catalog.catalog_exception import TableNotExistException
from pypaimon.common.identifier import DEFAULT_MAIN_BRANCH
from pypaimon.common.file_io import FileIO
from pypaimon.common.options.core_options import CoreOptions, MergeEngine
@@ -28,7 +30,7 @@ from pypaimon.common.options.options import Options
from pypaimon.schema.data_types import (ArrayType, AtomicType, DataField,
MapType, RowType)
from pypaimon.schema.schema import Schema
-from pypaimon.schema.schema_change import RemoveOption, SetOption
+from pypaimon.schema.schema_change import RemoveOption, SchemaChange, SetOption
from pypaimon.schema.schema_manager import SchemaManager
from pypaimon.schema.table_schema import TableSchema
from pypaimon.snapshot.snapshot_manager import SnapshotManager
@@ -860,5 +862,70 @@ class TestRowTrackingValidation(unittest.TestCase):
self.assertNotIn("row-tracking.enabled", manager.latest().options)
+class TestColumnAndKeyValidation(unittest.TestCase):
+ """create_table and alter_table reject the column and key lists Java's
Schema rejects."""
+
+ def setUp(self):
+ self.temp_dir = tempfile.mkdtemp()
+ warehouse = os.path.join(self.temp_dir, "warehouse")
+ self.catalog = CatalogFactory.create({"warehouse": warehouse})
+ self.catalog.create_database("default", True)
+
+ def tearDown(self):
+ import shutil
+ shutil.rmtree(self.temp_dir, ignore_errors=True)
+
+ @staticmethod
+ def _schema(names=("id", "dt"), partition_keys=None, primary_keys=None):
+ return Schema(
+ fields=[DataField(i, name, AtomicType("INT", False))
+ for i, name in enumerate(names)],
+ partition_keys=partition_keys or [],
+ primary_keys=primary_keys or [],
+ options={"bucket": "1"} if primary_keys else {},
+ )
+
+ def test_create_table_rejects_key_that_is_not_a_column(self):
+ for kwargs, message in (
+ ({"partition_keys": ["dtt"]}, "should include all partition
fields"),
+ ({"primary_keys": ["idd"]}, "should include all primary key
constraint")):
+ with self.subTest(**kwargs):
+ with self.assertRaisesRegex(ValueError, message):
+ self.catalog.create_table("default.t",
self._schema(**kwargs), False)
+ # Nothing is persisted, so the name can be used again.
+ with self.assertRaises(TableNotExistException):
+ self.catalog.get_table("default.t")
+
+ def test_alter_table_rejects_rename_that_drops_a_primary_key(self):
+ self.catalog.create_table(
+ "default.t", self._schema(primary_keys=["id"]), False)
+ # Each rename maps the old key once, so the key becomes 'middle'.
+ with self.assertRaisesRegex(
+ RuntimeError, "should include all primary key constraint"):
+ self.catalog.alter_table("default.t", [
+ SchemaChange.rename_column("id", "middle"),
+ SchemaChange.rename_column("middle", "new_id"),
+ ], False)
+ table = self.catalog.get_table("default.t")
+ self.assertEqual(0, table.table_schema.id)
+ self.assertEqual(["id"], table.table_schema.primary_keys)
+
+ self.catalog.alter_table(
+ "default.t", [SchemaChange.rename_column("id", "new_id")], False)
+ self.assertEqual(
+ ["new_id"],
self.catalog.get_table("default.t").table_schema.primary_keys)
+
+ def test_create_table_rejects_duplicates(self):
+ cases = [
+ ({"names": ("id", "id")}, "must not contain duplicate fields"),
+ ({"partition_keys": ["dt", "dt"]}, "Partition key constraint"),
+ ({"primary_keys": ["id", "id"]}, "Primary key constraint"),
+ ]
+ for kwargs, message in cases:
+ with self.subTest(**kwargs):
+ with self.assertRaisesRegex(ValueError, message):
+ self.catalog.create_table("default.t",
self._schema(**kwargs), False)
+
+
if __name__ == '__main__':
unittest.main()