|
15 | 15 | # specific language governing permissions and limitations |
16 | 16 | # under the License. |
17 | 17 |
|
| 18 | +import gc |
| 19 | +import logging |
| 20 | +import sqlite3 |
| 21 | +import warnings |
18 | 22 | from collections.abc import Generator |
| 23 | +from concurrent.futures import ThreadPoolExecutor |
19 | 24 | from pathlib import Path |
20 | 25 | from typing import cast |
21 | 26 |
|
22 | 27 | import pytest |
23 | | -from sqlalchemy import Engine, create_engine, event, inspect, text |
24 | | -from sqlalchemy.exc import ArgumentError |
| 28 | +from sqlalchemy import Engine, Pool, create_engine, event, inspect, text |
| 29 | +from sqlalchemy.exc import ArgumentError, OperationalError |
| 30 | +from sqlalchemy.pool import QueuePool, SingletonThreadPool |
25 | 31 |
|
26 | 32 | from pyiceberg.catalog import load_catalog |
27 | 33 | from pyiceberg.catalog.sql import ( |
@@ -288,6 +294,128 @@ def test_sql_catalog_multiple_close_calls(self, catalog_sqlite: SqlCatalog) -> N |
288 | 294 | # Second close should not raise an exception |
289 | 295 | catalog_sqlite.close() |
290 | 296 |
|
| 297 | + def test_sql_catalog_cross_thread_sqlite_close(self, warehouse: Path, caplog: pytest.LogCaptureFixture) -> None: |
| 298 | + """Closing a SQLite SqlCatalog on a different thread than the one that created succeeds.""" |
| 299 | + gc.collect() |
| 300 | + |
| 301 | + def create_in_worker() -> SqlCatalog: |
| 302 | + return SqlCatalog("test", uri="sqlite:///:memory:", warehouse=f"file://{warehouse}") |
| 303 | + |
| 304 | + with ThreadPoolExecutor(max_workers=1) as executor: |
| 305 | + catalog = executor.submit(create_in_worker).result() |
| 306 | + |
| 307 | + with warnings.catch_warnings(record=True) as caught_warnings: |
| 308 | + warnings.simplefilter("always", ResourceWarning) |
| 309 | + with caplog.at_level(logging.ERROR, logger="sqlalchemy.pool"): |
| 310 | + catalog.close() |
| 311 | + |
| 312 | + pool_errors = [ |
| 313 | + (record.exc_info[0], str(record.exc_info[1])) |
| 314 | + for record in caplog.records |
| 315 | + if record.exc_info and record.exc_info[0] is not None and record.exc_info[1] is not None |
| 316 | + ] |
| 317 | + caplog.clear() |
| 318 | + del catalog |
| 319 | + gc.collect() |
| 320 | + |
| 321 | + assert pool_errors == [] |
| 322 | + assert [str(w.message) for w in caught_warnings] == [] |
| 323 | + |
| 324 | + |
| 325 | +@pytest.mark.parametrize("uri", ["sqlite:///:memory:", "sqlite+pysqlite:///:memory:"]) |
| 326 | +def test_sql_catalog_sqlite_memory_preserves_thread_isolation( |
| 327 | + warehouse: Path, caplog: pytest.LogCaptureFixture, uri: str |
| 328 | +) -> None: |
| 329 | + """check_same_thread=False keeps SingletonThreadPool isolation, and only affects close and garbage collection.""" |
| 330 | + gc.collect() |
| 331 | + catalog = SqlCatalog("test", uri=uri, warehouse=f"file://{warehouse}") |
| 332 | + assert isinstance(catalog.engine.pool, SingletonThreadPool) |
| 333 | + |
| 334 | + catalog.create_namespace("ns") |
| 335 | + assert catalog.list_namespaces() == [("ns",)] |
| 336 | + |
| 337 | + # worker thread cannot see the main thread DB |
| 338 | + with ThreadPoolExecutor(max_workers=1) as executor: |
| 339 | + with pytest.raises(OperationalError, match="no such table"): |
| 340 | + executor.submit(catalog.list_namespaces).result() |
| 341 | + |
| 342 | + # closing the main thread connection also closes the worker thread's connection |
| 343 | + with warnings.catch_warnings(record=True) as caught_warnings: |
| 344 | + warnings.simplefilter("always", ResourceWarning) |
| 345 | + with caplog.at_level(logging.ERROR, logger="sqlalchemy.pool"): |
| 346 | + catalog.close() |
| 347 | + |
| 348 | + pool_errors = [ |
| 349 | + (record.exc_info[0], str(record.exc_info[1])) |
| 350 | + for record in caplog.records |
| 351 | + if record.exc_info and record.exc_info[0] is not None and record.exc_info[1] is not None |
| 352 | + ] |
| 353 | + caplog.clear() |
| 354 | + del catalog |
| 355 | + gc.collect() |
| 356 | + |
| 357 | + assert pool_errors == [] |
| 358 | + assert [str(w.message) for w in caught_warnings] == [] |
| 359 | + |
| 360 | + |
| 361 | +def test_sql_catalog_sqlite_explicit_check_same_thread_enforced(warehouse: Path, caplog: pytest.LogCaptureFixture) -> None: |
| 362 | + """Explicit check_same_thread=true enforces sqlite3 same-thread checks at runtime during close().""" |
| 363 | + with ThreadPoolExecutor(max_workers=1) as executor: |
| 364 | + |
| 365 | + def create_in_worker() -> tuple[SqlCatalog, sqlite3.Connection]: |
| 366 | + cat = SqlCatalog("test", uri="sqlite:///:memory:?check_same_thread=true", warehouse=f"file://{warehouse}") |
| 367 | + with cat.engine.connect() as conn: |
| 368 | + dbapi_conn = cast(sqlite3.Connection, conn.connection.dbapi_connection) |
| 369 | + return cat, dbapi_conn |
| 370 | + |
| 371 | + strict_catalog, worker_conn = executor.submit(create_in_worker).result() |
| 372 | + try: |
| 373 | + with caplog.at_level(logging.ERROR, logger="sqlalchemy.pool"): |
| 374 | + strict_catalog.close() |
| 375 | + pool_errors = [record.exc_info[0] for record in caplog.records if record.exc_info and record.exc_info[0] is not None] |
| 376 | + caplog.clear() |
| 377 | + assert pool_errors == [sqlite3.ProgrammingError] |
| 378 | + finally: |
| 379 | + executor.submit(worker_conn.close).result() |
| 380 | + |
| 381 | + |
| 382 | +@pytest.mark.parametrize( |
| 383 | + ("uri_template", "expected_pool_type", "expected_cparams"), |
| 384 | + [ |
| 385 | + ("sqlite:///:memory:?check_same_thread=true", SingletonThreadPool, {"check_same_thread": True}), |
| 386 | + ( |
| 387 | + "sqlite:///{warehouse}/sql-catalog-explicit-thread?check_same_thread=true", |
| 388 | + QueuePool, |
| 389 | + {"check_same_thread": True}, |
| 390 | + ), |
| 391 | + ( |
| 392 | + "sqlite:///:memory:?timeout=15&cached_statements=50", |
| 393 | + SingletonThreadPool, |
| 394 | + {"timeout": 15.0, "cached_statements": 50, "check_same_thread": False}, |
| 395 | + ), |
| 396 | + ], |
| 397 | +) |
| 398 | +def test_sql_catalog_sqlite_preserves_explicit_query_params( |
| 399 | + warehouse: Path, |
| 400 | + uri_template: str, |
| 401 | + expected_pool_type: type[Pool], |
| 402 | + expected_cparams: dict[str, object], |
| 403 | +) -> None: |
| 404 | + """Explicit SQLite URI query parameters (including check_same_thread=true) must not be overridden.""" |
| 405 | + uri = uri_template.format(warehouse=warehouse.as_posix()) |
| 406 | + with SqlCatalog("test", uri=uri, warehouse=f"file://{warehouse}") as catalog: |
| 407 | + assert isinstance(catalog.engine.pool, expected_pool_type) |
| 408 | + catalog.engine.dispose() |
| 409 | + seen_cparams: list[dict[str, object]] = [] |
| 410 | + |
| 411 | + @event.listens_for(catalog.engine, "do_connect") |
| 412 | + def capture_cparams(_dialect: object, _conn_rec: object, _cargs: object, cparams: dict[str, object]) -> None: |
| 413 | + seen_cparams.append(dict(cparams)) |
| 414 | + |
| 415 | + with catalog.engine.connect(): |
| 416 | + pass |
| 417 | + assert seen_cparams == [expected_cparams] |
| 418 | + |
291 | 419 |
|
292 | 420 | def get_columns(engine: Engine) -> set[str]: |
293 | 421 | return {c["name"] for c in inspect(engine).get_columns("iceberg_tables")} |
|
0 commit comments