Files
NovalRedot/backend/app/database.py

36 lines
1.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
from pathlib import Path
from sqlalchemy import text
from sqlmodel import SQLModel, Session, create_engine
# 数据目录优先使用环境变量Docker 中设为 /app/data否则用 backend/data/
DATA_DIR = Path(os.environ.get("NOVAL_DATA_DIR", Path(__file__).resolve().parent.parent / "data"))
DATA_DIR.mkdir(exist_ok=True)
DATABASE_URL = f"sqlite:///{DATA_DIR / 'noval.db'}"
engine = create_engine(DATABASE_URL, echo=False)
def init_db() -> None:
SQLModel.metadata.create_all(engine)
_migrate_outline_parent_id()
def _migrate_outline_parent_id() -> None:
"""迁移:为 outline 表添加 parent_id 列(如果尚不存在)"""
with Session(engine) as session:
# 检查 outline 表是否存在 parent_id 列
result = session.exec(text("PRAGMA table_info(outline)"))
columns = [row[1] for row in result]
if "parent_id" not in columns:
session.exec(text("ALTER TABLE outline ADD COLUMN parent_id INTEGER REFERENCES outline(id)"))
session.exec(text("CREATE INDEX IF NOT EXISTS ix_outline_parent_id ON outline(parent_id)"))
session.commit()
def get_session():
with Session(engine) as session:
yield session