intra_max_chatbot/database/connection.py
2026-03-26 00:25:37 +03:00

30 lines
854 B
Python

import aiosqlite
import os
from pathlib import Path
import config
_db: aiosqlite.Connection | None = None
async def init_db() -> None:
global _db
_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