- 创建DataProvider静态类,提供统一的数据查询接口 - 支持批量查询多股票,返回Dict[str, DataFrame]格式 - 实现ensure_klines智能数据检查和save_klines批量保存 - 优化DatabaseManager使用连接池(pool_size=5, pool_pre_ping=True) - 将数据下载器移至data_downloader子文件夹 - 添加数据库连接设计文档 - 创建测试用例验证功能完整性
408 lines
12 KiB
Python
408 lines
12 KiB
Python
"""
|
||
数据库管理器
|
||
提供数据库和表的直接操作
|
||
"""
|
||
|
||
from typing import List, Optional, Dict, Any
|
||
from sqlalchemy import (
|
||
create_engine,
|
||
text,
|
||
inspect,
|
||
MetaData,
|
||
Table,
|
||
Column,
|
||
Integer,
|
||
String,
|
||
Float,
|
||
DateTime,
|
||
Boolean,
|
||
Text,
|
||
JSON,
|
||
Index,
|
||
)
|
||
from sqlalchemy.engine import Engine
|
||
from sqlalchemy.exc import SQLAlchemyError
|
||
|
||
from ..core import get_logger, get_config
|
||
|
||
logger = get_logger("DatabaseManager")
|
||
|
||
|
||
class DatabaseManager:
|
||
"""
|
||
数据库管理器
|
||
|
||
功能:
|
||
- 检查数据库是否存在
|
||
- 创建数据库
|
||
- 删除数据库
|
||
- 创建表
|
||
- 删除表
|
||
- 检查表是否存在
|
||
|
||
架构说明:
|
||
- 使用连接池(pool_size=5),不需要保持长连接
|
||
- 每个进程连接一个数据库(由配置文件指定)
|
||
- 回测/模拟/实时 各自独立运行
|
||
"""
|
||
|
||
def __init__(
|
||
self,
|
||
host: Optional[str] = None,
|
||
port: Optional[int] = None,
|
||
user: Optional[str] = None,
|
||
password: Optional[str] = None,
|
||
):
|
||
"""
|
||
初始化数据库管理器
|
||
|
||
Args:
|
||
host: 数据库主机
|
||
port: 数据库端口
|
||
user: 数据库用户名
|
||
password: 数据库密码
|
||
"""
|
||
config = get_config()
|
||
|
||
self.host = host or config.get("database.host", "127.0.0.1")
|
||
self.port = port or config.get("database.port", 3306)
|
||
self.user = user or config.get("database.user", "root")
|
||
self.password = password or config.get("database.password", "")
|
||
self.pool_size = config.get("database.pool_size", 5)
|
||
self.pool_recycle = config.get("database.pool_recycle", 3600)
|
||
|
||
# 创建不指定数据库的连接(用于管理数据库)
|
||
self._admin_engine = self._create_admin_engine()
|
||
|
||
logger.info(f"数据库管理器初始化完成: {self.user}@{self.host}:{self.port}")
|
||
|
||
def _create_admin_engine(self) -> Engine:
|
||
"""创建管理员引擎(不指定数据库,带连接池)"""
|
||
connection_url = (
|
||
f"mysql+pymysql://{self.user}:{self.password}@"
|
||
f"{self.host}:{self.port}/?charset=utf8mb4"
|
||
)
|
||
return create_engine(
|
||
connection_url,
|
||
echo=False,
|
||
pool_size=self.pool_size,
|
||
pool_recycle=self.pool_recycle,
|
||
pool_pre_ping=True, # 自动检查连接有效性
|
||
)
|
||
|
||
def _create_db_engine(self, database: str) -> Engine:
|
||
"""创建指定数据库的引擎(带连接池)"""
|
||
connection_url = (
|
||
f"mysql+pymysql://{self.user}:{self.password}@"
|
||
f"{self.host}:{self.port}/{database}?charset=utf8mb4"
|
||
)
|
||
return create_engine(
|
||
connection_url,
|
||
echo=False,
|
||
pool_size=self.pool_size,
|
||
pool_recycle=self.pool_recycle,
|
||
pool_pre_ping=True,
|
||
)
|
||
|
||
def database_exists(self, database: str) -> bool:
|
||
"""
|
||
检查数据库是否存在
|
||
|
||
Args:
|
||
database: 数据库名
|
||
|
||
Returns:
|
||
是否存在
|
||
"""
|
||
try:
|
||
with self._admin_engine.connect() as conn:
|
||
result = conn.execute(text(f"SHOW DATABASES LIKE '{database}'"))
|
||
exists = result.fetchone() is not None
|
||
logger.debug(f"检查数据库 {database}: {'存在' if exists else '不存在'}")
|
||
return exists
|
||
except SQLAlchemyError as e:
|
||
logger.error(f"检查数据库失败: {e}")
|
||
return False
|
||
|
||
def create_database(self, database: str, if_not_exists: bool = True) -> bool:
|
||
"""
|
||
创建数据库
|
||
|
||
Args:
|
||
database: 数据库名
|
||
if_not_exists: 如果存在是否跳过
|
||
|
||
Returns:
|
||
是否成功
|
||
"""
|
||
try:
|
||
if if_not_exists and self.database_exists(database):
|
||
logger.info(f"数据库 {database} 已存在,跳过创建")
|
||
return True
|
||
|
||
with self._admin_engine.connect() as conn:
|
||
conn.execute(
|
||
text(
|
||
f"CREATE DATABASE `{database}` "
|
||
f"CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
|
||
)
|
||
)
|
||
conn.commit()
|
||
logger.info(f"✓ 创建数据库: {database}")
|
||
return True
|
||
except SQLAlchemyError as e:
|
||
logger.error(f"创建数据库失败: {e}")
|
||
return False
|
||
|
||
def drop_database(self, database: str, confirm: bool = False) -> bool:
|
||
"""
|
||
删除数据库
|
||
|
||
Args:
|
||
database: 数据库名
|
||
confirm: 确认删除(防止误删)
|
||
|
||
Returns:
|
||
是否成功
|
||
"""
|
||
if not confirm:
|
||
logger.warning("删除数据库需要确认: confirm=True")
|
||
return False
|
||
|
||
try:
|
||
if not self.database_exists(database):
|
||
logger.warning(f"数据库 {database} 不存在")
|
||
return False
|
||
|
||
with self._admin_engine.connect() as conn:
|
||
conn.execute(text(f"DROP DATABASE `{database}`"))
|
||
conn.commit()
|
||
logger.info(f"✓ 删除数据库: {database}")
|
||
return True
|
||
except SQLAlchemyError as e:
|
||
logger.error(f"删除数据库失败: {e}")
|
||
return False
|
||
|
||
def list_databases(self) -> List[str]:
|
||
"""
|
||
列出所有数据库
|
||
|
||
Returns:
|
||
数据库名列表
|
||
"""
|
||
try:
|
||
with self._admin_engine.connect() as conn:
|
||
result = conn.execute(text("SHOW DATABASES"))
|
||
databases = [row[0] for row in result]
|
||
# 过滤系统数据库
|
||
databases = [
|
||
db
|
||
for db in databases
|
||
if db
|
||
not in ["information_schema", "mysql", "performance_schema", "sys"]
|
||
]
|
||
return databases
|
||
except SQLAlchemyError as e:
|
||
logger.error(f"列出数据库失败: {e}")
|
||
return []
|
||
|
||
def table_exists(self, database: str, table: str) -> bool:
|
||
"""
|
||
检查表是否存在
|
||
|
||
Args:
|
||
database: 数据库名
|
||
table: 表名
|
||
|
||
Returns:
|
||
是否存在
|
||
"""
|
||
try:
|
||
engine = self._create_db_engine(database)
|
||
inspector = inspect(engine)
|
||
exists = table in inspector.get_table_names()
|
||
logger.debug(f"检查表 {database}.{table}: {'存在' if exists else '不存在'}")
|
||
return exists
|
||
except SQLAlchemyError as e:
|
||
logger.error(f"检查表失败: {e}")
|
||
return False
|
||
|
||
def list_tables(self, database: str) -> List[str]:
|
||
"""
|
||
列出数据库中的所有表
|
||
|
||
Args:
|
||
database: 数据库名
|
||
|
||
Returns:
|
||
表名列表
|
||
"""
|
||
try:
|
||
engine = self._create_db_engine(database)
|
||
inspector = inspect(engine)
|
||
return inspector.get_table_names()
|
||
except SQLAlchemyError as e:
|
||
logger.error(f"列出表失败: {e}")
|
||
return []
|
||
|
||
def create_table(
|
||
self,
|
||
database: str,
|
||
table_name: str,
|
||
columns: Dict[str, Dict[str, Any]],
|
||
indexes: Optional[List[Dict[str, Any]]] = None,
|
||
if_not_exists: bool = True,
|
||
) -> bool:
|
||
"""
|
||
创建表
|
||
|
||
Args:
|
||
database: 数据库名
|
||
table_name: 表名
|
||
columns: 列定义,格式:
|
||
{
|
||
'column_name': {
|
||
'type': 'String'/'Integer'/'Float'/'DateTime'/'Boolean'/'Text'/'JSON',
|
||
'length': 50, # String类型需要
|
||
'primary_key': False,
|
||
'nullable': True,
|
||
'default': None,
|
||
'comment': '字段说明'
|
||
}
|
||
}
|
||
indexes: 索引定义列表,格式:
|
||
[
|
||
{'name': 'idx_symbol', 'columns': ['symbol']},
|
||
{'name': 'idx_time', 'columns': ['timestamp'], 'unique': False}
|
||
]
|
||
if_not_exists: 如果存在是否跳过
|
||
|
||
Returns:
|
||
是否成功
|
||
"""
|
||
try:
|
||
if if_not_exists and self.table_exists(database, table_name):
|
||
logger.info(f"表 {database}.{table_name} 已存在,跳过创建")
|
||
return True
|
||
|
||
engine = self._create_db_engine(database)
|
||
metadata = MetaData()
|
||
|
||
# 构建列定义
|
||
table_columns = []
|
||
for col_name, col_def in columns.items():
|
||
col_type_str = col_def.get("type", "String")
|
||
|
||
# 映射类型(String 直接返回实例,其他返回类)
|
||
if col_type_str == "String":
|
||
col_type = String(col_def.get("length", 50))
|
||
elif col_type_str == "Integer":
|
||
col_type = Integer()
|
||
elif col_type_str == "Float":
|
||
col_type = Float()
|
||
elif col_type_str == "DateTime":
|
||
col_type = DateTime()
|
||
elif col_type_str == "Boolean":
|
||
col_type = Boolean()
|
||
elif col_type_str == "Text":
|
||
col_type = Text()
|
||
elif col_type_str == "JSON":
|
||
col_type = JSON()
|
||
else:
|
||
col_type = String(50)
|
||
|
||
column = Column(
|
||
col_name,
|
||
col_type, # type: ignore
|
||
primary_key=col_def.get("primary_key", False),
|
||
nullable=col_def.get("nullable", True),
|
||
default=col_def.get("default"),
|
||
comment=col_def.get("comment", ""),
|
||
)
|
||
table_columns.append(column)
|
||
|
||
# 创建表对象
|
||
table = Table(table_name, metadata, *table_columns)
|
||
|
||
# 添加索引
|
||
if indexes:
|
||
for idx_def in indexes:
|
||
idx_name = idx_def.get("name")
|
||
idx_columns = idx_def.get("columns", [])
|
||
idx_unique = idx_def.get("unique", False)
|
||
|
||
Index(
|
||
idx_name,
|
||
*[table.c[col] for col in idx_columns],
|
||
unique=idx_unique,
|
||
)
|
||
|
||
# 创建表
|
||
metadata.create_all(engine)
|
||
logger.info(f"✓ 创建表: {database}.{table_name}")
|
||
return True
|
||
|
||
except SQLAlchemyError as e:
|
||
logger.error(f"创建表失败: {e}")
|
||
return False
|
||
|
||
def drop_table(self, database: str, table: str, confirm: bool = False) -> bool:
|
||
"""
|
||
删除表
|
||
|
||
Args:
|
||
database: 数据库名
|
||
table: 表名
|
||
confirm: 确认删除(防止误删)
|
||
|
||
Returns:
|
||
是否成功
|
||
"""
|
||
if not confirm:
|
||
logger.warning("删除表需要确认: confirm=True")
|
||
return False
|
||
|
||
try:
|
||
if not self.table_exists(database, table):
|
||
logger.warning(f"表 {database}.{table} 不存在")
|
||
return False
|
||
|
||
engine = self._create_db_engine(database)
|
||
with engine.connect() as conn:
|
||
conn.execute(text(f"DROP TABLE `{table}`"))
|
||
conn.commit()
|
||
logger.info(f"✓ 删除表: {database}.{table}")
|
||
return True
|
||
except SQLAlchemyError as e:
|
||
logger.error(f"删除表失败: {e}")
|
||
return False
|
||
|
||
def get_table_schema(self, database: str, table: str) -> Dict[str, Any]:
|
||
"""
|
||
获取表结构
|
||
|
||
Args:
|
||
database: 数据库名
|
||
table: 表名
|
||
|
||
Returns:
|
||
表结构信息
|
||
"""
|
||
try:
|
||
engine = self._create_db_engine(database)
|
||
inspector = inspect(engine)
|
||
|
||
columns = inspector.get_columns(table)
|
||
indexes = inspector.get_indexes(table)
|
||
pk = inspector.get_pk_constraint(table)
|
||
|
||
return {"columns": columns, "indexes": indexes, "primary_key": pk}
|
||
except SQLAlchemyError as e:
|
||
logger.error(f"获取表结构失败: {e}")
|
||
return {}
|
||
|
||
def close(self):
|
||
"""关闭连接"""
|
||
self._admin_engine.dispose()
|
||
logger.info("数据库管理器连接已关闭")
|