扩展功能包: 群聊/朋友圈/语音通话/Swipe多版本/广场与角色卡分享导入 + 30项小功能(搜索/收藏/导出/摘要/偏好/置顶归档/会话设置/后台统计/轻量自动迁移等)
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
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
|
||||
|
||||
@@ -20,5 +22,30 @@ async def get_db():
|
||||
|
||||
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}=''"))
|
||||
|
||||
Reference in New Issue
Block a user