diff --git a/pyiceberg/catalog/sql.py b/pyiceberg/catalog/sql.py index a89caff2ed..cb40c109d5 100644 --- a/pyiceberg/catalog/sql.py +++ b/pyiceberg/catalog/sql.py @@ -31,6 +31,7 @@ delete, func, insert, + inspect, select, text, union, @@ -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) diff --git a/tests/catalog/test_sql.py b/tests/catalog/test_sql.py index 3d40cad22b..1c3392608a 100644 --- a/tests/catalog/test_sql.py +++ b/tests/catalog/test_sql.py @@ -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."""