staran 0.3.0__tar.gz → 0.4.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. {staran-0.3.0/staran.egg-info → staran-0.4.1}/PKG-INFO +57 -6
  2. {staran-0.3.0 → staran-0.4.1}/README.md +56 -5
  3. staran-0.4.1/setup.py +31 -0
  4. {staran-0.3.0 → staran-0.4.1}/staran/__init__.py +11 -3
  5. staran-0.4.1/staran/engines/__init__.py +65 -0
  6. staran-0.4.1/staran/engines/base.py +255 -0
  7. staran-0.4.1/staran/engines/hive.py +163 -0
  8. staran-0.4.1/staran/engines/spark.py +252 -0
  9. staran-0.4.1/staran/engines/turing.py +439 -0
  10. staran-0.4.1/staran/examples/__init__.py +8 -0
  11. staran-0.4.1/staran/examples/aum_longtail.py +250 -0
  12. staran-0.4.1/staran/examples/aum_longtail_old.py +487 -0
  13. staran-0.4.1/staran/features/__init__.py +59 -0
  14. staran-0.4.1/staran/features/engines.py +284 -0
  15. staran-0.4.1/staran/features/generator.py +603 -0
  16. staran-0.4.1/staran/features/manager.py +155 -0
  17. staran-0.4.1/staran/features/schema.py +193 -0
  18. staran-0.4.1/staran/schemas/__init__.py +28 -0
  19. staran-0.4.1/staran/schemas/aum/__init__.py +314 -0
  20. staran-0.4.1/staran/schemas/document_generator.py +350 -0
  21. {staran-0.3.0 → staran-0.4.1/staran.egg-info}/PKG-INFO +57 -6
  22. staran-0.4.1/staran.egg-info/SOURCES.txt +27 -0
  23. staran-0.3.0/setup.py +0 -23
  24. staran-0.3.0/staran.egg-info/SOURCES.txt +0 -11
  25. {staran-0.3.0 → staran-0.4.1}/LICENSE +0 -0
  26. {staran-0.3.0 → staran-0.4.1}/setup.cfg +0 -0
  27. {staran-0.3.0 → staran-0.4.1}/staran/tools/__init__.py +0 -0
  28. {staran-0.3.0 → staran-0.4.1}/staran/tools/date.py +0 -0
  29. {staran-0.3.0 → staran-0.4.1}/staran.egg-info/dependency_links.txt +0 -0
  30. {staran-0.3.0 → staran-0.4.1}/staran.egg-info/requires.txt +0 -0
  31. {staran-0.3.0 → staran-0.4.1}/staran.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: staran
3
- Version: 0.3.0
3
+ Version: 0.4.1
4
4
  Summary: staran - 高性能Python工具库
5
5
  Home-page: https://github.com/starlxa/staran
6
6
  Author: StarAn
@@ -24,13 +24,25 @@ Dynamic: requires-dist
24
24
  Dynamic: requires-python
25
25
  Dynamic: summary
26
26
 
27
- # Staran - 智能特征工程工具包
27
+ # Star## v0.4.1 新特性
28
+
29
+ - 📋 **独立Schema模块** - 专门的表结构定义和管理模块
30
+ - 📄 **文档自动生成** - 支持Markdown/PDF/HTML格式的技术文档生成
31
+ - 🏢 **业务域支持** - AUM等业务领域的标准表结构定义
32
+ - 🔗 **无缝集成** - Schema与特征工程examples模块完美集成
33
+ - 🛠️ **模块化引擎架构** - 独立的引擎模块,支持Spark、Hive、图灵平台
34
+ - 🔧 **统一接口设计** - 所有引擎提供一致的SQL生成、执行和下载接口
35
+ - 🎯 **继承复用架构** - TuringEngine继承SparkEngine,复用SQL生成逻辑
36
+ - 📦 **清晰代码分离** - SQL生成与平台特定执行逻辑完全分离
37
+ - 🚀 **易于扩展** - 新增数据库支持只需实现BaseEngine接口
38
+ - 📁 **独立引擎存储** - engines/文件夹专门存放所有数据库引擎
39
+ - 🔄 **向后兼容** - 保持对原有API的完全兼容工程工具包
28
40
 
29
41
  ## � 专为机器学习设计的Python工具包
30
42
 
31
43
  Staran是一个强大的特征工程和数据处理工具包,提供从数据到模型的完整解决方案。特别针对工银图灵平台优化,让特征工程和模型训练变得前所未有的简单。
32
44
 
