File tree Expand file tree Collapse file tree 2 files changed +30
-2
lines changed
Expand file tree Collapse file tree 2 files changed +30
-2
lines changed Original file line number Diff line number Diff line change @@ -124,6 +124,33 @@ def init_demo_database() -> str:
124124 return get_demo_db_path ()
125125
126126
127+ async def ensure_demo_connection (db : AsyncSession , demo_db_path : str ) -> None :
128+ """Ensure a Sample Database connection exists. Creates one if the connections table is empty."""
129+ from sqlalchemy import func
130+
131+ from app .services .app_settings import get_or_create_app_settings
132+
133+ count = await db .scalar (select (func .count (Connection .id )))
134+ if count and count > 0 :
135+ return
136+
137+ conn = Connection (
138+ name = DEMO_CONNECTION_NAME ,
139+ driver = "sqlite" ,
140+ database_name = demo_db_path ,
141+ extra_options = {},
142+ is_default = True ,
143+ )
144+ db .add (conn )
145+ await db .flush ()
146+
147+ settings = await get_or_create_app_settings (db )
148+ settings .default_connection_id = conn .id
149+ settings .demo_initialized = True
150+
151+ logger .info ("Created demo connection" , name = DEMO_CONNECTION_NAME , path = demo_db_path )
152+
153+
127154async def fix_demo_db_path (db : AsyncSession , demo_db_path : str ) -> None :
128155 """修正预打包数据库中的占位符路径为实际的 demo.db 绝对路径"""
129156 result = await db .scalar (
Original file line number Diff line number Diff line change 2121
2222from app .api .v1 import api_router
2323from app .core .config import settings
24- from app .core .demo_db import fix_demo_db_path , init_demo_database
24+ from app .core .demo_db import ensure_demo_connection , fix_demo_db_path , init_demo_database
2525from app .db import AsyncSessionLocal , engine
2626from app .db .base import Base
2727from app .services .engine_diagnostics import categorize_sql_error
@@ -99,9 +99,10 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
9999 # 确保 demo.db 存在(构建时已预生成,这里只是 fallback)
100100 demo_db_path = init_demo_database ()
101101
102- # 修正预打包数据库中的占位符路径
102+ # 修正预打包数据库中的占位符路径,并确保 demo 连接存在
103103 async with AsyncSessionLocal () as session :
104104 await fix_demo_db_path (session , demo_db_path )
105+ await ensure_demo_connection (session , demo_db_path )
105106 await session .commit ()
106107
107108 logger .info (
You can’t perform that action at this time.
0 commit comments