Newer
Older
hard-panel / panel / backend / app / db.py
import json
from pathlib import Path

import aiosqlite

from app.config import get_settings

_conn: aiosqlite.Connection | None = None


async def init_db() -> None:
    """Открыть БД, включить WAL, применить schema.sql."""
    global _conn
    settings = get_settings()
    settings.database_path.parent.mkdir(parents=True, exist_ok=True)
    _conn = await aiosqlite.connect(settings.database_path)
    _conn.row_factory = aiosqlite.Row
    await _conn.execute("PRAGMA journal_mode=WAL")
    await _conn.execute("PRAGMA foreign_keys=ON")
    schema = (Path(__file__).with_name("schema.sql")).read_text(encoding="utf-8")
    await _conn.executescript(schema)
    await _conn.commit()


async def close_db() -> None:
    global _conn
    if _conn is not None:
        await _conn.close()
        _conn = None


def get_db() -> aiosqlite.Connection:
    assert _conn is not None, "database not initialized"
    return _conn


def j(value) -> str:
    """Сериализация JSON-колонок."""
    return json.dumps(value, ensure_ascii=False)