feat(db): P2 摘除运行时种子 + 脚本化迁移/种子(migrate.py/seed.py)
- Database.initialize() 不再 create_all/seed_data:运行时仅做库连通检查(不建表不灌种子)。 - 新增 scripts/db/migrate.py(封装 alembic upgrade/downgrade)、scripts/db/seed.py(非运行态灌平台种子)。 - 新增 serverdata/seed/(README) 存放种子 JSON。 - 迁移/种子流程:uv run python scripts/db/migrate.py + scripts/db/seed.py,再启动应用。 - 已知待修:seed 内 AGENT_SEED 全局固定 id 唯一冲突(既有缺陷, 待 P2 后续修);pine/角色已能灌入。
This commit is contained in:
@@ -1857,21 +1857,13 @@ class Database:
|
||||
self.stats = StatsRepository(self.session)
|
||||
|
||||
async def initialize(self) -> None:
|
||||
"""建表(本实例的 engine)+ 幂等种子(roles 空时才写)。"""
|
||||
from .db import Base
|
||||
from .seed import seed_data
|
||||
|
||||
"""运行时仅保活:不建表、不灌种子(迁移/种子一律走 alembic + scripts/db/seed.py)。
|
||||
仅做一次连通性检查,确保库可达。"""
|
||||
if self._engine is not None:
|
||||
async with self._engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
# 种子容错:个别幂等保护不严的地方(如 demo 用户固定 agent id)可能触发唯一冲突,
|
||||
# 不能让种子失败拖垮 lifespan 建库,否则 app.state.db 未设置→全部 500。
|
||||
try:
|
||||
await seed_data(self.session)
|
||||
except Exception as e: # noqa: BLE001
|
||||
import logging
|
||||
logging.getLogger("servercore").warning("种子数据写入失败(忽略,应用仍可用): %s", e)
|
||||
await self.session.rollback()
|
||||
from sqlalchemy import text
|
||||
async with self._engine.connect() as conn:
|
||||
await conn.execute(text("SELECT 1"))
|
||||
# 建表/种子:由 alembic upgrade + scripts/db/seed.py 在非运行态执行,禁止运行时注入。
|
||||
|
||||
async def close(self) -> None:
|
||||
if self._owns_session:
|
||||
|
||||
Reference in New Issue
Block a user