33
- ## ✨ v0.3.0 新特性
45
+ ## ✨ v0.4.1 新特性
34
46
 
35
47
  - �️ **模块化引擎架构** - 独立的引擎模块,支持Spark、Hive、图灵平台
36
48
  - 🔧 **统一接口设计** - 所有引擎提供一致的SQL生成、执行和下载接口
@@ -82,6 +94,40 @@ result = turing_engine.create_table('my_table', sql, execute=True)
82
94
  download = turing_engine.download_table_data('my_table', 'file:///nfsHome/data.parquet')
83
95
  ```
84
96
 
97
+ ### Schema模块 - 表结构管理与文档生成
98
+
99
+ ```python
100
+ from staran import get_aum_schemas, export_aum_docs, SchemaDocumentGenerator
101
+
102
+ # 1. 获取预定义业务表结构
103
+ schemas = get_aum_schemas() # 获取AUM业务域的所有表结构
104
+
105
+ for table_type, schema in schemas.items():
106
+ print(f"{table_type}: {schema.table_name} ({len(schema.fields)}个字段)")
107
+
108
+ # 2. 生成业务文档
109
+ docs = export_aum_docs('./docs', 'markdown') # 生成Markdown格式文档
110
+
111
+ # 3. 自定义文档生成
112
+ generator = SchemaDocumentGenerator()
113
+ doc_path = generator.export_schema_doc(
114
+ schema=schemas['behavior'],
115
+ business_domain="AUM",
116
+ table_type="behavior",
117
+ format_type="markdown"
118
+ )
119
+
120
+ # 4. 与特征工程集成
121
+ from staran import create_aum_example, run_aum_example
122
+
123
+ # 基于预定义schema创建特征工程示例
124
+ example = create_aum_example()
125
+ summary = example.get_summary() # 获取特征统计信息
126
+
127
+ # 一键运行完整流程
128
+ results = run_aum_example('202507') # 生成916个特征
129
+ ```
130
+
85
131
  ### 特征工程 - SQL自动生成
86
132
 
87
133
  ```python
@@ -315,7 +361,12 @@ tomorrow = date.add_days(1) # 202504 (智能处理)
315
361
 
316
362
  ```
317
363
  staran/
318
- ├── __init__.py # 主包入口,v0.3.0功能导出
364
+ ├── __init__.py # 主包入口,v0.4.1功能导出
365
+ ├── schemas/ # 🆕 表结构定义与文档生成模块
366
+ │ ├── __init__.py # Schema模块入口
367
+ │ ├── document_generator.py # 文档生成器 (MD/PDF/HTML)
368
+ │ └── aum/ # AUM业务域表结构
369
+ │ └── __init__.py # AUM表结构定义
319
370
  ├── engines/ # 🆕 模块化引擎架构
320
371
  │ ├── __init__.py # 引擎模块入口
321
372
  │ ├── base.py # BaseEngine抽象基类
@@ -334,7 +385,7 @@ staran/
334
385
  │ ├── __init__.py # 工具模块
335
386
  │ └── date.py # Date类实现
336
387
  ├── setup.py # 安装配置
337
- ├── README.md # 本文档 v0.3.0
388
+ ├── README.md # 本文档 v0.4.1
338
389
  └── quick-upload.sh # 快速部署脚本
339
390
  ```
340
391
 
@@ -510,4 +561,4 @@ MIT License
510
561
 
511
562
  ---
512
563
 
513
- **Staran v0.3.0** - 模块化引擎架构,让机器学习特征工程变得前所未有的简单 🌟
564
+ **Staran v0.4.1** - 模块化引擎架构,让机器学习特征工程变得前所未有的简单 🌟
@@ -1,10 +1,22 @@
1
- # Staran - 智能特征工程工具包
1
+ # Star## v0.4.1 新特性
2
+
3
+ - 📋 **独立Schema模块** - 专门的表结构定义和管理模块
4
+ - 📄 **文档自动生成** - 支持Markdown/PDF/HTML格式的技术文档生成
5
+ - 🏢 **业务域支持** - AUM等业务领域的标准表结构定义
6
+ - 🔗 **无缝集成** - Schema与特征工程examples模块完美集成
7
+ - 🛠️ **模块化引擎架构** - 独立的引擎模块,支持Spark、Hive、图灵平台
8
+ - 🔧 **统一接口设计** - 所有引擎提供一致的SQL生成、执行和下载接口
9
+ - 🎯 **继承复用架构** - TuringEngine继承SparkEngine,复用SQL生成逻辑
10
+ - 📦 **清晰代码分离** - SQL生成与平台特定执行逻辑完全分离
11
+ - 🚀 **易于扩展** - 新增数据库支持只需实现BaseEngine接口
12
+ - 📁 **独立引擎存储** - engines/文件夹专门存放所有数据库引擎
13
+ - 🔄 **向后兼容** - 保持对原有API的完全兼容工程工具包
2
14
 
