88from tempfile import TemporaryDirectory
99from typing import Any , Callable , Literal , Union , overload
1010
11+ from . import warnings
1112from .common import PathIsh
1213from .compat import assert_never
1314
@@ -44,13 +45,19 @@ def dict_factory(cursor, row):
4445
4546
4647@contextmanager
47- def sqlite_connection (db : PathIsh , * , immutable : bool = False , row_factory : Factory | None = None ) -> Iterator [sqlite3 .Connection ]:
48- dbp = f'file:{ db } '
48+ def sqlite_connection (
49+ db : PathIsh ,
50+ * ,
51+ immutable : bool = False ,
52+ row_factory : Factory | None = None ,
53+ _via_apsw : bool = False , # NOTE: experimental for now
54+ ) -> Iterator [sqlite3 .Connection ]:
55+ uri = f'file:{ db } '
4956 # https://www.sqlite.org/draft/uri.html#uriimmutable
5057 if immutable :
5158 # assert results in nicer error than sqlite3.OperationalError
5259 assert Path (db ).exists (), db
53- dbp = f'{ dbp } ?immutable=1'
60+ uri = f'{ uri } ?immutable=1'
5461 row_factory_ : Any = None
5562 if row_factory is not None :
5663 if callable (row_factory ):
@@ -62,7 +69,25 @@ def sqlite_connection(db: PathIsh, *, immutable: bool = False, row_factory: Fact
6269 else :
6370 assert_never (row_factory ) # ty: ignore[type-assertion-failure]
6471
65- conn = sqlite3 .connect (dbp , uri = True )
72+
73+ if _via_apsw :
74+ try :
75+ # for now, defensive, will see later how to do it properly
76+ import apsw # type: ignore[import-not-found,unused-ignore] # ty: ignore[unresolved-import]
77+ except ImportError :
78+ warnings .high ('apsw is not installed, falling back to sqlite' )
79+ else :
80+ assert row_factory is None , "row_factory is not supported with apsw (yet?)"
81+
82+ apsw_conn = apsw .Connection (uri , flags = apsw .SQLITE_OPEN_READONLY | apsw .SQLITE_OPEN_URI )
83+ try :
84+ with apsw_conn :
85+ yield apsw_conn # type: ignore[misc,unused-ignore]
86+ finally :
87+ apsw_conn .close ()
88+ return
89+
90+ conn = sqlite3 .connect (uri , uri = True )
6691 try :
6792 conn .row_factory = row_factory_
6893 with conn :
0 commit comments