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
9 changes: 8 additions & 1 deletion pyiceberg/catalog/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
delete,
func,
insert,
inspect,
select,
text,
union,
Expand Down Expand Up @@ -203,7 +204,13 @@ def _init_catalog(self) -> None:
self._schema_version = "v0"

def create_tables(self) -> None:
SqlCatalogBaseTable.metadata.create_all(self.engine)
for table in SqlCatalogBaseTable.metadata.sorted_tables:
try:
table.create(self.engine, checkfirst=True)
except (OperationalError, ProgrammingError, IntegrityError):
# The table may have been created concurrently by another process, as in Java's JdbcCatalog.
if not inspect(self.engine).has_table(table.name):
raise

def destroy_tables(self) -> None:
SqlCatalogBaseTable.metadata.drop_all(self.engine)
Expand Down
26 changes: 26 additions & 0 deletions tests/catalog/test_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,32 @@ def test_creation_when_all_tables_exists(alchemy_engine: Engine, catalog_name: s
confirm_all_tables_exist(catalog)


def test_creation_when_tables_are_created_concurrently(alchemy_engine: Engine, catalog_name: str, catalog_uri: str) -> None:
confirm_no_tables_exist(alchemy_engine)

# Another process opening the same new catalog creates the tables after the catalog has
# checked that they are absent, but before it issues CREATE TABLE.
created_elsewhere = False

def create_tables_elsewhere(*args: object, **kwargs: object) -> None:
nonlocal created_elsewhere
if not created_elsewhere:
created_elsewhere = True
SqlCatalogBaseTable.metadata.create_all(bind=create_engine(catalog_uri))

tables = SqlCatalogBaseTable.metadata.sorted_tables
for table in tables:
event.listen(table, "before_create", create_tables_elsewhere)
try:
catalog = load_catalog_for_catalog_table_creation(catalog_name=catalog_name, catalog_uri=catalog_uri)
finally:
for table in tables:
event.remove(table, "before_create", create_tables_elsewhere)

assert created_elsewhere
confirm_all_tables_exist(catalog)


class TestSqlCatalogClose:
"""Test SqlCatalog close functionality."""

Expand Down
Loading