修复init初始化异常

This commit is contained in:
Cheng Zhou
2025-12-30 16:09:10 +08:00
parent 0c1fc49f17
commit ba3cf95b8a
2 changed files with 81 additions and 37 deletions
+35
View File
@@ -2,6 +2,7 @@ from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy import text
from app.api.v1.router import api_router
from app.core.config import settings
@@ -18,12 +19,46 @@ async def lifespan(_: FastAPI):
if settings.ENV == "development":
async with engine.begin() as conn:
await _ensure_legacy_primary_keys(conn)
await conn.run_sync(Base.metadata.create_all)
async with SessionLocal() as session:
await ensure_admin_exists(session)
yield
async def _ensure_legacy_primary_keys(conn) -> None:
# Fix legacy databases where tables with an "id" column were created without a PK.
result = await conn.execute(
text(
"""
SELECT c.relname AS table_name
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'public'
AND c.relkind = 'r'
AND EXISTS (
SELECT 1
FROM pg_attribute a
WHERE a.attrelid = c.oid
AND a.attname = 'id'
AND a.attisdropped = false
)
AND NOT EXISTS (
SELECT 1
FROM pg_constraint con
WHERE con.conrelid = c.oid
AND con.contype = 'p'
)
"""
)
)
tables = [row.table_name for row in result.fetchall()]
for table_name in tables:
await conn.execute(
text(f'ALTER TABLE "{table_name}" ADD CONSTRAINT "{table_name}_pkey" PRIMARY KEY (id)')
)
def create_app() -> FastAPI:
app = FastAPI(
title="CTMS 后端 API",