3
15
  ## � 专为机器学习设计的Python工具包
4
16
 
5
17
  Staran是一个强大的特征工程和数据处理工具包,提供从数据到模型的完整解决方案。特别针对工银图灵平台优化,让特征工程和模型训练变得前所未有的简单。
6
18
 
7
- ## ✨ v0.3.0 新特性
19
+ ## ✨ v0.4.1 新特性
8
20
 
9
21
  - �️ **模块化引擎架构** - 独立的引擎模块,支持Spark、Hive、图灵平台
10
22
  - 🔧 **统一接口设计** - 所有引擎提供一致的SQL生成、执行和下载接口
@@ -56,6 +68,40 @@ result = turing_engine.create_table('my_table', sql, execute=True)
56
68
  download = turing_engine.download_table_data('my_table', 'file:///nfsHome/data.parquet')
57
69
  ```
58
70
 
71
+ ### Schema模块 - 表结构管理与文档生成
72
+
73
+ ```python
74
+ from staran import get_aum_schemas, export_aum_docs, SchemaDocumentGenerator
75
+
76
+ # 1. 获取预定义业务表结构
77
+ schemas = get_aum_schemas() # 获取AUM业务域的所有表结构
78
+
79
+ for table_type, schema in schemas.items():
80
+ print(f"{table_type}: {schema.table_name} ({len(schema.fields)}个字段)")
81
+
82
+ # 2. 生成业务文档
83
+ docs = export_aum_docs('./docs', 'markdown') # 生成Markdown格式文档
84
+
85
+ # 3. 自定义文档生成
86
+ generator = SchemaDocumentGenerator()
87
+ doc_path = generator.export_schema_doc(
88
+ schema=schemas['behavior'],
89
+ business_domain="AUM",
90
+ table_type="behavior",
91
+ format_type="markdown"
92
+ )
93
+
94
+ # 4. 与特征工程集成
95
+ from staran import create_aum_example, run_aum_example
96
+
97
+ # 基于预定义schema创建特征工程示例
98
+ example = create_aum_example()
99
+ summary = example.get_summary() # 获取特征统计信息
100
+
101
+ # 一键运行完整流程
102
+ results = run_aum_example('202507') # 生成916个特征
103
+ ```
104
+
59
105
  ### 特征工程 - SQL自动生成
60
106
 
61
107
  ```python
@@ -289,7 +335,12 @@ tomorrow = date.add_days(1) # 202504 (智能处理)
289
335
 
290
336
  ```
291
337
  staran/
292
- ├── __init__.py # 主包入口,v0.3.0功能导出
338
+ ├── __init__.py # 主包入口,v0.4.1功能导出
339
+ ├── schemas/ # 🆕 表结构定义与文档生成模块
340
+ │ ├── __init__.py # Schema模块入口
341
+ │ ├── document_generator.py # 文档生成器 (MD/PDF/HTML)
342
+ │ └── aum/ # AUM业务域表结构
343
+ │ └── __init__.py # AUM表结构定义
293
344
  ├── engines/ # 🆕 模块化引擎架构
294
345
  │ ├── __init__.py # 引擎模块入口
295
346
  │ ├── base.py # BaseEngine抽象基类
@@ -308,7 +359,7 @@ staran/
308
359
  │ ├── __init__.py # 工具模块
309
360
  │ └── date.py # Date类实现
310
361
  ├── setup.py # 安装配置
311
- ├── README.md # 本文档 v0.3.0
362
+ ├── README.md # 本文档 v0.4.1
312
363
  └── quick-upload.sh # 快速部署脚本
313
364
  ```
314
365
 
@@ -484,4 +535,4 @@ MIT License
484
535
 
485
536
  ---
486
537
 
487
- **Staran v0.3.0** - 模块化引擎架构,让机器学习特征工程变得前所未有的简单 🌟
538
+ **Staran v0.4.1** - 模块化引擎架构,让机器学习特征工程变得前所未有的简单 🌟
staran-0.4.1/setup.py ADDED
@@ -0,0 +1,31 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name="staran",
5
+ version="0.4.1",
6
+ description="staran - 高性能Python工具库",
7
+ long_description=open("README.md", encoding="utf-8").read(),
8
+ long_description_content_type="text/markdown",
9
+ author="StarAn",
10
+ author_email="starlxa@icloud.com",
11
+ url="https://github.com/starlxa/staran",
12
+ packages=[
13
+ "staran",
14
+ "staran.tools",
15
+ "staran.features",
16
+ "staran.engines",
17
+ "staran.examples",
18
+ "staran.schemas",
19
+ "staran.schemas.aum",
20
+ ],
21
+ install_requires=[
22
+ "datetime",
23
+ "calendar",
24
+ "re",
25
+ ],
26
+ classifiers=[
27
+ "Programming Language :: Python :: 3",
28
+ "License :: OSI Approved :: MIT License",
29
+ ],
30
+ python_requires=">=3.7",
31
+ )
@@ -158,9 +158,13 @@ from .features import (
158
158
  )
159
159
  from .engines import SparkEngine, HiveEngine, TuringEngine, BaseEngine, create_engine, create_turing_engine
160
160
 
161
- # 示例模块
161
+ # Examples模块 - 业务示例
162
162
  from .examples import create_aum_example, run_aum_example
163
163
 
164
+ # Schemas模块 - 表结构定义与文档生成
165
+ from .schemas import SchemaDocumentGenerator
166
+ from .schemas.aum import get_aum_schemas, export_aum_docs
167
+
164
168
  # 图灵平台引擎 (可选导入,避免依赖问题)
165
169
  try:
166
170
  from .features import quick_create_and_download
@@ -194,6 +198,10 @@ __all__ = [
194
198
  # 示例模块
195
199
  'create_aum_example',
196
200
  'run_aum_example',
201
+ # 表结构模块
202
+ 'SchemaDocumentGenerator',
203
+ 'get_aum_schemas',
204
+ 'export_aum_docs',
197
205
  # 向后兼容
198
206
  'SQLManager',
199
207
  'SparkSQLGenerator'
@@ -206,9 +214,9 @@ if _TURING_AVAILABLE:
206
214
  ])
207
215
 
208
216
  # 包信息
209
- __version__ = '0.2.4'
217
+ __version__ = '0.3.0'
210
218
  __author__ = 'Staran Team'
211
- __description__ = 'Smart feature engineering toolkit with modular engine architecture and examples'
219
+ __description__ = 'Smart feature engineering toolkit with schema management, document generation and business examples'
212
220
  __license__ = 'MIT'
213
221
 
