Skip to content

Commit a67ae9f

Browse files
committed
default to check_same_thread=False for (py)sqlite URLs if not specified
1 parent 535425d commit a67ae9f

2 files changed

Lines changed: 141 additions & 4 deletions

File tree

‎pyiceberg/catalog/sql.py‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
union,
3636
update,
3737
)
38+
from sqlalchemy.engine import make_url
3839
from sqlalchemy.exc import IntegrityError, NoResultFound, OperationalError, ProgrammingError
3940
from sqlalchemy.orm import (
4041
DeclarativeBase,
@@ -139,8 +140,16 @@ def __init__(self, name: str, engine: Engine | None = None, **properties: str):
139140
echo_str = str(self.properties.get("echo", DEFAULT_ECHO_VALUE)).lower()
140141
echo = strtobool(echo_str) if echo_str != "debug" else "debug"
141142
pool_pre_ping = strtobool(self.properties.get("pool_pre_ping", DEFAULT_POOL_PRE_PING_VALUE))
142-
143-
self.engine = create_engine(uri_prop, echo=echo, pool_pre_ping=pool_pre_ping)
143+
url = make_url(uri_prop)
144+
connect_args: dict[str, bool] = {}
145+
if (
146+
url.get_backend_name() == "sqlite"
147+
and url.get_driver_name() == "pysqlite"
148+
and "check_same_thread" not in url.query
149+
):
150+
connect_args["check_same_thread"] = False
151+
152+
self.engine = create_engine(url, echo=echo, pool_pre_ping=pool_pre_ping, connect_args=connect_args)
144153

145154
self._init_catalog()
146155

‎tests/catalog/test_sql.py‎

Lines changed: 130 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,19 @@
1515
# specific language governing permissions and limitations
1616
# under the License.
1717

18+
import gc
19+
import logging
20+
import sqlite3
21+
import warnings
1822
from collections.abc import Generator
23+
from concurrent.futures import ThreadPoolExecutor
1924
from pathlib import Path
2025
from typing import cast
2126

2227
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
2531

2632
from pyiceberg.catalog import load_catalog
2733
from pyiceberg.catalog.sql import (
@@ -288,6 +294,128 @@ def test_sql_catalog_multiple_close_calls(self, catalog_sqlite: SqlCatalog) -> N
288294
# Second close should not raise an exception
289295
catalog_sqlite.close()
290296

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+
291419

292420
def get_columns(engine: Engine) -> set[str]:
293421
return {c["name"] for c in inspect(engine).get_columns("iceberg_tables")}

0 commit comments

Comments
 (0)