Skip to content

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

pyiceberg/catalog/sql.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -497,10 +497,16 @@ def commit_table(
497497
def _namespace_exists(self, identifier: Union[str, Identifier]) -> bool:
498498
namespace_tuple = Catalog.identifier_to_tuple(identifier)
499499
namespace = Catalog.namespace_to_string(namespace_tuple, NoSuchNamespaceError)
500+
namespace_starts_with = namespace.replace("!", "!!").replace("_", "!_").replace("%", "!%") + ".%"
501+
500502
with Session(self.engine) as session:
501503
stmt = (
502504
select(IcebergTables)
503-
.where(IcebergTables.catalog_name == self.name, IcebergTables.table_namespace == namespace)
505+
.where(
506+
IcebergTables.catalog_name == self.name,
507+
(IcebergTables.table_namespace == namespace)
508+
| (IcebergTables.table_namespace.like(namespace_starts_with, escape="!")),
509+
)
504510
.limit(1)
505511
)
506512
result = session.execute(stmt).all()
@@ -510,7 +516,8 @@ def _namespace_exists(self, identifier: Union[str, Identifier]) -> bool:
510516
select(IcebergNamespaceProperties)
511517
.where(
512518
IcebergNamespaceProperties.catalog_name == self.name,
513-
IcebergNamespaceProperties.namespace == namespace,
519+
(IcebergNamespaceProperties.namespace == namespace)
520+
| (IcebergNamespaceProperties.namespace.like(namespace_starts_with, escape="!")),
514521
)
515522
.limit(1)
516523
)

tests/catalog/test_sql.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1110,6 +1110,24 @@ def test_create_namespace_with_empty_identifier(catalog: SqlCatalog, empty_names
11101110
catalog.create_namespace(empty_namespace)
11111111

11121112

1113+
@pytest.mark.parametrize(
1114+
"catalog",
1115+
[
1116+
lazy_fixture("catalog_memory"),
1117+
lazy_fixture("catalog_sqlite"),
1118+
],
1119+
)
1120+
def test_namespace_exists(catalog: SqlCatalog) -> None:
1121+
for ns in [("db1",), ("db1", "ns1"), ("db2", "ns1"), ("db3", "ns1", "ns2")]:
1122+
catalog.create_namespace(ns)
1123+
assert catalog._namespace_exists(ns)
1124+
1125+
assert catalog._namespace_exists("db2") # `db2` exists because `db2.ns1` exists
1126+
assert catalog._namespace_exists("db3.ns1") # `db3.ns1` exists because `db3.ns1.ns2` exists
1127+
assert not catalog._namespace_exists("db_") # make sure '_' is escaped in the query
1128+
assert not catalog._namespace_exists("db%") # make sure '%' is escaped in the query
1129+
1130+
11131131
@pytest.mark.parametrize(
11141132
"catalog",
11151133
[

0 commit comments

Comments
 (0)