diff --git a/pyiceberg/catalog/memory.py b/pyiceberg/catalog/memory.py index 024d14fba6..207052aca8 100644 --- a/pyiceberg/catalog/memory.py +++ b/pyiceberg/catalog/memory.py @@ -15,6 +15,9 @@ # specific language governing permissions and limitations # under the License. +from sqlalchemy import Engine, create_engine +from sqlalchemy.pool import StaticPool + from pyiceberg.catalog import URI from pyiceberg.catalog.sql import SqlCatalog @@ -26,8 +29,10 @@ class InMemoryCatalog(SqlCatalog): This is useful for test, demo, and playground but not in production as it does not support concurrent access. """ - def __init__(self, name: str, warehouse: str = "file:///tmp/iceberg/warehouse", **kwargs: str) -> None: + def __init__( + self, name: str, warehouse: str = "file:///tmp/iceberg/warehouse", engine: Engine | None = None, **kwargs: str + ) -> None: self._warehouse_location = warehouse - if URI not in kwargs: - kwargs[URI] = "sqlite:///:memory:" - super().__init__(name=name, warehouse=warehouse, **kwargs) + if engine is None and URI not in kwargs: + engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False}) + super().__init__(name=name, engine=engine, warehouse=warehouse, **kwargs) diff --git a/tests/catalog/test_base.py b/tests/catalog/test_base.py index 1a47478313..9585a93df5 100644 --- a/tests/catalog/test_base.py +++ b/tests/catalog/test_base.py @@ -17,7 +17,11 @@ # pylint:disable=redefined-outer-name +import gc +import logging +import warnings from collections.abc import Generator +from concurrent.futures import ThreadPoolExecutor from pathlib import PosixPath import pytest @@ -88,3 +92,34 @@ def test_in_memory_catalog_context_manager(self, catalog: InMemoryCatalog) -> No # InMemoryCatalog inherits close from SqlCatalog, so engine should be disposed assert hasattr(cat, "engine") + + def test_in_memory_catalog_cross_thread_use_and_close(self, tmp_path: PosixPath, caplog: pytest.LogCaptureFixture) -> None: + """An InMemoryCatalog created in a worker thread can be used and closed cleanly on the main thread.""" + gc.collect() + + def create_in_worker() -> InMemoryCatalog: + cat = InMemoryCatalog("test", warehouse=tmp_path.absolute().as_posix()) + cat.create_namespace("ns") + return cat + + with ThreadPoolExecutor(max_workers=1) as executor: + catalog = executor.submit(create_in_worker).result() + assert executor.submit(catalog.list_namespaces).result() == [("ns",)] + + assert catalog.list_namespaces() == [("ns",)] + + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.simplefilter("always", ResourceWarning) + with caplog.at_level(logging.ERROR, logger="sqlalchemy.pool"): + catalog.close() + + pool_errors = [ + (record.exc_info[0], str(record.exc_info[1])) + for record in caplog.records + if record.exc_info and record.exc_info[0] is not None and record.exc_info[1] is not None + ] + del catalog + gc.collect() + + assert pool_errors == [] + assert [str(w.message) for w in caught_warnings] == []