QTrade/scripts/database_admin_script.py
cuizhan 19b21a133b refactor(data_provider): 重构DataProvider架构,实现工厂模式下载器集成
主要改动:
1. 架构优化
   - DataProvider 改为实例化设计,支持上下文管理器
   - 实现外观模式,组合专门的处理类(KlineReader, DataCoverageChecker, DataQualityChecker)
   - 下载器集成采用工厂模式,通过字符串参数动态创建

2. 新增核心类
   - DownloaderFactory: 下载器工厂,管理注册表和创建逻辑
   - KlineReader: K线数据读取器,统一返回 Dict[symbol, DataFrame] 格式
   - DataCoverageChecker: 数据覆盖检查器,支持覆盖率计算和缺口检测
   - DataQualityChecker: 数据质量检查器,检查重复/完整性/逻辑错误

3. 依赖解耦
   - DataProvider 不再直接依赖具体下载器类
   - 通过 DownloaderFactory.create(downloader_type) 动态创建
   - 下载器类型从 global.yaml 配置文件读取

4. 功能增强
   - 新增 check_coverage(): 检查数据覆盖率和缺口
   - 新增 check_data_quality(): 检查数据质量问题
   - 新增 remove_duplicates(): 清理重复数据
   - 支持 ensure_klines() 智能获取数据

5. 文档和工具
   - 新增 scripts/database_admin_script.py: 交互式数据库管理工具
   - 新增 scripts/readme.md: 脚本使用文档
   - 新增 tests/test_data_quality.py: 数据质量测试脚本
   - 更新 design_pricinple.md: 完整的设计原则文档

6. 清理
   - 删除旧的环境变量文件 (.env.*)
   - 删除测试脚本 (test_config_validation.py, test_xtquant_token.py)
   - 删除临时脚本 (drop_qtrade_databases.py)

配置变更:
- global.yaml 新增 data_source.downloader 配置项

Breaking Changes:
- DataProvider 由静态类改为实例类,使用方式变更
- download_klines() 参数变更,不再需要传入 downloader_class
2025-12-17 15:42:26 +08:00

526 lines
18 KiB
Python

