From 06749d361cc5feaf64b70edb5d2ee3d42fc68f1a Mon Sep 17 00:00:00 2001 From: quby Date: Sun, 23 Feb 2025 21:30:25 +0800 Subject: [PATCH] refactor(database): migrate to SQLAlchemy 2.0 async API - Replace `conn.execute(text(query))` with `conn.exec_driver_sql(query)` for raw SQL execution. - Use the new async transaction context (`async with engine.begin() as conn:`) per SQLAlchemy 2.0. - Update engine variable naming and disposal with `await engine.dispose()`. --- app.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/app.py b/app.py index 1c35cba..b182e51 100644 --- a/app.py +++ b/app.py @@ -4,7 +4,6 @@ import pytz from py_tools.connections.db.mysql import DBManager, BaseOrmTable, SQLAlchemyManager -from sqlalchemy import text from sqlalchemy.ext.asyncio import create_async_engine from bot.bot_client import BotClient @@ -19,15 +18,15 @@ async def create_database_if_not_exists() -> None: """创建数据库。""" - engine_without_db = create_async_engine( + engine = create_async_engine( f"mysql+asyncmy://{config.db_user}:{config.db_pass}@{config.db_host}:{config.db_port}/", echo=True, ) - async with engine_without_db.begin() as conn: + async with engine.begin() as conn: query = f"CREATE DATABASE IF NOT EXISTS {config.db_name}" logger.info(f"SQL Query: {query}, Context: Creating database") - await conn.execute(text(query)) - await engine_without_db.dispose() + await conn.exec_driver_sql(query) + await engine.dispose() async def _init_db() -> None: