diff --git a/pyiceberg/catalog/sql.py b/pyiceberg/catalog/sql.py index d2c34a692e..a89caff2ed 100644 --- a/pyiceberg/catalog/sql.py +++ b/pyiceberg/catalog/sql.py @@ -29,6 +29,7 @@ String, create_engine, delete, + func, insert, select, text, @@ -576,13 +577,19 @@ def namespace_exists(self, identifier: str | Identifier) -> bool: namespace = Catalog.namespace_to_string(namespace_tuple, NoSuchNamespaceError) namespace_starts_with = namespace.replace("!", "!!").replace("_", "!_").replace("%", "!%") + ".%" + # LIKE keeps the lookup index-friendly but is case-insensitive on some backends (e.g. SQLite), + # so the prefix is also compared with "=", which follows the same rules as the exact lookups + prefix = f"{namespace}." with Session(self.engine) as session: stmt = ( select(IcebergTables) .where( IcebergTables.catalog_name == self.name, (IcebergTables.table_namespace == namespace) - | (IcebergTables.table_namespace.like(namespace_starts_with, escape="!")), + | ( + IcebergTables.table_namespace.like(namespace_starts_with, escape="!") + & (func.substr(IcebergTables.table_namespace, 1, len(prefix)) == prefix) + ), ) .limit(1) ) @@ -594,7 +601,10 @@ def namespace_exists(self, identifier: str | Identifier) -> bool: .where( IcebergNamespaceProperties.catalog_name == self.name, (IcebergNamespaceProperties.namespace == namespace) - | (IcebergNamespaceProperties.namespace.like(namespace_starts_with, escape="!")), + | ( + IcebergNamespaceProperties.namespace.like(namespace_starts_with, escape="!") + & (func.substr(IcebergNamespaceProperties.namespace, 1, len(prefix)) == prefix) + ), ) .limit(1) ) diff --git a/tests/catalog/test_catalog_behaviors.py b/tests/catalog/test_catalog_behaviors.py index ebc6c03ff8..ca9dfd9ac5 100644 --- a/tests/catalog/test_catalog_behaviors.py +++ b/tests/catalog/test_catalog_behaviors.py @@ -1305,6 +1305,21 @@ def test_namespace_exists(catalog: Catalog) -> None: assert not catalog.namespace_exists("db_") # make sure '%' is escaped in the query assert not catalog.namespace_exists("db%") + # namespaces are case-sensitive, also when matching a parent namespace + assert not catalog.namespace_exists("DB2") + assert not catalog.namespace_exists("db3.NS1") + + +def test_parent_namespace_match_is_case_sensitive(catalog: Catalog, table_schema_simple: Schema) -> None: + # https://github.com/apache/iceberg-python/issues/4163: with only `sales.eu`, `SALES` must not be treated as existing + catalog.create_namespace(("sales", "eu")) + + with pytest.raises(NoSuchNamespaceError): + catalog.create_table(("SALES", "orders"), table_schema_simple) + + catalog.create_namespace("SALES") + assert catalog.namespace_exists("SALES") + assert catalog.namespace_exists("sales") # Namespace properties