"""
数据库管理交互式脚本
提供交互式命令行界面管理数据库
"""
import sys
import os
from pathlib import Path
# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
# 设置环境变量
os.environ["CONFIG_FILE"] = "configs/backtest.yaml"
# 导入必须在路径设置和环境变量之后
from src.database_manager import DatabaseManager # noqa: E402
from src.core import get_config # noqa: E402
from sqlalchemy import create_engine, text # noqa: E402
class DatabaseAdminCLI:
"""数据库管理命令行界面"""
def __init__(self):
self.db_manager = DatabaseManager()
self.config = get_config()
self.current_db = self.config.get("database.database")
self.running = True
def print_banner(self):
"""打印欢迎横幅"""
print("\n" + "=" * 70)
print(" QTrade 数据库管理工具")
print("=" * 70)
print(f"当前数据库: {self.current_db}")
print("输入 'help' 查看所有命令, 'exit' 或 Ctrl+C 退出")
print("=" * 70 + "\n")
def print_help(self):
"""打印帮助信息"""
help_text = """
可用命令:
数据库操作:
list-db - 列出所有数据库
use <database> - 切换到指定数据库
create-db <database> - 创建新数据库
drop-db <database> - 删除指定数据库
db-exists <database> - 检查数据库是否存在
表操作:
list-tables - 列出当前数据库的所有表
create-tables - 在当前数据库创建所有表结构
drop-tables - 删除当前数据库的所有表
clear-tables - 清空当前数据库所有表的数据(保留结构)
table-exists <table> - 检查表是否存在
table-info <table> - 查看表结构信息
drop-table <table> - 删除指定表
数据操作:
count-table <table> - 统计表中记录数
clear-table <table> - 清空指定表的数据
系统命令:
help - 显示此帮助信息
exit / quit - 退出程序
clear - 清屏
命令示例:
use qtrade_test
create-db qtrade_backup
drop-db qtrade_old
list-tables
create-tables
clear-tables
count-table klines_1m
"""
print(help_text)
def execute_command(self, command: str):
"""执行命令"""
command = command.strip()
if not command:
return
parts = command.split(maxsplit=1)
cmd = parts[0].lower()
args = parts[1] if len(parts) > 1 else ""
try:
# 数据库操作
if cmd == "list-db":
self.list_databases()
elif cmd == "use":
self.use_database(args)
elif cmd == "create-db":
self.create_database(args)
elif cmd == "drop-db":
self.drop_database(args)
elif cmd == "db-exists":
self.check_database_exists(args)
# 表操作
elif cmd == "list-tables":
self.list_tables()
elif cmd == "create-tables":
self.create_all_tables()
elif cmd == "drop-tables":
self.drop_all_tables()
elif cmd == "clear-tables":
self.clear_all_tables()
elif cmd == "table-exists":
self.check_table_exists(args)
elif cmd == "table-info":
self.show_table_info(args)
elif cmd == "drop-table":
self.drop_table(args)
# 数据操作
elif cmd == "count-table":
self.count_table_rows(args)
elif cmd == "clear-table":
self.clear_table(args)
# 系统命令
elif cmd == "help":
self.print_help()
elif cmd in ["exit", "quit"]:
self.running = False
print("\n再见!")
elif cmd == "clear":
os.system("cls" if os.name == "nt" else "clear")
else:
print(f"✗ 未知命令: {cmd}. 输入 'help' 查看帮助")
except Exception as e:
print(f"✗ 执行命令时出错: {str(e)}")
# ==================== 数据库操作 ====================
def list_databases(self):
"""列出所有数据库"""
databases = self.db_manager.list_databases()
print(f"\n找到 {len(databases)} 个数据库:")
for db in databases:
marker = " (当前)" if db == self.current_db else ""
print(f" • {db}{marker}")
print()
def use_database(self, database: str):
"""切换数据库"""
if not database:
print("✗ 请指定数据库名称")
return
if self.db_manager.database_exists(database):
self.current_db = database
print(f"✓ 已切换到数据库: {database}")
else:
print(f"✗ 数据库不存在: {database}")
def create_database(self, database: str):
"""创建数据库"""
if not database:
print("✗ 请指定数据库名称")
return
if self.db_manager.database_exists(database):
print(f"✗ 数据库已存在: {database}")
return
response = input(f"确认创建数据库 '{database}'? (yes/no): ").strip().lower()
if response == "yes":
if self.db_manager.create_database(database):
print(f"✓ 数据库创建成功: {database}")
else:
print(f"✗ 数据库创建失败: {database}")
else:
print("✗ 操作已取消")
def drop_database(self, database: str):
"""删除数据库"""
if not database:
print("✗ 请指定数据库名称")
return
if not self.db_manager.database_exists(database):
print(f"✗ 数据库不存在: {database}")
return
print(f"\n⚠️ 警告: 即将删除数据库 '{database}' 及其所有数据!")
response = input("请输入数据库名称确认删除: ").strip()
if response == database:
if self.db_manager.drop_database(database, confirm=True):
print(f"✓ 数据库已删除: {database}")
if self.current_db == database:
self.current_db = self.config.get("database.database")
print(f"✓ 已切换回默认数据库: {self.current_db}")
else:
print(f"✗ 数据库删除失败: {database}")
else:
print("✗ 名称不匹配,操作已取消")
def check_database_exists(self, database: str):
"""检查数据库是否存在"""
if not database:
print("✗ 请指定数据库名称")
return
exists = self.db_manager.database_exists(database)
if exists:
print(f"✓ 数据库存在: {database}")
else:
print(f"✗ 数据库不存在: {database}")
# ==================== 表操作 ====================
def list_tables(self):
"""列出所有表"""
tables = self.db_manager.list_tables(self.current_db)
print(f"\n数据库 '{self.current_db}' 中的表 ({len(tables)} 个):")
if tables:
for table in sorted(tables):
print(f" • {table}")
else:
print(" (无表)")
print()
def create_all_tables(self):
"""创建所有表结构"""
print(f"\n即将在数据库 '{self.current_db}' 中创建所有表结构")
response = input("确认继续? (yes/no): ").strip().lower()
if response != "yes":
print("✗ 操作已取消")
return
from src.database_manager.table_schemas import ALL_TABLES
success_count = 0
fail_count = 0
for table_name, table_def in ALL_TABLES.items():
try:
if self.db_manager.create_table(
database=self.current_db,
table_name=table_name,
columns=table_def["columns"],
indexes=table_def.get("indexes"),
if_not_exists=True,
):
print(f"✓ 创建表: {table_name}")
success_count += 1
else:
print(f"✗ 创建失败: {table_name}")
fail_count += 1
except Exception as e:
print(f"✗ 创建失败: {table_name} - {str(e)}")
fail_count += 1
print(f"\n完成: 成功 {success_count} 个, 失败 {fail_count} 个")
def drop_all_tables(self):
"""删除所有表"""
tables = self.db_manager.list_tables(self.current_db)
if not tables:
print(f"✓ 数据库 '{self.current_db}' 中没有表")
return
print(
f"\n⚠️ 警告: 即将删除数据库 '{self.current_db}' 中所有 {len(tables)} 个表!"
)
print("表列表:", ", ".join(tables))
response = input("\n确认删除所有表? (yes/no): ").strip().lower()
if response != "yes":
print("✗ 操作已取消")
return
# 创建数据库连接
db_url = (
f"mysql+pymysql://{self.config.get('database.user')}:"
f"{self.config.get('database.password')}@"
f"{self.config.get('database.host')}:{self.config.get('database.port')}"
f"/{self.current_db}"
)
engine = create_engine(db_url, echo=False)
success_count = 0
fail_count = 0
try:
with engine.connect() as conn:
# 禁用外键检查
conn.execute(text("SET FOREIGN_KEY_CHECKS = 0"))
for table in tables:
try:
conn.execute(text(f"DROP TABLE `{table}`"))
conn.commit()
print(f"✓ 已删除: {table}")
success_count += 1
except Exception as e:
print(f"✗ 删除失败: {table} - {str(e)}")
fail_count += 1
# 恢复外键检查
conn.execute(text("SET FOREIGN_KEY_CHECKS = 1"))
conn.commit()
finally:
engine.dispose()
print(f"\n完成: 成功 {success_count} 个, 失败 {fail_count} 个")
def clear_all_tables(self):
"""清空所有表数据"""
tables = self.db_manager.list_tables(self.current_db)
if not tables:
print(f"✓ 数据库 '{self.current_db}' 中没有表")
return
print(
f"\n⚠️ 警告: 即将清空数据库 '{self.current_db}' 中所有 {len(tables)} 个表的数据!"
)
print("⚠️ 表结构会保留,但所有数据将被永久删除!")
response = input("\n确认清空所有表? (yes/no): ").strip().lower()
if response != "yes":
print("✗ 操作已取消")
return
# 创建数据库连接
db_url = (
f"mysql+pymysql://{self.config.get('database.user')}:"
f"{self.config.get('database.password')}@"
f"{self.config.get('database.host')}:{self.config.get('database.port')}"
f"/{self.current_db}"
)
engine = create_engine(db_url, echo=False)
success_count = 0
fail_count = 0
try:
with engine.connect() as conn:
# 禁用外键检查
conn.execute(text("SET FOREIGN_KEY_CHECKS = 0"))
for table in tables:
try:
conn.execute(text(f"TRUNCATE TABLE `{table}`"))
conn.commit()
print(f"✓ 已清空: {table}")
success_count += 1
except Exception as e:
print(f"✗ 清空失败: {table} - {str(e)}")
fail_count += 1
# 恢复外键检查
conn.execute(text("SET FOREIGN_KEY_CHECKS = 1"))
conn.commit()
finally:
engine.dispose()
print(f"\n完成: 成功 {success_count} 个, 失败 {fail_count} 个")
def check_table_exists(self, table: str):
"""检查表是否存在"""
if not table:
print("✗ 请指定表名称")
return
exists = self.db_manager.table_exists(self.current_db, table)
if exists:
print(f"✓ 表存在: {table}")
else:
print(f"✗ 表不存在: {table}")
def show_table_info(self, table: str):
"""显示表结构信息"""
if not table:
print("✗ 请指定表名称")
return
if not self.db_manager.table_exists(self.current_db, table):
print(f"✗ 表不存在: {table}")
return
schema = self.db_manager.get_table_schema(self.current_db, table)
print(f"\n表名: {table}")
print(f"列数: {len(schema.get('columns', []))}")
print(f"索引数: {len(schema.get('indexes', []))}")
print("\n列信息:")
for col in schema.get("columns", []):
nullable = "NULL" if col["nullable"] else "NOT NULL"
key = ""
if col.get("primary_key"):
key = " [PRIMARY KEY]"
print(
f" • {col['name']}: {col['type']} {nullable}{key} - {col.get('comment', '')}"
)
print()
def drop_table(self, table: str):
"""删除指定表"""
if not table:
print("✗ 请指定表名称")
return
if not self.db_manager.table_exists(self.current_db, table):
print(f"✗ 表不存在: {table}")
return
print(f"\n⚠️ 警告: 即将删除表 '{table}' 及其所有数据!")
response = input("确认删除? (yes/no): ").strip().lower()
if response == "yes":
if self.db_manager.drop_table(self.current_db, table, confirm=True):
print(f"✓ 表已删除: {table}")
else:
print(f"✗ 表删除失败: {table}")
else:
print("✗ 操作已取消")
# ==================== 数据操作 ====================
def count_table_rows(self, table: str):
"""统计表记录数"""
if not table:
print("✗ 请指定表名称")
return
if not self.db_manager.table_exists(self.current_db, table):
print(f"✗ 表不存在: {table}")
return
db_url = (
f"mysql+pymysql://{self.config.get('database.user')}:"
f"{self.config.get('database.password')}@"
f"{self.config.get('database.host')}:{self.config.get('database.port')}"
f"/{self.current_db}"
)
engine = create_engine(db_url, echo=False)
try:
with engine.connect() as conn:
result = conn.execute(text(f"SELECT COUNT(*) FROM `{table}`"))
count = result.scalar()
print(f"✓ 表 '{table}' 中有 {count:,} 条记录")
except Exception as e:
print(f"✗ 查询失败: {str(e)}")
finally:
engine.dispose()
def clear_table(self, table: str):
"""清空指定表数据"""
if not table:
print("✗ 请指定表名称")
return
if not self.db_manager.table_exists(self.current_db, table):
print(f"✗ 表不存在: {table}")
return
print(f"\n⚠️ 警告: 即将清空表 '{table}' 的所有数据!")
response = input("确认清空? (yes/no): ").strip().lower()
if response != "yes":
print("✗ 操作已取消")
return
db_url = (
f"mysql+pymysql://{self.config.get('database.user')}:"
f"{self.config.get('database.password')}@"
f"{self.config.get('database.host')}:{self.config.get('database.port')}"
f"/{self.current_db}"
)
engine = create_engine(db_url, echo=False)
try:
with engine.connect() as conn:
conn.execute(text(f"TRUNCATE TABLE `{table}`"))
conn.commit()
print(f"✓ 表已清空: {table}")
except Exception as e:
print(f"✗ 清空失败: {str(e)}")
finally:
engine.dispose()
# ==================== 主循环 ====================
def run(self):
"""运行交互式命令行"""
self.print_banner()
try:
while self.running:
try:
command = input(f"qtrade-db [{self.current_db}]> ").strip()
if command:
self.execute_command(command)
except KeyboardInterrupt:
print("\n\n使用 'exit' 命令退出,或再次按 Ctrl+C 强制退出")
try:
response = input("确认退出? (yes/no): ").strip().lower()
if response == "yes":
self.running = False
print("\n再见!")
except KeyboardInterrupt:
print("\n\n强制退出")
break
except EOFError:
break
finally:
self.db_manager.close()
def main():
"""主函数"""
cli = DatabaseAdminCLI()
cli.run()
if __name__ == "__main__":
main()