2026-06-27 14:07:10 +03:00
|
|
|
from collections.abc import Generator
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
2026-08-15 14:21:59 +03:00
|
|
|
from sqlalchemy import create_engine, event, text
|
2026-06-27 14:07:10 +03:00
|
|
|
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)
|
2026-08-15 14:21:59 +03:00
|
|
|
migrate_db()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def migrate_db() -> None:
|
|
|
|
|
migrations = {
|
|
|
|
|
"videos": {
|
|
|
|
|
"thumbnail_url": "TEXT NOT NULL DEFAULT ''",
|
|
|
|
|
"progress_percent": "INTEGER NOT NULL DEFAULT 0",
|
|
|
|
|
"progress_stage": "TEXT NOT NULL DEFAULT ''",
|
|
|
|
|
"progress_log": "TEXT NOT NULL DEFAULT ''",
|
|
|
|
|
},
|
|
|
|
|
"articles": {
|
|
|
|
|
"feature_image_url": "TEXT NOT NULL DEFAULT ''",
|
|
|
|
|
},
|
|
|
|
|
}
|
2026-06-27 14:07:10 +03:00
|
|
|
with engine.begin() as connection:
|
2026-08-15 14:21:59 +03:00
|
|
|
for table, columns in migrations.items():
|
|
|
|
|
existing = {
|
|
|
|
|
row[1]
|
|
|
|
|
for row in connection.execute(text(f"PRAGMA table_info({table})")).fetchall()
|
|
|
|
|
}
|
|
|
|
|
for column, definition in columns.items():
|
|
|
|
|
if column not in existing:
|
|
|
|
|
connection.execute(text(f"ALTER TABLE {table} ADD COLUMN {column} {definition}"))
|
2026-06-27 14:07:10 +03:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_session() -> Generator[Session, None, None]:
|
|
|
|
|
with SessionLocal() as session:
|
|
|
|
|
yield session
|