33 lines
1.1 KiB
Python
33 lines
1.1 KiB
Python
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
|
|
from sqlalchemy.orm import DeclarativeBase
|
|
from app.core.config import settings
|
|
|
|
settings.data_path.mkdir(parents=True, exist_ok=True)
|
|
settings.upload_path.mkdir(parents=True, exist_ok=True)
|
|
|
|
engine = create_async_engine(settings.database_url, echo=False)
|
|
async_session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
|
|
|
|
|
class Base(DeclarativeBase):
|
|
pass
|
|
|
|
|
|
async def init_db():
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.create_all)
|
|
await _migrate()
|
|
|
|
|
|
async def _migrate():
|
|
"""轻量迁移:SQLite 下给已有 segments 表补 embedding 列(create_all 不会改老表)。"""
|
|
async with engine.begin() as conn:
|
|
rows = (await conn.exec_driver_sql("PRAGMA table_info(segments)")).all()
|
|
cols = {row[1] for row in rows}
|
|
if rows and "embedding" not in cols:
|
|
await conn.exec_driver_sql("ALTER TABLE segments ADD COLUMN embedding TEXT")
|
|
|
|
|
|
async def get_db():
|
|
async with async_session() as session:
|
|
yield session |