diff --git a/pyiceberg/catalog/sql.py b/pyiceberg/catalog/sql.py index ff7831d77f..b58d1c94ef 100644 --- a/pyiceberg/catalog/sql.py +++ b/pyiceberg/catalog/sql.py @@ -543,19 +543,21 @@ def drop_namespace(self, namespace: Union[str, Identifier]) -> None: NoSuchNamespaceError: If a namespace with the given name does not exist. NamespaceNotEmptyError: If the namespace is not empty. """ - if self._namespace_exists(namespace): - namespace_str = Catalog.namespace_to_string(namespace) - if tables := self.list_tables(namespace): - raise NamespaceNotEmptyError(f"Namespace {namespace_str} is not empty. {len(tables)} tables exist.") - - with Session(self.engine) as session: - session.execute( - delete(IcebergNamespaceProperties).where( - IcebergNamespaceProperties.catalog_name == self.name, - IcebergNamespaceProperties.namespace == namespace_str, - ) + if not self._namespace_exists(namespace): + raise NoSuchNamespaceError(f"Namespace does not exist: {namespace}") + + namespace_str = Catalog.namespace_to_string(namespace) + if tables := self.list_tables(namespace): + raise NamespaceNotEmptyError(f"Namespace {namespace_str} is not empty. {len(tables)} tables exist.") + + with Session(self.engine) as session: + session.execute( + delete(IcebergNamespaceProperties).where( + IcebergNamespaceProperties.catalog_name == self.name, + IcebergNamespaceProperties.namespace == namespace_str, ) - session.commit() + ) + session.commit() def list_tables(self, namespace: Union[str, Identifier]) -> List[Identifier]: """List tables under the given namespace in the catalog. diff --git a/tests/catalog/test_sql.py b/tests/catalog/test_sql.py index 24adfb88ab..7534a115bf 100644 --- a/tests/catalog/test_sql.py +++ b/tests/catalog/test_sql.py @@ -1093,6 +1093,18 @@ def test_drop_namespace(catalog: SqlCatalog, table_schema_nested: Schema, table_ assert namespace not in catalog.list_namespaces() +@pytest.mark.parametrize( + "catalog", + [ + lazy_fixture("catalog_memory"), + lazy_fixture("catalog_sqlite"), + ], +) +def test_drop_non_existing_namespaces(catalog: SqlCatalog) -> None: + with pytest.raises(NoSuchNamespaceError): + catalog.drop_namespace("does_not_exist") + + @pytest.mark.parametrize( "catalog", [