55
66from fastapi import Depends
77from sqlalchemy import URL
8- from sqlalchemy .ext .asyncio import AsyncSession , async_sessionmaker , create_async_engine
8+ from sqlalchemy .ext .asyncio import AsyncEngine , AsyncSession , async_sessionmaker , create_async_engine
99
1010from backend .common .log import log
1111from backend .common .model import MappedBase
@@ -32,11 +32,23 @@ def create_database_url(unittest: bool = False) -> URL:
3232 return url
3333
3434
35- def create_engine_and_session (url : str | URL ):
35+ def create_async_engine_and_session (url : str | URL ) -> tuple [ AsyncEngine , async_sessionmaker [ AsyncSession ]] :
3636 """创建数据库引擎和 Session"""
3737 try :
3838 # 数据库引擎
39- engine = create_async_engine (url , echo = settings .DATABASE_ECHO , future = True , pool_pre_ping = True )
39+ engine = create_async_engine (
40+ url ,
41+ echo = settings .DATABASE_ECHO ,
42+ echo_pool = settings .DATABASE_POOL_ECHO ,
43+ future = True ,
44+ # 中等并发
45+ pool_size = 10 , # 低:- 高:+
46+ max_overflow = 20 , # 低:- 高:+
47+ pool_timeout = 30 , # 低:+ 高:-
48+ pool_recycle = 3600 , # 低:+ 高:-
49+ pool_pre_ping = True , # 低:False 高:True
50+ pool_use_lifo = False , # 低:False 高:True
51+ )
4052 # log.success('数据库连接成功')
4153 except Exception as e :
4254 log .error ('❌ 数据库链接失败 {}' , e )
@@ -52,7 +64,7 @@ async def get_db():
5264 yield session
5365
5466
55- async def create_table ():
67+ async def create_table () -> None :
5668 """创建数据库表"""
5769 async with async_engine .begin () as coon :
5870 await coon .run_sync (MappedBase .metadata .create_all )
@@ -64,6 +76,6 @@ def uuid4_str() -> str:
6476
6577
6678SQLALCHEMY_DATABASE_URL = create_database_url ()
67- async_engine , async_db_session = create_engine_and_session (SQLALCHEMY_DATABASE_URL )
79+ async_engine , async_db_session = create_async_engine_and_session (SQLALCHEMY_DATABASE_URL )
6880# Session Annotated
6981CurrentSession = Annotated [AsyncSession , Depends (get_db )]
0 commit comments