Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download sinetti_data_reads/sqlite_connect.py from Couscouskabyle/iscc-app: direct link, hf CLI and curl.
- Browser
- Download file 2.01 kB
-
https://huggingface.co/spaces/Couscouskabyle/iscc-app/resolve/main/sinetti_data_reads/sqlite_connect.py
- Command line
-
hf download hf://spaces/Couscouskabyle/iscc-app/sinetti_data_reads/sqlite_connect.py
-
curl -L -o sqlite_connect.py https://huggingface.co/spaces/Couscouskabyle/iscc-app/resolve/main/sinetti_data_reads/sqlite_connect.py
2.01 kB
| """Shared SQLite connection helpers (SIN-1114). | |
| Two shapes cover the repeated ``sqlite3.connect(`` call sites: | |
| * ``connect_readonly`` opens ``file:<posix path>?mode=ro`` through a URI; the file must exist. | |
| * ``connect_readwrite`` opens a plain file with an explicit busy timeout applied twice, the | |
| pattern most stores repeat: the ``timeout`` argument of ``sqlite3.connect`` and | |
| ``PRAGMA busy_timeout``. | |
| Neither helper touches journal mode, synchronous level or isolation level, so adopting a call | |
| site never changes how it commits. A site whose settings differ (other pragmas, another | |
| isolation level, no busy timeout) keeps its own ``sqlite3.connect``. | |
| """ | |
| from __future__ import annotations | |
| import sqlite3 | |
| from pathlib import Path | |
| DEFAULT_BUSY_TIMEOUT_MS = 5000 | |
| def connect_readonly(path: str | Path, *, row_factory: object | None = sqlite3.Row) -> sqlite3.Connection: | |
| """Open an existing database read-only; raises ``FileNotFoundError`` when it is missing.""" | |
| database = Path(path) | |
| if not database.exists(): | |
| raise FileNotFoundError(database) | |
| connection = sqlite3.connect(f"file:{database.as_posix()}?mode=ro", uri=True) | |
| if row_factory is not None: | |
| connection.row_factory = row_factory # type: ignore[assignment] | |
| return connection | |
| def connect_readwrite( | |
| path: str | Path, | |
| *, | |
| busy_timeout_ms: int = DEFAULT_BUSY_TIMEOUT_MS, | |
| row_factory: object | None = None, | |
| create_parent: bool = False, | |
| ) -> sqlite3.Connection: | |
| """Open a database for reading and writing with a busy timeout of ``busy_timeout_ms``.""" | |
| database = Path(path) | |
| if create_parent: | |
| database.parent.mkdir(parents=True, exist_ok=True) | |
| connection = sqlite3.connect(database, timeout=busy_timeout_ms / 1000) | |
| connection.execute(f"PRAGMA busy_timeout={int(busy_timeout_ms)}") | |
| if row_factory is not None: | |
| connection.row_factory = row_factory # type: ignore[assignment] | |
| return connection | |