31 lines
921 B
Python
31 lines
921 B
Python
import aiosqlite
|
|
import os
|
|
from pathlib import Path
|
|
|
|
import config
|
|
|
|
_db: aiosqlite.Connection | None = None
|
|
|
|
|
|
async def init_db() -> None:
|
|
global _db
|
|
Path(config.DB_PATH).parent.mkdir(parents=True, exist_ok=True)
|
|
_db = await aiosqlite.connect(config.DB_PATH)
|
|
_db.row_factory = aiosqlite.Row
|
|
await _db.execute("PRAGMA journal_mode=WAL")
|
|
await _db.execute("PRAGMA foreign_keys=ON")
|
|
|
|
schema_path = Path(__file__).parent / "schema.sql"
|
|
schema = schema_path.read_text(encoding="utf-8")
|
|
# Выполняем каждый оператор отдельно
|
|
for statement in schema.split(";"):
|
|
stmt = statement.strip()
|
|
if stmt and not stmt.startswith("PRAGMA"):
|
|
await _db.execute(stmt)
|
|
await _db.commit()
|
|
|
|
|
|
def get_db() -> aiosqlite.Connection:
|
|
if _db is None:
|
|
raise RuntimeError("Database not initialized. Call init_db() first.")
|
|
return _db
|