Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion pyiceberg/catalog/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -329,14 +332,22 @@ 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)))
session.commit()
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:
Expand Down
25 changes: 25 additions & 0 deletions tests/catalog/test_catalog_behaviors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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


Expand Down
52 changes: 52 additions & 0 deletions tests/catalog/test_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
Loading