214
222
  # 便捷函数示例
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ 数据库引擎模块
6
+ 提供统一的数据库引擎接口
7
+ """
8
+
9
+ # 基础组件
10
+ from .base import BaseEngine, DatabaseType
11
+
12
+ # 具体引擎实现
13
+ from .spark import SparkEngine
14
+ from .hive import HiveEngine
15
+
16
+ # 图灵平台引擎 (可选导入)
17
+ try:
18
+ from .turing import TuringEngine, create_turing_engine
19
+ _TURING_AVAILABLE = True
20
+ except ImportError:
21
+ TuringEngine = None
22
+ create_turing_engine = None
23
+ _TURING_AVAILABLE = False
24
+
25
+ # 便捷创建函数
26
+ def create_engine(engine_type: str, database_name: str, **kwargs) -> BaseEngine:
27
+ """
28
+ 创建数据库引擎的便捷函数
29
+
30
+ Args:
31
+ engine_type: 引擎类型 ('spark', 'hive', 'turing')
32
+ database_name: 数据库名称
33
+ **kwargs: 其他参数
34
+
35
+ Returns:
36
+ 数据库引擎实例
37
+ """
38
+ engine_type = engine_type.lower()
39
+
40
+ if engine_type == 'spark':
41
+ return SparkEngine(database_name, **kwargs)
42
+ elif engine_type == 'hive':
43
+ return HiveEngine(database_name, **kwargs)
44
+ elif engine_type == 'turing':
45
+ if not _TURING_AVAILABLE:
46
+ raise ImportError("TuringEngine不可用,请确保turingPythonLib已安装")
47
+ return TuringEngine(database_name, **kwargs)
48
+ else:
49
+ raise ValueError(f"不支持的引擎类型: {engine_type}")
50
+
51
+ # 主要导出
52
+ __all__ = [
53
+ 'BaseEngine',
54
+ 'DatabaseType',
55
+ 'SparkEngine',
56
+ 'HiveEngine',
57
+ 'create_engine'
58
+ ]
59
+
60
+ # 如果图灵引擎可用,添加到导出
61
+ if _TURING_AVAILABLE:
62
+ __all__.extend([
63
+ 'TuringEngine',
64
+ 'create_turing_engine'
65
+ ])
@@ -0,0 +1,255 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ 数据库引擎基类
6
+ 定义统一的SQL生成、执行和数据下载接口
7
+ """
8
+
9
+ from abc import ABC, abstractmethod
10
+ from typing import Dict, Any, Optional, List, Callable
11
+ from enum import Enum
12
+ from datetime import datetime
13
+
14
+
15
+ class DatabaseType(Enum):
16
+ """数据库类型枚举"""
17
+ SPARK = "spark"
18
+ HIVE = "hive"
19
+ MYSQL = "mysql"
20
+ POSTGRESQL = "postgresql"
21
+
22
+
23
+ class BaseEngine(ABC):
24
+ """
25
+ 数据库引擎基类
26
+ 整合SQL生成、执行和数据下载功能
27
+ """
28
+
29
+ def __init__(self, database_name: str, sql_executor: Optional[Callable] = None):
30
+ """
31
+ 初始化引擎
32
+
33
+ Args:
34
+ database_name: 数据库名称
35
+ sql_executor: SQL执行器函数 (可选)
36
+ """
37
+ self.database_name = database_name
38
+ self.sql_executor = sql_executor
39
+ self.execution_history = []
40
+
41
+ @abstractmethod
42
+ def get_engine_type(self) -> DatabaseType:
43
+ """获取引擎类型"""
44
+ pass
45
+
46
+ @abstractmethod
47
+ def get_engine_name(self) -> str:
48
+ """获取引擎名称"""
49
+ pass
50
+
51
+ # ==================== SQL生成方法 ====================
52
+
53
+ @abstractmethod
54
+ def generate_create_table_sql(self, table_name: str, select_sql: str,
55
+ if_not_exists: bool = True) -> str:
56
+ """生成创建表的SQL"""
57
+ pass
58
+
59
+ @abstractmethod
60
+ def generate_insert_sql(self, table_name: str, select_sql: str) -> str:
61
+ """生成插入数据的SQL"""
62
+ pass
63
+
64
+ @abstractmethod
65
+ def generate_drop_table_sql(self, table_name: str, if_exists: bool = True) -> str:
66
+ """生成删除表的SQL"""
67
+ pass
68
+
69
+ def generate_aggregation_sql(self, schema, year: int, month: int,
70
+ aggregation_types: List[str]) -> str:
71
+ """生成聚合特征SQL (可被子类重写)"""
72
+ base_table = self.get_full_table_name(schema.table_name)
73
+ pk_field = schema.primary_key
74
+ date_field = schema.date_field
75
+
76
+ # 获取可聚合字段
77
+ agg_fields = [field for field in schema.fields.values() if field.aggregatable]
78
+
79
+ # 构建聚合选择语句
80
+ select_parts = [pk_field, f"'{year}-{month:02d}-01' as feature_month"]
81
+
82
+ for field in agg_fields:
83
+ for agg_type in aggregation_types:
84
+ alias = f"{field.name}_{agg_type}"
85
+ select_parts.append(f"{agg_type.upper()}({field.name}) as {alias}")
86
+
87
+ sql = f"""
88
+ SELECT {', '.join(select_parts)}
89
+ FROM {base_table}
90
+ WHERE YEAR({date_field}) = {year}
91
+ AND MONTH({date_field}) = {month}
92
+ GROUP BY {pk_field}
93
+ """
94
+
95
+ return sql.strip()
96
+
97
+ # ==================== SQL执行方法 ====================
98
+
99
+ def execute_sql(self, sql: str, description: str = "") -> Any:
100
+ """
101
+ 执行SQL语句
102
+
103
+ Args:
104
+ sql: SQL语句
105
+ description: 执行描述
106
+
107
+ Returns:
108
+ 执行结果
109
+ """
110
+ if self.sql_executor:
111
+ result = self.sql_executor(sql)
112
+ self.execution_history.append({
113
+ 'sql': sql,
114
+ 'description': description,
115
+ 'timestamp': datetime.now(),
116
+ 'result': result
117
+ })
118
+ return result
119
+ else:
120
+ print(f"SQL (未执行): {description or 'SQL语句'}")
121
+ print(f" {sql[:100]}...")
122
+ return None
123
+
124
+ def create_table(self, table_name: str, select_sql: str,
125
+ execute: bool = False) -> Dict[str, Any]:
126
+ """
127
+ 创建表
128
+
129
+ Args:
130
+ table_name: 表名
131
+ select_sql: 选择SQL
132
+ execute: 是否立即执行
133
+
134
+ Returns:
135
+ 操作结果
136
+ """
137
+ full_table_name = self.get_full_table_name(table_name)
138
+ create_sql = self.generate_create_table_sql(full_table_name, select_sql)
139
+
140
+ result = {
141
+ 'table_name': table_name,
142
+ 'full_table_name': full_table_name,
143
+ 'sql': create_sql,
144
+ 'executed': execute
145
+ }
146
+
147
+ if execute:
148
+ exec_result = self.execute_sql(create_sql, f"创建表 {table_name}")
149
+ result['execution_result'] = exec_result
150
+ result['status'] = 'success' if exec_result is not None else 'simulated'
151
+ else:
152
+ result['status'] = 'prepared'
153
+
154
+ return result
155
+
156
+ # ==================== 数据下载方法 ====================
157
+
158
+ @abstractmethod
159
+ def download_table_data(self, table_name: str, output_path: str,
160
+ **kwargs) -> Dict[str, Any]:
161
+ """
162
+ 下载表数据 (子类必须实现)
163
+
164
+ Args:
165
+ table_name: 表名
166
+ output_path: 输出路径
167
+ **kwargs: 其他参数
168
+
169
+ Returns:
170
+ 下载结果
171
+ """
172
+ pass
173
+
174
+ def download_query_result(self, sql: str, output_path: str,
175
+ **kwargs) -> Dict[str, Any]:
176
+ """
177
+ 下载查询结果 (默认实现,子类可重写)
178
+
179
+ Args:
180
+ sql: 查询SQL
181
+ output_path: 输出路径
182
+ **kwargs: 其他参数
183
+
184
+ Returns:
185
+ 下载结果
186
+ """
187
+ # 创建临时表然后下载
188
+ temp_table = f"temp_query_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
189
+
190
+ try:
191
+ # 创建临时表
192
+ self.create_table(temp_table, sql, execute=True)
193
+
194
+ # 下载数据
195
+ result = self.download_table_data(temp_table, output_path, **kwargs)
196
+
197
+ # 清理临时表
198
+ self.drop_table(temp_table, execute=True)
199
+
200
+ return result
201
+
202
+ except Exception as e:
203
+ return {
204
+ 'status': 'error',
205
+ 'message': f"下载查询结果失败: {str(e)}",
206
+ 'error': str(e)
207
+ }
208
+
209
+ # ==================== 工具方法 ====================
210
+
211
+ def get_full_table_name(self, table_name: str) -> str:
212
+ """获取完整的表名(包含数据库名)"""
213
+ if '.' in table_name:
214
+ return table_name # 已经包含数据库名
215
+ return f"{self.database_name}.{table_name}"
216
+
217
+ def generate_table_name(self, base_name: str, year: int, month: int,
218
+ suffix: str = "raw") -> str:
219
+ """
220
+ 生成标准化的表名
221
+ 格式: {base_name}_{yyyy}_{MM}_{suffix}
222
+ """
223
+ return f"{base_name}_{year}_{month:02d}_{suffix}"
224
+
225
+ def drop_table(self, table_name: str, execute: bool = False) -> Dict[str, Any]:
226
+ """删除表"""
227
+ full_table_name = self.get_full_table_name(table_name)
228
+ drop_sql = self.generate_drop_table_sql(full_table_name)
229
+
230
+ result = {
231
+ 'table_name': table_name,
232
+ 'full_table_name': full_table_name,
233
+ 'sql': drop_sql,
234
+ 'executed': execute
235
+ }
236
+
237
+ if execute:
238
+ exec_result = self.execute_sql(drop_sql, f"删除表 {table_name}")
239
+ result['execution_result'] = exec_result
240
+ result['status'] = 'success' if exec_result is not None else 'simulated'
241
+ else:
242
+ result['status'] = 'prepared'
243
+
244
+ return result
245
+
246
+ def get_execution_history(self) -> List[Dict]:
247
+ """获取SQL执行历史"""
248
+ return self.execution_history.copy()
249
+
250
+ def clear_history(self):
251
+ """清空执行历史"""
252
+ self.execution_history.clear()
253
+
254
+ def __str__(self):
255
+ return f"{self.__class__.__name__}(db={self.database_name}, type={self.get_engine_type().value})"