import os from sqlalchemy import create_engine, event from sqlalchemy.orm import sessionmaker, scoped_session from .config import DATA_DIR DB_PATH = os.path.join(DATA_DIR, "sougouwiki.db") DATABASE_URL = f"sqlite:///{DB_PATH}" # Now that we run on local ephemeral disk (NOT tmpfs and NOT FUSE), # we can safely use WAL mode for high performance. engine = create_engine( DATABASE_URL, echo=False, connect_args={"check_same_thread": False, "timeout": 30} ) @event.listens_for(engine, "connect") def set_sqlite_pragma(dbapi_connection, connection_record): cursor = dbapi_connection.cursor() # WAL mode is perfect for "Crawler writing, API reading" cursor.execute("PRAGMA journal_mode=WAL") cursor.execute("PRAGMA synchronous=NORMAL") cursor.execute("PRAGMA busy_timeout=30000") cursor.close() SessionLocal = scoped_session(sessionmaker(bind=engine)) def init_db(): from .models import Base Base.metadata.create_all(engine) def get_session(): return SessionLocal()