Implement Alembic for database migrations and update FastAPI initialization

- Integrate Alembic for managing database schema migrations, replacing the previous SQL schema management.
- Update the FastAPI application to synchronize interface definitions at startup.
- Modify the Docker Compose command to run Alembic migrations before starting the API.
- Enhance the Makefile with new commands for database migration and revision management.
- Remove outdated SQL schema and seed files, transitioning to a more dynamic migration approach.
- Add initial migration scripts and configuration for Alembic, ensuring a structured database evolution.
This commit is contained in:
Xin Wang
2026-07-09 16:29:10 +08:00
parent 54329aa516
commit 03b532dd09
16 changed files with 325 additions and 247 deletions

View File

@@ -2,14 +2,13 @@
- engine / SessionLocal:全局单例
- get_session:FastAPI 依赖,按请求注入一个会话
- init_db:启动时建表(MVP 用 create_all;表结构稳定后切 alembic 迁移,对齐 dograh)
- sync_interface_definitions:启动时同步接口定义;表结构由 Alembic 管理
"""
from collections.abc import AsyncGenerator
import json
import config
from db.models import Base
from services.interface_catalog import INTERFACE_DEFINITIONS
from sqlalchemy import text
from sqlalchemy.ext.asyncio import (
@@ -27,15 +26,8 @@ async def get_session() -> AsyncGenerator[AsyncSession, None]:
yield session
async def init_db() -> None:
async def sync_interface_definitions() -> None:
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
await conn.execute(
text(
"ALTER TABLE interface_definitions "
"ALTER COLUMN field_schema TYPE JSONB USING field_schema::jsonb"
)
)
for definition in INTERFACE_DEFINITIONS:
await conn.execute(
text(