- Introduce a new model structure for managing interface definitions and model resources, enhancing the backend's capability to handle various service integrations. - Update the Makefile to reflect changes in database seeding and resource management commands. - Remove the deprecated credentials management routes and replace them with a unified model registry API. - Modify existing routes and schemas to align with the new model structure, ensuring seamless integration with the frontend. - Enhance database seeding scripts to populate new model resources and their configurations. - Update README documentation to reflect the new architecture and usage instructions for model resources and interface definitions.
56 lines
2.0 KiB
Python
56 lines
2.0 KiB
Python
"""异步数据库引擎 + 会话。
|
|
|
|
- engine / SessionLocal:全局单例
|
|
- get_session:FastAPI 依赖,按请求注入一个会话
|
|
- init_db:启动时建表(MVP 用 create_all;表结构稳定后切 alembic 迁移,对齐 dograh)
|
|
"""
|
|
|
|
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 (
|
|
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 init_db() -> 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(
|
|
"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"]}),
|
|
},
|
|
)
|