2026-06-08 13:51:28 +08:00
|
|
|
"""异步数据库引擎 + 会话。
|
|
|
|
|
|
|
|
|
|
- engine / SessionLocal:全局单例
|
|
|
|
|
- get_session:FastAPI 依赖,按请求注入一个会话
|
|
|
|
|
- init_db:启动时建表(MVP 用 create_all;表结构稳定后切 alembic 迁移,对齐 dograh)
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
from collections.abc import AsyncGenerator
|
|
|
|
|
|
|
|
|
|
import config
|
|
|
|
|
from db.models import Base
|
2026-06-09 14:42:25 +08:00
|
|
|
from sqlalchemy import text
|
2026-06-08 13:51:28 +08:00
|
|
|
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)
|
2026-06-09 14:42:25 +08:00
|
|
|
# MVP 兼容迁移:create_all 不会给已存在的表补列。
|
|
|
|
|
await conn.execute(
|
|
|
|
|
text(
|
|
|
|
|
"ALTER TABLE provider_credentials "
|
|
|
|
|
"ADD COLUMN IF NOT EXISTS voice VARCHAR(128) NOT NULL DEFAULT ''"
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
await conn.execute(
|
|
|
|
|
text(
|
|
|
|
|
"ALTER TABLE provider_credentials "
|
|
|
|
|
"ADD COLUMN IF NOT EXISTS speed DOUBLE PRECISION NOT NULL DEFAULT 1.0"
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
await conn.execute(
|
|
|
|
|
text(
|
|
|
|
|
"ALTER TABLE provider_credentials "
|
|
|
|
|
"ADD COLUMN IF NOT EXISTS language VARCHAR(32) NOT NULL DEFAULT ''"
|
|
|
|
|
)
|
|
|
|
|
)
|