add
This commit is contained in:
75
utils/database_manager.py
Normal file
75
utils/database_manager.py
Normal file
@@ -0,0 +1,75 @@
|
||||
from sqlalchemy import create_engine, select, update, insert, delete, and_, or_, text
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from loguru import logger
|
||||
from typing import List, Dict, Optional, Any
|
||||
import json
|
||||
|
||||
from config.database import DATABASE_CONFIG, SQLALCHEMY_CONFIG
|
||||
from models.orm_models import Base, StrategyPosition, StrategyOrder, StrategyKX
|
||||
|
||||
class DatabaseManager:
|
||||
"""数据库管理器"""
|
||||
|
||||
_instance = None
|
||||
|
||||
def __new__(cls):
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
cls._instance._initialized = False
|
||||
return cls._instance
|
||||
|
||||
def __init__(self):
|
||||
if not self._initialized:
|
||||
self._engine = None
|
||||
self._session_factory = None
|
||||
self._initialized = True
|
||||
self._init_engine()
|
||||
|
||||
def _init_engine(self):
|
||||
"""初始化数据库引擎"""
|
||||
try:
|
||||
# 构建数据库URL
|
||||
db_url = (
|
||||
f"mysql+pymysql://{DATABASE_CONFIG['user']}:{DATABASE_CONFIG['password']}"
|
||||
f"@{DATABASE_CONFIG['host']}:{DATABASE_CONFIG['port']}"
|
||||
f"/{DATABASE_CONFIG['database']}?charset={DATABASE_CONFIG['charset']}"
|
||||
)
|
||||
|
||||
# 创建引擎
|
||||
self._engine = create_engine(
|
||||
db_url,
|
||||
echo=SQLALCHEMY_CONFIG['echo'],
|
||||
echo_pool=SQLALCHEMY_CONFIG['echo_pool'],
|
||||
pool_size=DATABASE_CONFIG['pool_size'],
|
||||
max_overflow=DATABASE_CONFIG['max_overflow'],
|
||||
pool_recycle=DATABASE_CONFIG['pool_recycle'],
|
||||
pool_pre_ping=SQLALCHEMY_CONFIG['pool_pre_ping']
|
||||
)
|
||||
|
||||
# 创建会话工厂
|
||||
self._session_factory = sessionmaker(
|
||||
bind=self._engine,
|
||||
expire_on_commit=False
|
||||
)
|
||||
|
||||
# 创建表(如果不存在)
|
||||
Base.metadata.create_all(self._engine)
|
||||
|
||||
logger.info("SQLAlchemy数据库引擎初始化成功")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"数据库引擎初始化失败: {e}")
|
||||
raise
|
||||
|
||||
def get_session(self) -> Session:
|
||||
"""获取数据库会话"""
|
||||
if self._session_factory is None:
|
||||
self._init_engine()
|
||||
return self._session_factory()
|
||||
|
||||
def close(self):
|
||||
"""关闭数据库连接"""
|
||||
if self._engine:
|
||||
self._engine.dispose()
|
||||
logger.info("数据库连接已关闭")
|
||||
Reference in New Issue
Block a user