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
20 changes: 12 additions & 8 deletions pyiceberg/catalog/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from __future__ import annotations

import logging
from collections.abc import Iterable
from typing import (
TYPE_CHECKING,
Any,
Expand Down Expand Up @@ -573,31 +574,34 @@ def namespace_exists(self, identifier: str | Identifier) -> bool:

with Session(self.engine) as session:
stmt = (
select(IcebergTables)
select(IcebergTables.table_namespace)
.where(
IcebergTables.catalog_name == self.name,
(IcebergTables.table_namespace == namespace)
| (IcebergTables.table_namespace.like(namespace_starts_with, escape="!")),
)
.limit(1)
.distinct()
)
result = session.execute(stmt).all()
if result:
if self._contains_namespace(session.scalars(stmt), namespace):
return True
stmt = (
select(IcebergNamespaceProperties)
select(IcebergNamespaceProperties.namespace)
.where(
IcebergNamespaceProperties.catalog_name == self.name,
(IcebergNamespaceProperties.namespace == namespace)
| (IcebergNamespaceProperties.namespace.like(namespace_starts_with, escape="!")),
)
.limit(1)
.distinct()
)
result = session.execute(stmt).all()
if result:
if self._contains_namespace(session.scalars(stmt), namespace):
return True
return False

@staticmethod
def _contains_namespace(candidates: Iterable[str], namespace: str) -> bool:
# LIKE is case-insensitive on some backends (e.g. SQLite), so re-check the prefix match
return any(candidate == namespace or candidate.startswith(f"{namespace}.") for candidate in candidates)

@override
def create_namespace(self, namespace: str | Identifier, properties: Properties = EMPTY_DICT) -> None:
"""Create a namespace in the catalog.
Expand Down
3 changes: 3 additions & 0 deletions tests/catalog/test_catalog_behaviors.py
Original file line number Diff line number Diff line change
Expand Up @@ -1046,6 +1046,9 @@ 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")


# Namespace properties
Expand Down
Loading