61 lines
1.8 KiB
Python
61 lines
1.8 KiB
Python
"""数据库配置"""
|
|
from sqlalchemy import create_engine, text
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
from .config import DATABASE_URL
|
|
|
|
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
Base = declarative_base()
|
|
|
|
|
|
def get_db():
|
|
"""获取数据库会话"""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def _migrate_db():
|
|
"""简单的数据库迁移:为旧表添加缺失的列"""
|
|
migrations = [
|
|
("tasks", "branch", "VARCHAR DEFAULT 'main'"),
|
|
("tasks", "error_category", "VARCHAR"),
|
|
]
|
|
with engine.connect() as conn:
|
|
for table, column, col_type in migrations:
|
|
try:
|
|
conn.execute(text(f"ALTER TABLE {table} ADD COLUMN {column} {col_type}"))
|
|
conn.commit()
|
|
except Exception:
|
|
pass # 列已存在则忽略
|
|
|
|
|
|
def _seed_admin():
|
|
"""初始化管理员账号(从 .env 配置)"""
|
|
from .models import User
|
|
from .config import ADMIN_USERNAME, ADMIN_PASSWORD
|
|
import hashlib
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
if not db.query(User).filter(User.username == ADMIN_USERNAME).first():
|
|
pw_hash = hashlib.sha256(ADMIN_PASSWORD.encode()).hexdigest()
|
|
db.add(User(id="admin-001", username=ADMIN_USERNAME, password_hash=pw_hash, is_admin=True))
|
|
db.commit()
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def init_db():
|
|
"""初始化数据库"""
|
|
# Load model declarations before create_all so a standalone startup creates every table.
|
|
from . import models # noqa: F401
|
|
|
|
Base.metadata.create_all(bind=engine)
|
|
_migrate_db()
|
|
_seed_admin()
|