Initial commit
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
"""Verbindungsaufbau fuer die SQLite-Datenbank."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
from ..utils.logging import get_logger
|
||||
|
||||
logger = get_logger("database")
|
||||
|
||||
|
||||
def connect(db_path: str | Path, *, create: bool = True) -> sqlite3.Connection:
|
||||
"""Oeffnet die Datenbank mit sinnvollen PRAGMAs.
|
||||
|
||||
``create=False`` verhindert, dass versehentlich eine neue Datenbankdatei
|
||||
angelegt wird (z. B. bei reiner Diagnose).
|
||||
"""
|
||||
path = Path(db_path)
|
||||
if not create and not path.exists():
|
||||
raise FileNotFoundError(f"Datenbank nicht gefunden: {path}")
|
||||
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
conn = sqlite3.connect(str(path), timeout=30.0)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.isolation_level = "" # explizite Transaktionen via "with conn:"
|
||||
|
||||
conn.execute("PRAGMA foreign_keys = ON")
|
||||
conn.execute("PRAGMA journal_mode = WAL")
|
||||
conn.execute("PRAGMA synchronous = NORMAL")
|
||||
conn.execute("PRAGMA busy_timeout = 30000")
|
||||
conn.execute("PRAGMA temp_store = MEMORY")
|
||||
|
||||
return conn
|
||||
|
||||
|
||||
def check_fts5(conn: sqlite3.Connection) -> tuple[bool, bool]:
|
||||
"""Prueft, ob FTS5 und der Trigram-Tokenizer verfuegbar sind."""
|
||||
fts5 = False
|
||||
trigram = False
|
||||
try:
|
||||
conn.execute("CREATE VIRTUAL TABLE IF NOT EXISTS _fts_check USING fts5(x)")
|
||||
conn.execute("DROP TABLE IF EXISTS _fts_check")
|
||||
fts5 = True
|
||||
except sqlite3.OperationalError as exc:
|
||||
logger.warning("FTS5 nicht verfuegbar: %s", exc)
|
||||
return False, False
|
||||
|
||||
if fts5:
|
||||
try:
|
||||
conn.execute(
|
||||
"CREATE VIRTUAL TABLE IF NOT EXISTS _trigram_check USING fts5(x, tokenize='trigram')"
|
||||
)
|
||||
conn.execute("DROP TABLE IF EXISTS _trigram_check")
|
||||
trigram = True
|
||||
except sqlite3.OperationalError as exc:
|
||||
logger.warning("FTS5-Trigram-Tokenizer nicht verfuegbar: %s", exc)
|
||||
return fts5, trigram
|
||||
|
||||
|
||||
def sqlite_version() -> str:
|
||||
return sqlite3.sqlite_version
|
||||
Reference in New Issue
Block a user