intra_max_chatbot/database/connection.py

43 lines
1.5 KiB
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()
# ── Миграции для существующих БД ─────────────────────────────────────────
# Добавляем intradesk_id в organizations, если ещё нет
try:
await _db.execute("ALTER TABLE organizations ADD COLUMN intradesk_id INTEGER")
await _db.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS idx_orgs_intradesk_id "
"ON organizations(intradesk_id)"
)
await _db.commit()
except Exception:
pass # колонка уже существует
def get_db() -> aiosqlite.Connection:
if _db is None:
raise RuntimeError("Database not initialized. Call init_db() first.")
return _db