From 68405f1df1124016766e890f7311ae53a4272a8b Mon Sep 17 00:00:00 2001 From: rahulsmahadev Date: Mon, 30 Nov 2026 09:37:22 +0000 Subject: [PATCH] Read the metadata before inserting the row in SqlCatalog.register_table register_table committed the table row before load_table read the metadata file, so a missing or invalid file left the table registered: list_tables showed it, table_exists raised and the name could not be registered again. Check the name, read the metadata, then insert the row, as Java's registerTable does. Co-authored-by: Isaac --- pyiceberg/catalog/sql.py | 13 ++++++- tests/catalog/test_catalog_behaviors.py | 25 ++++++++++++ tests/catalog/test_sql.py | 52 +++++++++++++++++++++++++ 3 files changed, 89 insertions(+), 1 deletion(-) diff --git a/pyiceberg/catalog/sql.py b/pyiceberg/catalog/sql.py index d2c34a692e..20448bed5f 100644 --- a/pyiceberg/catalog/sql.py +++ b/pyiceberg/catalog/sql.py @@ -319,6 +319,9 @@ def register_table(self, identifier: str | Identifier, metadata_location: str, o Raises: TableAlreadyExistsError: If the table already exists NoSuchNamespaceError: If namespace does not exist + FileNotFoundError: If the metadata file does not exist + ValidationError: If the file is not valid table metadata + NotImplementedError: If overwrite is True """ if overwrite: raise NotImplementedError("`overwrite` isn't supported") @@ -329,6 +332,14 @@ def register_table(self, identifier: str | Identifier, metadata_location: str, o if not self.namespace_exists(namespace): raise NoSuchNamespaceError(f"Namespace does not exist: {namespace}") + # Check the name, then read the metadata, then insert the row, so a failed read leaves no table behind + with Session(self.engine) as session: + if session.get(IcebergTables, (self.name, namespace, table_name)) is not None: + raise TableAlreadyExistsError(f"Table {namespace}.{table_name} already exists") + table = self._convert_orm_to_iceberg( + IcebergTables(self.name, namespace, table_name, metadata_location, previous_metadata_location=None) + ) + with Session(self.engine) as session: try: session.execute(insert(IcebergTables).values(**self._create_table_row(namespace, table_name, metadata_location))) @@ -336,7 +347,7 @@ def register_table(self, identifier: str | Identifier, metadata_location: str, o except IntegrityError as e: raise TableAlreadyExistsError(f"Table {namespace}.{table_name} already exists") from e - return self.load_table(identifier=identifier) + return table @override def load_table(self, identifier: str | Identifier) -> Table: diff --git a/tests/catalog/test_catalog_behaviors.py b/tests/catalog/test_catalog_behaviors.py index 5fc573c285..827b3ec3b2 100644 --- a/tests/catalog/test_catalog_behaviors.py +++ b/tests/catalog/test_catalog_behaviors.py @@ -31,6 +31,7 @@ from pytest_lazy_fixtures import lf from sqlalchemy.exc import IntegrityError +from pyiceberg import exceptions from pyiceberg.catalog import Catalog from pyiceberg.exceptions import ( CommitFailedException, @@ -417,6 +418,30 @@ def test_register_existing_table(catalog: Catalog, test_table_identifier: Identi catalog.register_table(test_table_identifier, metadata_location) +def test_register_table_with_unreadable_metadata( + catalog: Catalog, test_table_identifier: Identifier, metadata_location: str, tmp_path: Path +) -> None: + namespace = Catalog.namespace_from(test_table_identifier) + catalog.create_namespace(namespace) + missing_location = tmp_path / "00000-missing.metadata.json" + malformed_location = tmp_path / "00000-malformed.metadata.json" + malformed_location.write_text("{}") + # A failed registration leaves no table behind, so the name can be registered again + for location, error in [(missing_location, FileNotFoundError), (malformed_location, exceptions.ValidationError)]: + with pytest.raises(error): + catalog.register_table(test_table_identifier, str(location)) + assert not catalog.table_exists(test_table_identifier) + assert catalog.list_tables(namespace) == [] + + table = catalog.register_table(test_table_identifier, metadata_location) + assert table.metadata_location == metadata_location + + # An existing name still raises TableAlreadyExistsError when the new metadata cannot be read + with pytest.raises(TableAlreadyExistsError): + catalog.register_table(test_table_identifier, str(missing_location)) + assert catalog.load_table(test_table_identifier).metadata_location == metadata_location + + # Load table tests diff --git a/tests/catalog/test_sql.py b/tests/catalog/test_sql.py index 3d40cad22b..ad037a7c31 100644 --- a/tests/catalog/test_sql.py +++ b/tests/catalog/test_sql.py @@ -432,6 +432,45 @@ def test_rename_table_ignores_view_rows(warehouse: Path) -> None: assert row[0] == "VIEW" +def test_register_table_rejects_view_and_unreadable_table_rows(warehouse: Path, metadata_location: str, tmp_path: Path) -> None: + catalog = SqlCatalog(name="test", uri="sqlite:///:memory:", warehouse=f"file://{warehouse}") + catalog.create_namespace("ns") + _insert_view_row(catalog, "ns", "a_view") + # A table whose metadata file was removed after it was registered + removed_location = tmp_path / "00000-removed.metadata.json" + removed_location.write_text(Path(metadata_location).read_text()) + catalog.register_table(("ns", "unreadable"), str(removed_location)) + removed_location.unlink() + + # A taken name raises before any metadata is read, and the existing rows stay as they are + for table_name in ["a_view", "unreadable"]: + with pytest.raises(TableAlreadyExistsError): + catalog.register_table(("ns", table_name), str(removed_location)) + with catalog.engine.connect() as conn: + rows = conn.execute(text("SELECT table_name, metadata_location, iceberg_type FROM iceberg_tables")).fetchall() + assert sorted(tuple(row) for row in rows) == [ + ("a_view", "s3://fake/metadata.json", "VIEW"), + ("unreadable", str(removed_location), "TABLE"), + ] + + +def test_register_table_concurrent_integrity_error(warehouse: Path, metadata_location: str) -> None: + uri = f"sqlite:///{warehouse.as_posix()}/test-concurrent-register-table" + catalog_1 = SqlCatalog("test", uri=uri, warehouse=f"file://{warehouse}") + catalog_2 = SqlCatalog("test", uri=uri, warehouse=f"file://{warehouse}") + catalog_1.create_namespace("ns") + + # catalog_2 registers the name after the name check of catalog_1, right before its insert + @event.listens_for(catalog_1.engine, "before_cursor_execute") + def inject_concurrent_insert(_conn: object, _cursor: object, statement: str, *_: object) -> None: + if "INSERT INTO iceberg_tables" in statement: + catalog_2.register_table(("ns", "tbl"), metadata_location) + + with pytest.raises(TableAlreadyExistsError): + catalog_1.register_table(("ns", "tbl"), metadata_location) + assert catalog_1.load_table(("ns", "tbl")).metadata_location == metadata_location + + def test_migration_to_v1_with_property_set(warehouse: Path) -> None: uri = f"sqlite:///{warehouse.as_posix()}/test-v1-migrate" engine = _create_v0_db(uri) @@ -538,6 +577,19 @@ def _make_v0_catalog(uri: str, warehouse: Path) -> SqlCatalog: return SqlCatalog("test", uri=uri, warehouse=f"file://{warehouse}", init_catalog_tables="false") +def test_register_table_on_v0_schema(warehouse: Path, metadata_location: str, tmp_path: Path) -> None: + """register_table should work on V0 schema without iceberg_type column.""" + catalog = _make_v0_catalog(f"sqlite:///{warehouse.as_posix()}/test-v0-register", warehouse) + catalog.create_namespace("ns") + with pytest.raises(FileNotFoundError): + catalog.register_table(("ns", "tbl"), str(tmp_path / "missing.metadata.json")) + assert catalog.list_tables("ns") == [] + + assert catalog.register_table(("ns", "tbl"), metadata_location).metadata_location == metadata_location + with pytest.raises(TableAlreadyExistsError): + catalog.register_table(("ns", "tbl"), metadata_location) + + def test_namespace_exists_on_v0_schema(warehouse: Path) -> None: """namespace_exists should not fail on V0 schema (no iceberg_type column).""" catalog = _make_v0_catalog(f"sqlite:///{warehouse.as_posix()}/test-v0-ns-exists", warehouse)