52 lines
2.1 KiB
Python
52 lines
2.1 KiB
Python
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
|
|
from sqlalchemy import Integer, Boolean
|
|
from sqlalchemy.orm import DeclarativeBase
|
|
import sqlalchemy as sqla
|
|
|
|
from ..core.config import settings
|
|
|
|
|
|
class Base(DeclarativeBase):
|
|
pass
|
|
|
|
|
|
engine = create_async_engine(settings.database_url, echo=False)
|
|
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
|
|
|
|
|
|
async def get_db():
|
|
async with SessionLocal() as session:
|
|
yield session
|
|
|
|
|
|
|
|
async def init_db():
|
|
from ..models import entities # noqa: F401
|
|
from sqlalchemy import text
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.create_all)
|
|
# 轻量自动迁移:为已存在的表补齐新增列(SQLite)
|
|
if settings.database_url.startswith("sqlite"):
|
|
for table in Base.metadata.tables.values():
|
|
cols = {c["name"] for c in (await conn.execute(
|
|
text(f"PRAGMA table_info({table.name})"))).mappings()}
|
|
for col in table.columns:
|
|
if col.name not in cols:
|
|
coltype = col.type.compile()
|
|
# 默认值按类型给,避免旧行出现 '' 污染数值列
|
|
if isinstance(col.type, (sqla.Integer, sqla.Boolean)):
|
|
default = " DEFAULT 0"
|
|
elif col.server_default is not None:
|
|
default = f" DEFAULT '{col.server_default.arg}'"
|
|
elif col.nullable is False:
|
|
default = " DEFAULT ''"
|
|
else:
|
|
default = ""
|
|
await conn.execute(text(
|
|
f"ALTER TABLE {table.name} ADD COLUMN "
|
|
f"{col.name} {coltype}{default}"))
|
|
if isinstance(col.type, (sqla.Integer, sqla.Boolean)):
|
|
await conn.execute(text(
|
|
f"UPDATE {table.name} SET {col.name}=0 "
|
|
f"WHERE {col.name}=''"))
|