49 lines
1.4 KiB
Python
49 lines
1.4 KiB
Python
"""SQLite 连接。开启 WAL,供 Web 和 Worker 同时读取。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
from collections.abc import Generator
|
|
from pathlib import Path
|
|
|
|
from sqlalchemy import create_engine, event
|
|
from sqlalchemy.orm import Session, sessionmaker
|
|
|
|
def database_url() -> str:
|
|
path = os.environ.get("EUNIV_DB_PATH", "data/euniv.db")
|
|
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
|
return "sqlite:///" + path.replace("\\", "/")
|
|
|
|
|
|
engine = create_engine(database_url(), connect_args={"check_same_thread": False})
|
|
SessionLocal = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False)
|
|
|
|
|
|
@event.listens_for(engine, "connect")
|
|
def _enable_wal(dbapi_connection, _connection_record) -> None:
|
|
cursor = dbapi_connection.cursor()
|
|
cursor.execute("PRAGMA journal_mode=WAL")
|
|
cursor.execute("PRAGMA busy_timeout=5000")
|
|
cursor.close()
|
|
|
|
|
|
def init_db() -> None:
|
|
from pathlib import Path
|
|
|
|
from alembic import command
|
|
from alembic.config import Config
|
|
|
|
root = Path(__file__).resolve().parents[1]
|
|
config = Config(str(root / "alembic.ini"))
|
|
config.set_main_option("script_location", str(root / "alembic"))
|
|
config.set_main_option("sqlalchemy.url", database_url())
|
|
command.upgrade(config, "head")
|
|
|
|
|
|
def get_db() -> Generator[Session, None, None]:
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|