- 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.
48 lines
1.7 KiB
Python
48 lines
1.7 KiB
Python
"""异步数据库引擎 + 会话。
|
|
|
|
- engine / SessionLocal:全局单例
|
|
- get_session:FastAPI 依赖,按请求注入一个会话
|
|
- sync_interface_definitions:启动时同步接口定义;表结构由 Alembic 管理
|
|
"""
|
|
|
|
from collections.abc import AsyncGenerator
|
|
import json
|
|
|
|
import config
|
|
from services.interface_catalog import INTERFACE_DEFINITIONS
|
|
from sqlalchemy import text
|
|
from sqlalchemy.ext.asyncio import (
|
|
AsyncSession,
|
|
async_sessionmaker,
|
|
create_async_engine,
|
|
)
|
|
|
|
engine = create_async_engine(config.DATABASE_URL, echo=False, pool_pre_ping=True)
|
|
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
|
|
|
|
|
|
async def get_session() -> AsyncGenerator[AsyncSession, None]:
|
|
async with SessionLocal() as session:
|
|
yield session
|
|
|
|
|
|
async def sync_interface_definitions() -> None:
|
|
async with engine.begin() as conn:
|
|
for definition in INTERFACE_DEFINITIONS:
|
|
await conn.execute(
|
|
text(
|
|
"INSERT INTO interface_definitions "
|
|
"(interface_type, name, capability, field_schema, enabled, version) "
|
|
"VALUES (:interface_type, :name, :capability, CAST(:field_schema AS jsonb), TRUE, 1) "
|
|
"ON CONFLICT (interface_type) DO UPDATE SET "
|
|
"name = EXCLUDED.name, capability = EXCLUDED.capability, "
|
|
"field_schema = EXCLUDED.field_schema, enabled = TRUE, updated_at = now()"
|
|
),
|
|
{
|
|
"interface_type": definition["interface_type"],
|
|
"name": definition["name"],
|
|
"capability": definition["capability"],
|
|
"field_schema": json.dumps({"fields": definition["fields"]}),
|
|
},
|
|
)
|