138 lines
4.0 KiB
Python
138 lines
4.0 KiB
Python
"""SQLite datová vrstva a verzovaný atomický migrační runner."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import sqlite3
|
|
from pathlib import Path
|
|
|
|
from flask import Flask, current_app, g
|
|
|
|
DEFAULT_MIGRATIONS_DIR = Path(__file__).parent / "migrations"
|
|
BUSY_TIMEOUT_MS = 5000
|
|
|
|
_SCHEMA_MIGRATIONS_DDL = """
|
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
version TEXT PRIMARY KEY,
|
|
applied_at TEXT NOT NULL
|
|
DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
|
|
)
|
|
"""
|
|
|
|
|
|
def _configure_connection(conn: sqlite3.Connection) -> None:
|
|
conn.row_factory = sqlite3.Row
|
|
conn.execute("PRAGMA foreign_keys = ON")
|
|
conn.execute(f"PRAGMA busy_timeout = {BUSY_TIMEOUT_MS}")
|
|
|
|
|
|
def connect(db_path: Path | str) -> sqlite3.Connection:
|
|
"""Otevře SQLite připojení s povinnými pragma nastaveními."""
|
|
conn = sqlite3.connect(str(db_path))
|
|
try:
|
|
_configure_connection(conn)
|
|
except Exception:
|
|
conn.close()
|
|
raise
|
|
return conn
|
|
|
|
|
|
def _has_sql_content(chunk: str) -> bool:
|
|
for line in chunk.splitlines():
|
|
stripped = line.strip()
|
|
if stripped and not stripped.startswith("--"):
|
|
return True
|
|
return False
|
|
|
|
|
|
def split_sql_statements(sql: str) -> list[str]:
|
|
"""Rozdělí SQL skript na jednotlivé úplné příkazy."""
|
|
statements: list[str] = []
|
|
buffer = ""
|
|
for line in sql.splitlines(keepends=True):
|
|
buffer += line
|
|
if sqlite3.complete_statement(buffer):
|
|
if _has_sql_content(buffer):
|
|
statements.append(buffer.strip())
|
|
buffer = ""
|
|
if _has_sql_content(buffer):
|
|
raise sqlite3.OperationalError(
|
|
"Neukončený SQL příkaz v migračním skriptu."
|
|
)
|
|
return statements
|
|
|
|
|
|
def apply_migrations(
|
|
db_path: Path | str,
|
|
migrations_dir: Path | None = None,
|
|
) -> list[str]:
|
|
"""Aplikuje dosud neprovedené SQL migrace atomicky v pořadí názvů."""
|
|
target_dir = (
|
|
DEFAULT_MIGRATIONS_DIR if migrations_dir is None else migrations_dir
|
|
)
|
|
if not target_dir.is_dir():
|
|
raise FileNotFoundError(
|
|
f"Adresář s migracemi neexistuje: {target_dir}"
|
|
)
|
|
|
|
conn = sqlite3.connect(str(db_path), isolation_level=None)
|
|
applied_now: list[str] = []
|
|
try:
|
|
_configure_connection(conn)
|
|
if str(db_path) != ":memory:":
|
|
conn.execute("PRAGMA journal_mode = WAL")
|
|
|
|
conn.execute(_SCHEMA_MIGRATIONS_DDL)
|
|
rows = conn.execute(
|
|
"SELECT version FROM schema_migrations"
|
|
).fetchall()
|
|
applied_versions = {row["version"] for row in rows}
|
|
|
|
for migration_file in sorted(target_dir.glob("*.sql")):
|
|
version = migration_file.name
|
|
if version in applied_versions:
|
|
continue
|
|
|
|
sql = migration_file.read_text(encoding="utf-8")
|
|
statements = split_sql_statements(sql)
|
|
|
|
conn.execute("BEGIN IMMEDIATE")
|
|
try:
|
|
for statement in statements:
|
|
conn.execute(statement)
|
|
conn.execute(
|
|
"INSERT INTO schema_migrations (version) VALUES (?)",
|
|
(version,),
|
|
)
|
|
conn.execute("COMMIT")
|
|
except Exception:
|
|
if conn.in_transaction:
|
|
conn.execute("ROLLBACK")
|
|
raise
|
|
|
|
applied_now.append(version)
|
|
applied_versions.add(version)
|
|
finally:
|
|
conn.close()
|
|
|
|
return applied_now
|
|
|
|
|
|
def get_db() -> sqlite3.Connection:
|
|
"""Vrátí SQLite připojení svázané s aktuálním aplikačním kontextem."""
|
|
if "db" not in g:
|
|
g.db = connect(current_app.config["DB_PATH"])
|
|
return g.db
|
|
|
|
|
|
def close_db(error: BaseException | None = None) -> None:
|
|
"""Uzavře SQLite připojení na konci aplikačního kontextu."""
|
|
del error
|
|
conn = g.pop("db", None)
|
|
if conn is not None:
|
|
conn.close()
|
|
|
|
|
|
def init_app(app: Flask) -> None:
|
|
"""Zaregistruje správu SQLite připojení do Flask aplikace."""
|
|
app.teardown_appcontext(close_db)
|