67 lines
1.7 KiB
Python
67 lines
1.7 KiB
Python
"""数据库引擎与会话管理"""
|
|
|
|
from pathlib import Path
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker, declarative_base
|
|
|
|
DB_PATH = Path(__file__).parent.parent.parent / "data" / "web.db"
|
|
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
engine = create_engine(
|
|
f"sqlite:///{DB_PATH}",
|
|
connect_args={"check_same_thread": False},
|
|
echo=False,
|
|
)
|
|
|
|
SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)
|
|
Base = declarative_base()
|
|
|
|
|
|
def get_db():
|
|
"""FastAPI 依赖:提供数据库会话,请求结束自动关闭。"""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def init_db():
|
|
"""建表 + 写入初始数据。"""
|
|
Base.metadata.create_all(bind=engine)
|
|
_migrate()
|
|
_seed()
|
|
|
|
|
|
def _migrate():
|
|
"""数据库迁移:为已有表添加新列。"""
|
|
from sqlalchemy import text
|
|
with engine.connect() as conn:
|
|
# 检查 accounts.tag 列是否存在
|
|
result = conn.execute(text("PRAGMA table_info(accounts)"))
|
|
columns = [row[1] for row in result]
|
|
if 'tag' not in columns:
|
|
conn.execute(text("ALTER TABLE accounts ADD COLUMN tag VARCHAR(64) DEFAULT ''"))
|
|
conn.commit()
|
|
|
|
|
|
def _seed():
|
|
"""写入默认超管账号和角色。"""
|
|
from .models import User
|
|
from .security import hash_password
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
if not db.query(User).first():
|
|
admin = User(
|
|
username="admin",
|
|
password_hash=hash_password("admin123"),
|
|
role="super_admin",
|
|
is_active=True,
|
|
remark="默认超级管理员",
|
|
)
|
|
db.add(admin)
|
|
db.commit()
|
|
finally:
|
|
db.close()
|