2025-12-13 10:30:31 +08:00
|
|
|
|
"""
|
|
|
|
|
|
数据库管理服务
|
|
|
|
|
|
|
|
|
|
|
|
提供数据库级别的操作:创建、删除、查询等
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
import pymysql
|
|
|
|
|
|
from pymysql.err import OperationalError
|
|
|
|
|
|
from typing import List, Optional
|
|
|
|
|
|
from src.core.logger import get_logger
|
|
|
|
|
|
|
2025-12-13 11:27:08 +08:00
|
|
|
|
logger = get_logger("database_admin_service.db_admin")
|
2025-12-13 10:30:31 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 环境数据库映射
|
|
|
|
|
|
ENV_DATABASES = {
|
|
|
|
|
|
"production": "QTrade_RealTrade",
|
|
|
|
|
|
"backtest": "QTrade_BackTestTrade",
|
|
|
|
|
|
"simulation": "QTrade_SimuTrade",
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
2025-12-13 11:27:08 +08:00
|
|
|
|
class DatabaseAdmin:
|
|
|
|
|
|
"""数据库管理器(DBA级别操作)"""
|
2025-12-13 10:30:31 +08:00
|
|
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
|
|
self,
|
|
|
|
|
|
host: str = "127.0.0.1",
|
|
|
|
|
|
port: int = 3306,
|
|
|
|
|
|
user: str = "root",
|
|
|
|
|
|
password: str = "1234",
|
|
|
|
|
|
):
|
|
|
|
|
|
self.host = host
|
|
|
|
|
|
self.port = port
|
|
|
|
|
|
self.user = user
|
|
|
|
|
|
self.password = password
|
|
|
|
|
|
|
|
|
|
|
|
def _get_connection(self, database: Optional[str] = None):
|
|
|
|
|
|
"""获取数据库连接"""
|
|
|
|
|
|
return pymysql.connect(
|
|
|
|
|
|
host=self.host,
|
|
|
|
|
|
port=self.port,
|
|
|
|
|
|
user=self.user,
|
|
|
|
|
|
password=self.password,
|
|
|
|
|
|
database=database,
|
|
|
|
|
|
charset="utf8mb4",
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def list_databases(self) -> List[dict]:
|
|
|
|
|
|
"""列出所有QTrade数据库"""
|
|
|
|
|
|
conn = self._get_connection()
|
|
|
|
|
|
try:
|
|
|
|
|
|
with conn.cursor() as cursor:
|
|
|
|
|
|
cursor.execute("SHOW DATABASES LIKE 'QTrade%'")
|
|
|
|
|
|
db_names = [row[0] for row in cursor.fetchall()]
|
|
|
|
|
|
|
|
|
|
|
|
databases = []
|
|
|
|
|
|
for db_name in db_names:
|
|
|
|
|
|
# 获取环境类型
|
|
|
|
|
|
env = "unknown"
|
|
|
|
|
|
for e, d in ENV_DATABASES.items():
|
|
|
|
|
|
if d.lower() == db_name.lower():
|
|
|
|
|
|
env = e
|
|
|
|
|
|
break
|
|
|
|
|
|
|
|
|
|
|
|
# 获取表数量
|
|
|
|
|
|
cursor.execute(f"USE `{db_name}`")
|
|
|
|
|
|
cursor.execute("SHOW TABLES")
|
|
|
|
|
|
table_count = len(cursor.fetchall())
|
|
|
|
|
|
|
|
|
|
|
|
# 获取数据库大小
|
|
|
|
|
|
cursor.execute(
|
|
|
|
|
|
f"""
|
|
|
|
|
|
SELECT
|
|
|
|
|
|
ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) as size_mb
|
|
|
|
|
|
FROM information_schema.TABLES
|
|
|
|
|
|
WHERE table_schema = %s
|
|
|
|
|
|
""",
|
|
|
|
|
|
(db_name,),
|
|
|
|
|
|
)
|
|
|
|
|
|
result = cursor.fetchone()
|
|
|
|
|
|
size_mb = result[0] if result and result[0] else 0
|
|
|
|
|
|
|
|
|
|
|
|
databases.append(
|
|
|
|
|
|
{
|
|
|
|
|
|
"name": db_name,
|
|
|
|
|
|
"environment": env,
|
|
|
|
|
|
"table_count": table_count,
|
|
|
|
|
|
"size_mb": float(size_mb),
|
|
|
|
|
|
}
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
return databases
|
|
|
|
|
|
finally:
|
|
|
|
|
|
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
def create_database(self, environment: str) -> dict:
|
|
|
|
|
|
"""创建数据库"""
|
|
|
|
|
|
db_name = ENV_DATABASES.get(environment)
|
|
|
|
|
|
if not db_name:
|
|
|
|
|
|
raise ValueError(f"不支持的环境: {environment}")
|
|
|
|
|
|
|
|
|
|
|
|
conn = self._get_connection()
|
|
|
|
|
|
try:
|
|
|
|
|
|
with conn.cursor() as cursor:
|
|
|
|
|
|
# 检查是否已存在
|
|
|
|
|
|
cursor.execute("SHOW DATABASES LIKE %s", (db_name,))
|
|
|
|
|
|
if cursor.fetchone():
|
|
|
|
|
|
logger.warning(f"数据库已存在: {db_name}")
|
|
|
|
|
|
return {"message": f"数据库已存在: {db_name}", "existed": True}
|
|
|
|
|
|
|
|
|
|
|
|
# 创建数据库
|
|
|
|
|
|
cursor.execute(
|
|
|
|
|
|
f"CREATE DATABASE `{db_name}` "
|
|
|
|
|
|
f"CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
|
|
|
|
|
|
)
|
|
|
|
|
|
conn.commit()
|
|
|
|
|
|
|
|
|
|
|
|
logger.info(f"创建数据库成功: {db_name}")
|
|
|
|
|
|
return {"message": f"创建数据库成功: {db_name}", "existed": False}
|
|
|
|
|
|
finally:
|
|
|
|
|
|
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
def drop_database(self, environment: str) -> dict:
|
|
|
|
|
|
"""删除数据库"""
|
|
|
|
|
|
db_name = ENV_DATABASES.get(environment)
|
|
|
|
|
|
if not db_name:
|
|
|
|
|
|
raise ValueError(f"不支持的环境: {environment}")
|
|
|
|
|
|
|
|
|
|
|
|
conn = self._get_connection()
|
|
|
|
|
|
try:
|
|
|
|
|
|
with conn.cursor() as cursor:
|
|
|
|
|
|
# 检查是否存在
|
|
|
|
|
|
cursor.execute("SHOW DATABASES LIKE %s", (db_name,))
|
|
|
|
|
|
if not cursor.fetchone():
|
|
|
|
|
|
logger.warning(f"数据库不存在: {db_name}")
|
|
|
|
|
|
return {"message": f"数据库不存在: {db_name}", "existed": False}
|
|
|
|
|
|
|
|
|
|
|
|
# 删除数据库
|
|
|
|
|
|
cursor.execute(f"DROP DATABASE `{db_name}`")
|
|
|
|
|
|
conn.commit()
|
|
|
|
|
|
|
|
|
|
|
|
logger.info(f"删除数据库成功: {db_name}")
|
|
|
|
|
|
return {"message": f"删除数据库成功: {db_name}", "existed": True}
|
|
|
|
|
|
finally:
|
|
|
|
|
|
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
def get_database_info(self, environment: str) -> dict:
|
|
|
|
|
|
"""获取数据库详细信息"""
|
|
|
|
|
|
db_name = ENV_DATABASES.get(environment)
|
|
|
|
|
|
if not db_name:
|
|
|
|
|
|
raise ValueError(f"不支持的环境: {environment}")
|
|
|
|
|
|
|
|
|
|
|
|
conn = self._get_connection()
|
|
|
|
|
|
try:
|
|
|
|
|
|
with conn.cursor() as cursor:
|
|
|
|
|
|
# 检查是否存在
|
|
|
|
|
|
cursor.execute("SHOW DATABASES LIKE %s", (db_name,))
|
|
|
|
|
|
if not cursor.fetchone():
|
|
|
|
|
|
raise ValueError(f"数据库不存在: {db_name}")
|
|
|
|
|
|
|
|
|
|
|
|
cursor.execute(f"USE `{db_name}`")
|
|
|
|
|
|
|
|
|
|
|
|
# 获取表数量
|
|
|
|
|
|
cursor.execute("SHOW TABLES")
|
|
|
|
|
|
table_count = len(cursor.fetchall())
|
|
|
|
|
|
|
|
|
|
|
|
# 获取数据库大小
|
|
|
|
|
|
cursor.execute(
|
|
|
|
|
|
"""
|
|
|
|
|
|
SELECT
|
|
|
|
|
|
ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) as size_mb
|
|
|
|
|
|
FROM information_schema.TABLES
|
|
|
|
|
|
WHERE table_schema = %s
|
|
|
|
|
|
""",
|
|
|
|
|
|
(db_name,),
|
|
|
|
|
|
)
|
|
|
|
|
|
result = cursor.fetchone()
|
|
|
|
|
|
size_mb = result[0] if result and result[0] else 0
|
|
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
|
"name": db_name,
|
|
|
|
|
|
"environment": environment,
|
|
|
|
|
|
"table_count": table_count,
|
|
|
|
|
|
"size_mb": float(size_mb),
|
|
|
|
|
|
}
|
|
|
|
|
|
finally:
|
|
|
|
|
|
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 全局实例
|
2025-12-13 11:27:08 +08:00
|
|
|
|
db_admin = DatabaseAdmin()
|