dzen.nstarikov.ru/app/database.py

64 lines
2.5 KiB
Python
Raw Normal View History

2026-06-27 14:07:10 +03:00
from collections.abc import Generator
from pathlib import Path
from sqlalchemy import create_engine, event
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
from app.config import get_settings
class Base(DeclarativeBase):
pass
settings = get_settings()
Path(settings.sqlite_path).parent.mkdir(parents=True, exist_ok=True)
engine = create_engine(
settings.sqlite_url,
connect_args={"check_same_thread": False},
future=True,
)
@event.listens_for(engine, "connect")
def configure_sqlite(dbapi_connection, _connection_record) -> None:
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA journal_mode=WAL")
cursor.execute("PRAGMA busy_timeout=5000")
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=False)
def init_db() -> None:
from app import models # noqa: F401
Base.metadata.create_all(bind=engine)
with engine.begin() as connection:
post_media_columns = {
row[1] for row in connection.exec_driver_sql("PRAGMA table_info(post_media)").fetchall()
}
if "duration_seconds" not in post_media_columns:
connection.exec_driver_sql("ALTER TABLE post_media ADD COLUMN duration_seconds INTEGER")
if "playlist_title" not in post_media_columns:
connection.exec_driver_sql("ALTER TABLE post_media ADD COLUMN playlist_title TEXT")
post_columns = {row[1] for row in connection.exec_driver_sql("PRAGMA table_info(posts)").fetchall()}
if "content_key" not in post_columns:
connection.exec_driver_sql("ALTER TABLE posts ADD COLUMN content_key VARCHAR(128)")
connection.exec_driver_sql("CREATE INDEX IF NOT EXISTS ix_posts_content_key ON posts (content_key)")
if "publish_lock" not in post_columns:
connection.exec_driver_sql("ALTER TABLE posts ADD COLUMN publish_lock VARCHAR(128)")
connection.exec_driver_sql("CREATE INDEX IF NOT EXISTS ix_posts_publish_lock ON posts (publish_lock)")
video_columns = {row[1] for row in connection.exec_driver_sql("PRAGMA table_info(videos)").fetchall()}
if "upload_lock" not in video_columns:
connection.exec_driver_sql("ALTER TABLE videos ADD COLUMN upload_lock VARCHAR(128)")
connection.exec_driver_sql("CREATE INDEX IF NOT EXISTS ix_videos_upload_lock ON videos (upload_lock)")
def get_session() -> Generator[Session, None, None]:
with SessionLocal() as session:
yield session