flowdeck 0.2.1__py3-none-any.whl
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.
- flowdeck/__init__.py +65 -0
- flowdeck/_version.py +1 -0
- flowdeck/api/__init__.py +216 -0
- flowdeck/api/routers/__init__.py +1 -0
- flowdeck/api/routers/dashboard.py +73 -0
- flowdeck/api/routers/health.py +26 -0
- flowdeck/api/routers/notifications.py +92 -0
- flowdeck/api/routers/pipelines.py +274 -0
- flowdeck/api/routers/runs.py +227 -0
- flowdeck/api/routers/schedule_exceptions.py +141 -0
- flowdeck/api/routers/system.py +386 -0
- flowdeck/api/routers/ui_pipelines.py +507 -0
- flowdeck/api/routers/ui_task_tools.py +275 -0
- flowdeck/api/routers/webhooks.py +115 -0
- flowdeck/auth/__init__.py +0 -0
- flowdeck/auth/basic.py +65 -0
- flowdeck/cli.py +40 -0
- flowdeck/config.py +240 -0
- flowdeck/database/__init__.py +0 -0
- flowdeck/database/base.py +91 -0
- flowdeck/database/models.py +218 -0
- flowdeck/database/repository.py +1231 -0
- flowdeck/logger/__init__.py +122 -0
- flowdeck/logger/formatter.py +112 -0
- flowdeck/logger/web_socket_handler.py +85 -0
- flowdeck/notifications/__init__.py +13 -0
- flowdeck/notifications/email_sender.py +79 -0
- flowdeck/notifications/engine.py +412 -0
- flowdeck/notifications/rules.py +22 -0
- flowdeck/notifications/table_image.py +273 -0
- flowdeck/notifications/task_result.py +478 -0
- flowdeck/notifications/templates.py +224 -0
- flowdeck/orchestrator/__init__.py +380 -0
- flowdeck/orchestrator/executor.py +661 -0
- flowdeck/pipeline/__init__.py +5 -0
- flowdeck/pipeline/_utils.py +11 -0
- flowdeck/pipeline/context.py +13 -0
- flowdeck/pipeline/pipeline.py +40 -0
- flowdeck/pipeline/schedule.py +125 -0
- flowdeck/pipeline/task.py +104 -0
- flowdeck/pipeline/trigger.py +22 -0
- flowdeck/schemas.py +11 -0
- flowdeck/static/assets/BackfillModal-BViyo-00.js +1 -0
- flowdeck/static/assets/BackfillModal-D6je7CRx.css +1 -0
- flowdeck/static/assets/Btn-B77BQZvQ.js +1 -0
- flowdeck/static/assets/Btn-D6G_tsbF.css +1 -0
- flowdeck/static/assets/DashboardView-BM-S5j64.js +1 -0
- flowdeck/static/assets/DashboardView-CBu0kYw6.css +1 -0
- flowdeck/static/assets/DatePickerField-IOKwxOwp.js +830 -0
- flowdeck/static/assets/Empty-B5kRTX_h.css +1 -0
- flowdeck/static/assets/Empty-ScitfHnD.js +1 -0
- flowdeck/static/assets/Modal-7xA4aZKG.js +1 -0
- flowdeck/static/assets/Modal-BNFhtIvK.css +1 -0
- flowdeck/static/assets/NotificationsView-BTkWFeLt.css +1 -0
- flowdeck/static/assets/NotificationsView-BkofWdjj.js +1 -0
- flowdeck/static/assets/NotifySettings-BFdtzy6K.js +1 -0
- flowdeck/static/assets/NotifySettings-D9Nn2RLl.css +1 -0
- flowdeck/static/assets/NumInput--MSEekvd.js +582 -0
- flowdeck/static/assets/NumInput-DfqPA-uG.css +1 -0
- flowdeck/static/assets/PageHeader-3D30Zbvm.js +1 -0
- flowdeck/static/assets/PageHeader-BULVGwbD.css +1 -0
- flowdeck/static/assets/PipelineDetailView-89815vAO.js +1 -0
- flowdeck/static/assets/PipelineDetailView-B_iVBCYT.css +1 -0
- flowdeck/static/assets/PipelinesView-CtDub3qu.js +1 -0
- flowdeck/static/assets/PipelinesView-DC9QO4Wr.css +1 -0
- flowdeck/static/assets/PrettyJson-DjAv38hk.css +1 -0
- flowdeck/static/assets/PrettyJson-_gjY71Cb.js +1 -0
- flowdeck/static/assets/RecentFailuresView-CruW_Dj8.js +1 -0
- flowdeck/static/assets/RecentFailuresView-DjQsiRv9.css +1 -0
- flowdeck/static/assets/RunDetailView--NojY8JX.css +1 -0
- flowdeck/static/assets/RunDetailView-2ZVPmVgW.js +5 -0
- flowdeck/static/assets/ScheduleExceptionsView-DdccyMcD.js +2 -0
- flowdeck/static/assets/ScheduleExceptionsView-pWTB9mSE.css +1 -0
- flowdeck/static/assets/SettingsView-BwlizulV.js +4 -0
- flowdeck/static/assets/SettingsView-D4ybFG31.css +1 -0
- flowdeck/static/assets/StatCard-CdPYF8jZ.js +1 -0
- flowdeck/static/assets/StatCard-D06FdLL9.css +1 -0
- flowdeck/static/assets/StatsView-88bkL-AN.css +1 -0
- flowdeck/static/assets/StatsView-DONGQHCc.js +18 -0
- flowdeck/static/assets/StatusBadge-BDBPRgRa.css +1 -0
- flowdeck/static/assets/StatusBadge-DzUDQ0X_.js +1 -0
- flowdeck/static/assets/ToggleSwitch-KMgLwPsM.js +1 -0
- flowdeck/static/assets/ToggleSwitch-UNHeNS9K.css +1 -0
- flowdeck/static/assets/UiPipelinesView-BgzBgUYR.css +1 -0
- flowdeck/static/assets/UiPipelinesView-WTYqKxB5.js +2 -0
- flowdeck/static/assets/UiTaskEditorView-BgYyqqgT.js +10 -0
- flowdeck/static/assets/UiTaskEditorView-Dl6zmLDP.css +1 -0
- flowdeck/static/assets/_plugin-vue_export-helper-OBKhRxFI.js +12 -0
- flowdeck/static/assets/chakra-petch-latin-400-normal-D7EtbySE.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-400-normal-SafcrIr2.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-500-normal-BR1ody1F.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-500-normal-CnUQnZ4D.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-600-normal-DQKfcdKo.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-600-normal-DVQm9bgb.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-700-normal-CnDBPjkL.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-700-normal-D1s_c2du.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-400-normal-C8u6EFkq.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-400-normal-MNNNbyh_.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-500-normal-BCHeNDEx.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-500-normal-gA6791b0.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-600-normal-CdGvbdDU.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-600-normal-nL80L4xU.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-700-normal-BeviJPUl.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-700-normal-DAkvJhej.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-thai-400-normal-Bw1Q-fVY.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-thai-400-normal-KdzBjiWs.woff +0 -0
- flowdeck/static/assets/chakra-petch-thai-500-normal-CJG_V2_m.woff +0 -0
- flowdeck/static/assets/chakra-petch-thai-500-normal-DeexCGiz.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-thai-600-normal-BiM5MXH8.woff +0 -0
- flowdeck/static/assets/chakra-petch-thai-600-normal-C620THcd.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-thai-700-normal-B7WL5pBr.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-thai-700-normal-vZLZ_5L8.woff +0 -0
- flowdeck/static/assets/chakra-petch-vietnamese-400-normal-Cn7ya5On.woff +0 -0
- flowdeck/static/assets/chakra-petch-vietnamese-500-normal-BVzUBLGs.woff +0 -0
- flowdeck/static/assets/chakra-petch-vietnamese-600-normal-Pvj4qcw_.woff +0 -0
- flowdeck/static/assets/chakra-petch-vietnamese-700-normal-gQuUA8Wu.woff +0 -0
- flowdeck/static/assets/index-DpymzEZv.css +1 -0
- flowdeck/static/assets/index-DuXbXiXo.js +2 -0
- flowdeck/static/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-cyrillic-500-normal-DJqRU3vO.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-cyrillic-500-normal-DmUKJPL_.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-cyrillic-700-normal-BWTpRfYl.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-cyrillic-700-normal-CEoEElIJ.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-greek-500-normal-D7SFKleX.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-greek-500-normal-JpySY46c.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-greek-700-normal-C6CZE3T8.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-greek-700-normal-DEigVDxa.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-500-normal-CJOVTJB7.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-700-normal-BYuf6tUa.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-700-normal-D3wTyLJW.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-ext-500-normal-Cut-4mMH.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-ext-500-normal-ckzbgY84.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-ext-700-normal-CZipNAKV.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-ext-700-normal-CxPITLHs.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-vietnamese-500-normal-DNRqzVM1.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-vietnamese-700-normal-BDLVIk2r.woff +0 -0
- flowdeck/static/assets/light-B0F-b5Z6.js +20 -0
- flowdeck/static/assets/runtime-dom.esm-bundler-DESsN8Jj.js +2 -0
- flowdeck/static/favicon.svg +13 -0
- flowdeck/static/index.html +18 -0
- flowdeck/storage.py +145 -0
- flowdeck/tasks/__init__.py +1 -0
- flowdeck/tasks/http_executor.py +985 -0
- flowdeck/tasks/paramdefs.py +170 -0
- flowdeck/tasks/paramextract.py +185 -0
- flowdeck/tasks/python_executor.py +234 -0
- flowdeck/tasks/sql_executor.py +683 -0
- flowdeck/tasks/timevars.py +125 -0
- flowdeck/tasks/ui_registry.py +394 -0
- flowdeck-0.2.1.dist-info/METADATA +228 -0
- flowdeck-0.2.1.dist-info/RECORD +163 -0
- flowdeck-0.2.1.dist-info/WHEEL +4 -0
- flowdeck-0.2.1.dist-info/entry_points.txt +2 -0
- flowdeck-0.2.1.dist-info/licenses/LICENSE +293 -0
|
@@ -0,0 +1,683 @@
|
|
|
1
|
+
"""SQL / 存储过程执行器(UI 任务使用)。
|
|
2
|
+
|
|
3
|
+
执行逻辑与 TotalScheduled 的 sql_scheduler 保持一致(成熟路径复用):
|
|
4
|
+
- 存储过程:构建 ``EXEC @result = ...`` 脚本,显式 ``SET XACT_ABORT ON``
|
|
5
|
+
保证出错回滚,收集结果集(每个最多保留 20 行防大结果集撑爆内存),
|
|
6
|
+
最后一个结果集为脚本生成的返回值;
|
|
7
|
+
- SQL 脚本:直接执行返回 rowcount(DML 受影响行数,SELECT 恒为 0),
|
|
8
|
+
返回行的语句(SELECT)附限量结果集 result_sets(每集最多 20 行);
|
|
9
|
+
- ``${data_date}`` 等时间变量在执行时渲染(见 timevars),补数时可用
|
|
10
|
+
overrides 覆盖为历史日期。
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import logging
|
|
14
|
+
import time
|
|
15
|
+
from typing import Any, Dict, List, Optional, Sequence
|
|
16
|
+
|
|
17
|
+
from flowdeck.tasks.timevars import build_time_vars, render_vars
|
|
18
|
+
|
|
19
|
+
PROC_OUTPUT_ROW_LIMIT = 20
|
|
20
|
+
"""每个结果集最多保留的行数(防内存爆):存储过程输出与 SQL 脚本任务的
|
|
21
|
+
SELECT 结果共用此上限,定时任务不应依赖任务输出搬运海量数据"""
|
|
22
|
+
|
|
23
|
+
_logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _json_safe(value: Any) -> Any:
|
|
27
|
+
"""保持可 JSON 序列化的类型不变(date/Decimal 等转字符串)。"""
|
|
28
|
+
if value is None or isinstance(value, (bool, int, float, str)):
|
|
29
|
+
return value
|
|
30
|
+
return str(value)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _format_sql_literal(value: Any) -> str:
|
|
34
|
+
"""将参数值格式化为 SQL 字面量(值来自任务定义者自己,视为可信输入)。"""
|
|
35
|
+
if value is None:
|
|
36
|
+
return "NULL"
|
|
37
|
+
if isinstance(value, bool):
|
|
38
|
+
return "1" if value else "0"
|
|
39
|
+
if isinstance(value, (int, float)):
|
|
40
|
+
return str(value)
|
|
41
|
+
return "N'" + str(value).replace("'", "''") + "'"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def build_procedure_script(procedure: str, params: Optional[Dict[str, Any]]) -> str:
|
|
45
|
+
"""构建存储过程执行脚本:传入参数、捕获返回值并带回。"""
|
|
46
|
+
args = ", ".join(
|
|
47
|
+
f"@{name} = {_format_sql_literal(value)}"
|
|
48
|
+
for name, value in (params or {}).items()
|
|
49
|
+
)
|
|
50
|
+
arg_str = (" " + args) if args else ""
|
|
51
|
+
return "\n".join(
|
|
52
|
+
[
|
|
53
|
+
"SET NOCOUNT ON;",
|
|
54
|
+
"SET XACT_ABORT ON;",
|
|
55
|
+
"DECLARE @result int;",
|
|
56
|
+
f"EXEC @result = {procedure}{arg_str};",
|
|
57
|
+
"SELECT @result AS result;",
|
|
58
|
+
]
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def render_task_sql(
|
|
63
|
+
task_type: str,
|
|
64
|
+
sql_text: str,
|
|
65
|
+
params: Optional[Dict[str, Any]] = None,
|
|
66
|
+
var_overrides: Optional[Dict[str, str]] = None,
|
|
67
|
+
now: Optional[Any] = None,
|
|
68
|
+
var_defaults: Optional[Dict[str, str]] = None,
|
|
69
|
+
var_names: Optional[Sequence[str]] = None,
|
|
70
|
+
):
|
|
71
|
+
"""渲染时间变量,返回 ``(最终SQL脚本, 存储过程参数)``。
|
|
72
|
+
|
|
73
|
+
- sql 类型:渲染 SQL 脚本文本;
|
|
74
|
+
- procedure 类型:存储过程名不渲染,字符串型参数值渲染(如
|
|
75
|
+
``{"数据日期": "${data_date}"}``)。
|
|
76
|
+
var_overrides 用于补数/手动运行覆盖变量(如 data_date=2026-10-01);
|
|
77
|
+
var_defaults / var_names 传入任务声明的动态参数(默认值表 / 全部参数名),
|
|
78
|
+
缺省 None 时行为与历史版本完全一致。
|
|
79
|
+
"""
|
|
80
|
+
values = build_time_vars(
|
|
81
|
+
var_overrides, now=now, declared=var_defaults, declared_names=var_names
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
if task_type == "procedure":
|
|
85
|
+
rendered_params = {
|
|
86
|
+
name: (
|
|
87
|
+
render_vars(value, values, var_names) if isinstance(value, str) else value
|
|
88
|
+
)
|
|
89
|
+
for name, value in (params or {}).items()
|
|
90
|
+
}
|
|
91
|
+
return build_procedure_script(sql_text, rendered_params), rendered_params
|
|
92
|
+
|
|
93
|
+
return render_vars(sql_text, values, var_names), None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def extract_odbc_driver(conn_str: str) -> Optional[str]:
|
|
97
|
+
"""从 ODBC 连接串解析 DRIVER= 值(关键字大小写不敏感,支持 {大括号} 写法)。
|
|
98
|
+
|
|
99
|
+
连接串无 DRIVER 键时返回 None(此时无法判断驱动是否安装)。
|
|
100
|
+
"""
|
|
101
|
+
for part in conn_str.split(";"):
|
|
102
|
+
key, _, value = part.partition("=")
|
|
103
|
+
if key.strip().upper() == "DRIVER" and value.strip():
|
|
104
|
+
return value.strip().strip("{}") or None
|
|
105
|
+
return None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
# ---------------------------------------------------------------------------
|
|
109
|
+
# 数据源类型路由:三条执行路径(URL 形态自动分派,连接串零迁移)
|
|
110
|
+
# 1. pyodbc 路径(备选):传统 ODBC 串(DRIVER=...;SERVER=...)与 mssql 系 URL
|
|
111
|
+
# 2. PEP 249 直连路径:MySQL/PG 自家精确支持的 drivername(pip 驱动直连,
|
|
112
|
+
# 支持 procedure 多结果集收集)
|
|
113
|
+
# 3. SQLAlchemy 通用方言路径:其余一切 URL(支持面由用户 pip 安装的
|
|
114
|
+
# 方言包决定,Airflow/Superset 同思路;仅支持 SQL 脚本任务)
|
|
115
|
+
# ---------------------------------------------------------------------------
|
|
116
|
+
|
|
117
|
+
# PEP 249 直连路径精确支持的 drivername →(import 模块名,驱动展示名,安装提示)。
|
|
118
|
+
# 其余 mysql+X / postgresql+X 变体(mysqlconnector、asyncpg 等)走 SQLAlchemy
|
|
119
|
+
# 通用路径按 URL 声明执行——绝不静默偷换用户声明的驱动。
|
|
120
|
+
MSSQL_INSTALL_HINT = 'pip install "flowdeck[mssql]"'
|
|
121
|
+
PEP249_DRIVERS = {
|
|
122
|
+
"mysql": ("pymysql", "PyMySQL", 'pip install "flowdeck[mysql]"'),
|
|
123
|
+
"mysql+pymysql": ("pymysql", "PyMySQL", 'pip install "flowdeck[mysql]"'),
|
|
124
|
+
"postgresql": ("psycopg", "psycopg 3", 'pip install "flowdeck[postgres]"'),
|
|
125
|
+
"postgresql+psycopg": ("psycopg", "psycopg 3", 'pip install "flowdeck[postgres]"'),
|
|
126
|
+
"postgresql+psycopg2": ("psycopg2", "psycopg2", "pip install psycopg2-binary"),
|
|
127
|
+
}
|
|
128
|
+
"""drivername 精确映射(含安装提示);install_hint 同时被 datasources 端点
|
|
129
|
+
下发给前端,保持单一事实源。psycopg2 不入 extras(存量生态,用户自装)。"""
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _url_drivername(conn_str: str) -> Optional[str]:
|
|
133
|
+
"""连接串若为 URL 形态,返回小写 drivername(scheme[+driver]),否则 None。"""
|
|
134
|
+
s = conn_str.strip()
|
|
135
|
+
if "://" not in s:
|
|
136
|
+
return None
|
|
137
|
+
return s.split("://", 1)[0].lower()
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def datasource_kind(conn_str: str) -> str:
|
|
141
|
+
"""按连接串形态判断数据源类型:mysql / postgres / sqlalchemy / mssql。
|
|
142
|
+
|
|
143
|
+
- URL 的 drivername 在 PEP249_DRIVERS 中 → mysql / postgres(直连路径,
|
|
144
|
+
含 psycopg2;非 URL 的串一律按 ODBC 处理,MySQL/PG 必然是 URL 形态);
|
|
145
|
+
- 其余含 ``://`` 的 URL → ``sqlalchemy``(通用方言路径);
|
|
146
|
+
mssql 系 URL(mssql、mssql+pyodbc 等)→ mssql(pyodbc 路径);
|
|
147
|
+
- 其余(传统 ``SERVER=...;DRIVER=...`` ODBC 连接串)→ mssql。
|
|
148
|
+
"""
|
|
149
|
+
s = conn_str.strip().lower()
|
|
150
|
+
drivername = _url_drivername(s)
|
|
151
|
+
if drivername is not None:
|
|
152
|
+
if drivername in PEP249_DRIVERS:
|
|
153
|
+
return "mysql" if drivername.startswith("mysql") else "postgres"
|
|
154
|
+
if drivername.startswith("mssql"):
|
|
155
|
+
return "mssql"
|
|
156
|
+
return "sqlalchemy"
|
|
157
|
+
return "mssql"
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
MSSQL_DEFAULT_DRIVER = "ODBC Driver 17 for SQL Server"
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def build_conn_str(spec) -> str:
|
|
164
|
+
"""数据源模板 → 最终连接串。
|
|
165
|
+
|
|
166
|
+
- mssql → 传统 ODBC 连接串(UID/PWD 用 ``{}`` 包裹防特殊字符);
|
|
167
|
+
- mysql / postgres → SQLAlchemy URL(``URL.create`` 自动编码密码中的
|
|
168
|
+
特殊字符,如 ``@`` ``:`` ``/``)。
|
|
169
|
+
"""
|
|
170
|
+
from sqlalchemy.engine import URL
|
|
171
|
+
|
|
172
|
+
if spec.type == "mssql":
|
|
173
|
+
parts = [
|
|
174
|
+
"DRIVER={{{}}}".format(spec.driver or MSSQL_DEFAULT_DRIVER),
|
|
175
|
+
"SERVER=" + spec.host + (f",{spec.port}" if spec.port else ""),
|
|
176
|
+
f"DATABASE={spec.database}",
|
|
177
|
+
]
|
|
178
|
+
if spec.username:
|
|
179
|
+
parts.append(f"UID={spec.username}")
|
|
180
|
+
if spec.password:
|
|
181
|
+
parts.append("PWD={{{}}}".format(spec.password))
|
|
182
|
+
parts.append("Connection Timeout=30")
|
|
183
|
+
return ";".join(parts)
|
|
184
|
+
|
|
185
|
+
url = URL.create(
|
|
186
|
+
"mysql+pymysql" if spec.type == "mysql" else "postgresql+psycopg",
|
|
187
|
+
username=spec.username,
|
|
188
|
+
password=spec.password,
|
|
189
|
+
host=spec.host,
|
|
190
|
+
port=spec.port or (3306 if spec.type == "mysql" else 5432),
|
|
191
|
+
database=spec.database,
|
|
192
|
+
query={"charset": "utf8mb4"} if spec.type == "mysql" else {},
|
|
193
|
+
)
|
|
194
|
+
return url.render_as_string(hide_password=False)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def resolve_conn_str(value) -> str:
|
|
198
|
+
"""datasources 条目 → 最终连接串(str 原样 = 自定义逃生口;模板 → 转换)。"""
|
|
199
|
+
return value if isinstance(value, str) else build_conn_str(value)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _odbc_from_url(url: str) -> str:
|
|
203
|
+
"""把 mssql+pyodbc:// URL 转成传统 ODBC 连接串(pyodbc.connect 不吃 URL)。"""
|
|
204
|
+
from sqlalchemy.engine import make_url
|
|
205
|
+
|
|
206
|
+
u = make_url(url)
|
|
207
|
+
# odbc_connect query 参数 = 已编码好的完整 ODBC 串(SQLAlchemy 官方用法)
|
|
208
|
+
odbc = u.query.get("odbc_connect")
|
|
209
|
+
if odbc:
|
|
210
|
+
return odbc
|
|
211
|
+
parts: List[str] = []
|
|
212
|
+
if u.host:
|
|
213
|
+
parts.append(f"SERVER={u.host}" + (f",{u.port}" if u.port else ""))
|
|
214
|
+
if u.database:
|
|
215
|
+
parts.append(f"DATABASE={u.database}")
|
|
216
|
+
if u.username:
|
|
217
|
+
parts.append(f"UID={u.username}")
|
|
218
|
+
if u.password is not None:
|
|
219
|
+
parts.append(f"PWD={u.password}")
|
|
220
|
+
for key, value in u.query.items():
|
|
221
|
+
if key == "driver":
|
|
222
|
+
parts.append(f"DRIVER={{{value}}}")
|
|
223
|
+
elif key != "odbc_connect":
|
|
224
|
+
parts.append(f"{key.upper()}={{{value}}}")
|
|
225
|
+
return ";".join(parts)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def datasource_driver_info(value) -> "tuple[str, Optional[str]]":
|
|
229
|
+
"""返回 ``(kind, 驱动展示名或 None)``,供 datasources 端点做可用性标注。
|
|
230
|
+
|
|
231
|
+
value 为字符串(自定义连接串)或 DatasourceSpec 模板。URL 形态按
|
|
232
|
+
drivername 精确给出驱动名(PyMySQL / psycopg 3 / psycopg2 / 方言名)。
|
|
233
|
+
"""
|
|
234
|
+
if not isinstance(value, str):
|
|
235
|
+
# 模板式:type 即 kind,驱动名固定(mssql 缺省驱动可被 spec.driver 覆盖)
|
|
236
|
+
if value.type == "mssql":
|
|
237
|
+
return "mssql", value.driver or MSSQL_DEFAULT_DRIVER
|
|
238
|
+
return value.type, "PyMySQL" if value.type == "mysql" else "psycopg 3"
|
|
239
|
+
|
|
240
|
+
kind = datasource_kind(value)
|
|
241
|
+
drivername = _url_drivername(value)
|
|
242
|
+
if drivername is not None:
|
|
243
|
+
if drivername in PEP249_DRIVERS:
|
|
244
|
+
return kind, PEP249_DRIVERS[drivername][1]
|
|
245
|
+
if kind == "sqlalchemy":
|
|
246
|
+
return kind, drivername
|
|
247
|
+
# mssql 系 URL:转换后解析 DRIVER= 展示
|
|
248
|
+
odbc_str = _odbc_from_url(value.strip())
|
|
249
|
+
return "mssql", extract_odbc_driver(odbc_str)
|
|
250
|
+
if kind in ("mysql", "postgres"):
|
|
251
|
+
# 理论不可达(kind 路由要求 URL 形态),兜底不误标
|
|
252
|
+
return kind, None
|
|
253
|
+
return "mssql", extract_odbc_driver(value)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def sqlalchemy_dialect_installed(conn_str: str) -> bool:
|
|
257
|
+
"""探测连接串的 SQLAlchemy 方言是否已安装(不建立真实连接)。
|
|
258
|
+
|
|
259
|
+
create_engine 在方言未注册时立即抛 NoSuchModuleError(import 阶段),
|
|
260
|
+
方言已注册但 DBAPI pip 包未装时抛 ModuleNotFoundError,均不触碰网络;
|
|
261
|
+
其余异常(如 URL 参数问题)视为方言可用,由执行期报错。
|
|
262
|
+
"""
|
|
263
|
+
from sqlalchemy import create_engine
|
|
264
|
+
from sqlalchemy.exc import NoSuchModuleError
|
|
265
|
+
|
|
266
|
+
try:
|
|
267
|
+
create_engine(conn_str.strip())
|
|
268
|
+
return True
|
|
269
|
+
except NoSuchModuleError:
|
|
270
|
+
# 方言未注册(scheme 完全未知,如 foo://)
|
|
271
|
+
return False
|
|
272
|
+
except ModuleNotFoundError:
|
|
273
|
+
# 方言已注册但其 DBAPI pip 包未装(如 postgresql+psycopg 缺 psycopg)
|
|
274
|
+
return False
|
|
275
|
+
except Exception:
|
|
276
|
+
# 方言已解析(非方言/驱动问题,如参数校验失败)→ 视为已安装
|
|
277
|
+
return True
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
# 连接异常中出现这些特征 = 系统 ODBC 驱动缺失(pyodbc 库本身已装好):
|
|
281
|
+
# Windows Driver Manager 报 "Data source name not found and no default driver
|
|
282
|
+
# specified"(SQLSTATE IM002),unixODBC 报 "Can't open lib ..."(IM003)。
|
|
283
|
+
_ODBC_DRIVER_MISSING_MARKERS = (
|
|
284
|
+
"data source name not found",
|
|
285
|
+
"can't open lib",
|
|
286
|
+
"specified driver could not be loaded",
|
|
287
|
+
"im002",
|
|
288
|
+
"im003",
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
_ODBC_DOWNLOAD_URL = (
|
|
292
|
+
"https://learn.microsoft.com/zh-cn/sql/connect/odbc/download-odbc-driver-for-sql-server"
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _driver_missing_hint(exc: Exception, driver: Optional[str]) -> Optional[str]:
|
|
297
|
+
"""连接异常若源于系统 ODBC 驱动缺失,返回可操作的中文提示,否则 None。
|
|
298
|
+
|
|
299
|
+
SQL Server 驱动缺失给微软官方下载链接;其他数据库(如 ClickHouse、
|
|
300
|
+
达梦等走 ODBC 逃生口的库)给通用指引,避免误导去装微软驱动。
|
|
301
|
+
"""
|
|
302
|
+
text = str(exc).lower()
|
|
303
|
+
if not any(marker in text for marker in _ODBC_DRIVER_MISSING_MARKERS):
|
|
304
|
+
return None
|
|
305
|
+
target = f"(连接串要求驱动:{driver})" if driver else ""
|
|
306
|
+
if driver and "sql server" not in driver.lower():
|
|
307
|
+
return (
|
|
308
|
+
f"系统未安装所需的 ODBC 驱动{target}。pyodbc 只是 Python 库,"
|
|
309
|
+
"还需在服务器上安装该数据库对应的系统级 ODBC 驱动(请查阅该"
|
|
310
|
+
"数据库官方文档的下载与安装说明)"
|
|
311
|
+
)
|
|
312
|
+
return (
|
|
313
|
+
f"系统未安装所需的 ODBC 驱动{target}。pyodbc 只是 Python 库,"
|
|
314
|
+
"还需在服务器上安装 Microsoft ODBC Driver for SQL Server"
|
|
315
|
+
"(Windows 不自带),下载地址:" + _ODBC_DOWNLOAD_URL
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def execute_sql_task(
|
|
320
|
+
conn_str: str,
|
|
321
|
+
task_type: str,
|
|
322
|
+
sql_text: str,
|
|
323
|
+
params: Optional[Dict[str, Any]] = None,
|
|
324
|
+
var_overrides: Optional[Dict[str, str]] = None,
|
|
325
|
+
var_defaults: Optional[Dict[str, str]] = None,
|
|
326
|
+
var_names: Optional[Sequence[str]] = None,
|
|
327
|
+
) -> Dict[str, Any]:
|
|
328
|
+
"""执行一次 SQL / 存储过程任务(同步阻塞,调用方负责放线程池)。
|
|
329
|
+
|
|
330
|
+
返回 ``{"script": 渲染后脚本, "rowcount": ...}``;SQL 脚本任务对返回
|
|
331
|
+
行的语句(SELECT)附 ``"result_sets": [{"columns", "rows"}, ...]``(每集
|
|
332
|
+
限量 PROC_OUTPUT_ROW_LIMIT 行);存储过程任务另有 ``"result"`` 返回值
|
|
333
|
+
与 ``"procedure_output"``。连接或执行失败时抛异常(由任务框架记录并
|
|
334
|
+
决定重试/失败)。var_defaults / var_names 传声明式动态参数(见 paramdefs)。
|
|
335
|
+
"""
|
|
336
|
+
script, _ = render_task_sql(
|
|
337
|
+
task_type, sql_text, params, var_overrides, var_defaults=var_defaults, var_names=var_names
|
|
338
|
+
)
|
|
339
|
+
kind = datasource_kind(conn_str)
|
|
340
|
+
if kind == "mssql":
|
|
341
|
+
return _execute_mssql(conn_str, task_type, script)
|
|
342
|
+
if kind == "sqlalchemy":
|
|
343
|
+
return _execute_sqlalchemy(conn_str, task_type, script)
|
|
344
|
+
return _execute_pep249(kind, conn_str, task_type, script)
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
# ---------------------------------------------------------------------------
|
|
348
|
+
# 连通性测试(UI「测试连接」按钮):与任务执行走完全相同的连接路径和
|
|
349
|
+
# 错误转译链——测得过 = 任务执行时连得上(DolphinScheduler 保存前测试同思路)
|
|
350
|
+
# ---------------------------------------------------------------------------
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _test_ping(conn) -> None:
|
|
354
|
+
"""在已建立的 PEP 249 连接上执行 SELECT 1(mssql / 直连路径共用)。"""
|
|
355
|
+
cursor = conn.cursor()
|
|
356
|
+
try:
|
|
357
|
+
cursor.execute("SELECT 1")
|
|
358
|
+
cursor.fetchone()
|
|
359
|
+
finally:
|
|
360
|
+
cursor.close()
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def test_connection(conn_str: str) -> Dict[str, Any]:
|
|
364
|
+
"""测试数据源连通性:建立真实连接并执行 SELECT 1。
|
|
365
|
+
|
|
366
|
+
返回 ``{"ok": True, "elapsed_ms": ...}`` 或 ``{"ok": False, "error":
|
|
367
|
+
中文提示, "elapsed_ms": ...}``——测试失败不是异常,由调用方(测试
|
|
368
|
+
端点)直接下发前端展示。错误转译复用三条执行路径(方言未装 / pip
|
|
369
|
+
驱动缺失 / 系统 ODBC 驱动缺失均已转译为可操作提示)。
|
|
370
|
+
"""
|
|
371
|
+
start = time.monotonic()
|
|
372
|
+
|
|
373
|
+
def _elapsed() -> int:
|
|
374
|
+
return round((time.monotonic() - start) * 1000)
|
|
375
|
+
|
|
376
|
+
try:
|
|
377
|
+
kind = datasource_kind(conn_str)
|
|
378
|
+
if kind == "mssql":
|
|
379
|
+
conn = _mssql_connect(conn_str)
|
|
380
|
+
try:
|
|
381
|
+
_test_ping(conn)
|
|
382
|
+
finally:
|
|
383
|
+
_close_quietly(conn)
|
|
384
|
+
elif kind == "sqlalchemy":
|
|
385
|
+
# select(1) 由 SQLAlchemy 编译为各方言正确写法(如 Oracle
|
|
386
|
+
# 自动加 FROM DUAL),无裸 SQL 方言兼容问题
|
|
387
|
+
from sqlalchemy import select
|
|
388
|
+
|
|
389
|
+
engine = _get_engine(conn_str)
|
|
390
|
+
with engine.connect() as conn:
|
|
391
|
+
conn.execute(select(1))
|
|
392
|
+
else:
|
|
393
|
+
conn = _pep249_connect(kind, conn_str)
|
|
394
|
+
try:
|
|
395
|
+
_test_ping(conn)
|
|
396
|
+
finally:
|
|
397
|
+
_close_quietly(conn)
|
|
398
|
+
return {"ok": True, "elapsed_ms": _elapsed()}
|
|
399
|
+
except Exception as exc:
|
|
400
|
+
return {
|
|
401
|
+
"ok": False,
|
|
402
|
+
"error": str(exc) or exc.__class__.__name__,
|
|
403
|
+
"elapsed_ms": _elapsed(),
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _result_from_sets(
|
|
408
|
+
script: str,
|
|
409
|
+
rowcount: int,
|
|
410
|
+
result_sets: List[Dict[str, Any]],
|
|
411
|
+
task_type: str,
|
|
412
|
+
) -> Dict[str, Any]:
|
|
413
|
+
"""按任务类型整理返回结构(各驱动路径共用)。"""
|
|
414
|
+
result: Dict[str, Any] = {"script": script, "rowcount": rowcount}
|
|
415
|
+
if task_type == "procedure":
|
|
416
|
+
# 最后一个结果集是脚本生成的返回值(SELECT @result)
|
|
417
|
+
if result_sets and result_sets[-1]["rows"]:
|
|
418
|
+
result["result"] = result_sets[-1]["rows"][0][0]
|
|
419
|
+
# 其余为存储过程自身的 SELECT 输出(如 本次写入行数、数据日期)
|
|
420
|
+
if len(result_sets) > 1:
|
|
421
|
+
result["procedure_output"] = result_sets[:-1]
|
|
422
|
+
elif result_sets:
|
|
423
|
+
# SQL 脚本任务:返回行的语句(SELECT)限量采集,写操作无结果集
|
|
424
|
+
result["result_sets"] = result_sets
|
|
425
|
+
return result
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _fetch_result_sets(cursor, row_limit: int) -> List[Dict[str, Any]]:
|
|
429
|
+
"""遍历当前游标的所有结果集(每个最多保留 row_limit 行防内存爆)。"""
|
|
430
|
+
result_sets: List[Dict[str, Any]] = []
|
|
431
|
+
while True:
|
|
432
|
+
if cursor.description is not None:
|
|
433
|
+
columns = [d[0] for d in cursor.description]
|
|
434
|
+
rows = [
|
|
435
|
+
[_json_safe(v) for v in row]
|
|
436
|
+
for row in cursor.fetchmany(row_limit)
|
|
437
|
+
]
|
|
438
|
+
result_sets.append({"columns": columns, "rows": rows})
|
|
439
|
+
if not cursor.nextset():
|
|
440
|
+
break
|
|
441
|
+
return result_sets
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
# ---------------------------------------------------------------------------
|
|
445
|
+
# SQLAlchemy 通用方言路径
|
|
446
|
+
# ---------------------------------------------------------------------------
|
|
447
|
+
|
|
448
|
+
_engine_cache: Dict[str, Any] = {}
|
|
449
|
+
"""engine 全局缓存(key=连接串):调度任务高频执行同一数据源时复用连接池
|
|
450
|
+
(TCP/认证握手只做一次),datasources 为启动期加载(改配置需重启),缓存
|
|
451
|
+
不存在失效问题。pool_pre_ping 借出前探活,数据库重启后的死连接自动重建。"""
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def _get_engine(conn_str: str):
|
|
455
|
+
"""取(或建并缓存)engine;方言未装/依赖不完整时给出可操作的中文提示。
|
|
456
|
+
|
|
457
|
+
- NoSuchModuleError:方言包本体未安装;
|
|
458
|
+
- ImportError:方言包在但依赖不完整(如 pyhive 缺 thrift)——两类都
|
|
459
|
+
转译,避免用户面对英文 traceback 猜谜。
|
|
460
|
+
"""
|
|
461
|
+
import atexit
|
|
462
|
+
|
|
463
|
+
from sqlalchemy import create_engine
|
|
464
|
+
from sqlalchemy.exc import NoSuchModuleError
|
|
465
|
+
|
|
466
|
+
key = conn_str.strip()
|
|
467
|
+
engine = _engine_cache.get(key)
|
|
468
|
+
if engine is not None:
|
|
469
|
+
return engine
|
|
470
|
+
|
|
471
|
+
try:
|
|
472
|
+
engine = create_engine(key, pool_pre_ping=True)
|
|
473
|
+
except NoSuchModuleError as exc:
|
|
474
|
+
raise RuntimeError(
|
|
475
|
+
"连接串的 SQLAlchemy 方言未安装:请 pip 安装对应数据库的"
|
|
476
|
+
" SQLAlchemy 方言包(如 clickhouse-connect / oracledb,参考"
|
|
477
|
+
"该数据库官方文档),安装后重启服务"
|
|
478
|
+
) from exc
|
|
479
|
+
except ImportError as exc:
|
|
480
|
+
raise RuntimeError(
|
|
481
|
+
"连接串的 SQLAlchemy 方言包已安装但其依赖不完整"
|
|
482
|
+
f"(缺失:{exc})。请参考该方言包文档补齐依赖(常见如"
|
|
483
|
+
" thrift / sasl 等纯 Python 依赖),补齐后重启服务"
|
|
484
|
+
) from exc
|
|
485
|
+
|
|
486
|
+
if not _engine_cache:
|
|
487
|
+
# 首个 engine 入缓存时注册退出清理(只注册一次)
|
|
488
|
+
atexit.register(_dispose_all_engines)
|
|
489
|
+
_engine_cache[key] = engine
|
|
490
|
+
return engine
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def _dispose_all_engines() -> None:
|
|
494
|
+
for engine in _engine_cache.values():
|
|
495
|
+
try:
|
|
496
|
+
engine.dispose()
|
|
497
|
+
except Exception:
|
|
498
|
+
pass
|
|
499
|
+
_engine_cache.clear()
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def _execute_sqlalchemy(
|
|
503
|
+
conn_str: str, task_type: str, script: str
|
|
504
|
+
) -> Dict[str, Any]:
|
|
505
|
+
"""通用 SQLAlchemy 方言路径:支持面由用户 pip 安装的方言包决定。
|
|
506
|
+
|
|
507
|
+
业界标准做法(Airflow/Superset 同款思路):框架不维护方言映射,
|
|
508
|
+
SQLAlchemy 经 entry points 自动识别一切已安装方言(clickhouse-connect、
|
|
509
|
+
oracledb、db-dm 等)。仅支持 SQL 脚本任务——存储过程各库语法差异大
|
|
510
|
+
(EXEC/CALL/BEGIN-END),仍走对应库的专用路径。
|
|
511
|
+
|
|
512
|
+
连接超时:方言各异无法统一内置,建议在 URL query 写 connect_timeout
|
|
513
|
+
(如 ``clickhouse+connect://h/db?connect_timeout=30``),整体兜底
|
|
514
|
+
由任务的 timeout_seconds 保证。多语句脚本受方言限制(多数驱动仅单
|
|
515
|
+
语句),报错原样抛出——不做按分号拆分的危险行为。
|
|
516
|
+
"""
|
|
517
|
+
from sqlalchemy import text
|
|
518
|
+
|
|
519
|
+
if task_type == "procedure":
|
|
520
|
+
raise ValueError(
|
|
521
|
+
"SQLAlchemy 通用连接串不支持存储过程任务(各库过程语法差异大),"
|
|
522
|
+
"请改用 SQL 脚本任务,或为该库配置 ODBC 连接串(pyodbc 备选路径)"
|
|
523
|
+
)
|
|
524
|
+
|
|
525
|
+
engine = _get_engine(conn_str)
|
|
526
|
+
with engine.connect() as conn:
|
|
527
|
+
result = conn.execute(text(script))
|
|
528
|
+
# SELECT 型 rowcount 多为 -1(不可靠),归一为 0;DML 型正常
|
|
529
|
+
rowcount = result.rowcount or 0
|
|
530
|
+
if rowcount < 0:
|
|
531
|
+
rowcount = 0
|
|
532
|
+
out: Dict[str, Any] = {"script": script, "rowcount": rowcount}
|
|
533
|
+
if result.returns_rows:
|
|
534
|
+
# 与专用路径语义对齐:返回行的语句限量采集(防内存爆),
|
|
535
|
+
# 空结果也带 columns(与 _fetch_result_sets 行为一致)
|
|
536
|
+
columns = list(result.keys())
|
|
537
|
+
rows = [
|
|
538
|
+
[_json_safe(v) for v in row]
|
|
539
|
+
for row in result.fetchmany(PROC_OUTPUT_ROW_LIMIT)
|
|
540
|
+
]
|
|
541
|
+
out["result_sets"] = [{"columns": columns, "rows": rows}]
|
|
542
|
+
conn.commit()
|
|
543
|
+
return out
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def _close_quietly(conn) -> None:
|
|
547
|
+
"""关闭连接(已建立的连接 close 报错不影响主流程,静默吞掉)。"""
|
|
548
|
+
try:
|
|
549
|
+
conn.close()
|
|
550
|
+
except Exception:
|
|
551
|
+
pass
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def _mssql_connect(conn_str: str):
|
|
555
|
+
"""建立 SQL Server 连接(pyodbc):传统 ODBC 连接串或 mssql+pyodbc:// URL。
|
|
556
|
+
|
|
557
|
+
pyodbc 库缺失与系统 ODBC 驱动缺失转译为可操作中文提示,其余
|
|
558
|
+
(登录失败/超时等)原样抛出。执行路径与测试连接共用(同一转译链)。
|
|
559
|
+
"""
|
|
560
|
+
try:
|
|
561
|
+
import pyodbc
|
|
562
|
+
except ImportError as exc: # 未安装 pyodbc 时给出可操作的提示
|
|
563
|
+
raise RuntimeError(
|
|
564
|
+
"SQL Server 数据源需要 pyodbc 驱动库(pip 包,按需安装):"
|
|
565
|
+
f"{MSSQL_INSTALL_HINT},安装后重启服务;运行还需目标数据库的"
|
|
566
|
+
"系统级 ODBC Driver"
|
|
567
|
+
) from exc
|
|
568
|
+
|
|
569
|
+
odbc_str = (
|
|
570
|
+
_odbc_from_url(conn_str.strip())
|
|
571
|
+
if conn_str.strip().lower().startswith("mssql")
|
|
572
|
+
else conn_str
|
|
573
|
+
)
|
|
574
|
+
try:
|
|
575
|
+
return pyodbc.connect(odbc_str, timeout=30)
|
|
576
|
+
except Exception as exc:
|
|
577
|
+
# 仅转译「系统 ODBC 驱动缺失」类错误;登录失败/超时等原样抛出
|
|
578
|
+
hint = _driver_missing_hint(exc, extract_odbc_driver(odbc_str))
|
|
579
|
+
if hint:
|
|
580
|
+
raise RuntimeError(hint) from exc
|
|
581
|
+
raise
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def _execute_mssql(
|
|
585
|
+
conn_str: str, task_type: str, script: str
|
|
586
|
+
) -> Dict[str, Any]:
|
|
587
|
+
"""SQL Server 路径(pyodbc):传统 ODBC 连接串或 mssql+pyodbc:// URL。
|
|
588
|
+
|
|
589
|
+
执行逻辑与 TotalScheduled 的 sql_scheduler 保持一致(成熟路径复用):
|
|
590
|
+
显式 SET XACT_ABORT ON 保证出错回滚;存储过程任务收集结果集。
|
|
591
|
+
"""
|
|
592
|
+
conn = None
|
|
593
|
+
try:
|
|
594
|
+
conn = _mssql_connect(conn_str)
|
|
595
|
+
cursor = conn.cursor()
|
|
596
|
+
try:
|
|
597
|
+
cursor.execute(script)
|
|
598
|
+
|
|
599
|
+
# 结果集限量采集(PROC_OUTPUT_ROW_LIMIT 防内存爆):存储过程任务
|
|
600
|
+
# 收集过程输出与返回值;SQL 脚本任务对返回行的语句(SELECT)保留
|
|
601
|
+
# 前 N 行,写操作无结果集自然为空
|
|
602
|
+
result_sets = _fetch_result_sets(cursor, PROC_OUTPUT_ROW_LIMIT)
|
|
603
|
+
|
|
604
|
+
conn.commit()
|
|
605
|
+
rowcount = cursor.rowcount
|
|
606
|
+
finally:
|
|
607
|
+
cursor.close()
|
|
608
|
+
|
|
609
|
+
return _result_from_sets(script, rowcount, result_sets, task_type)
|
|
610
|
+
finally:
|
|
611
|
+
_close_quietly(conn)
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def _pep249_connect(kind: str, conn_str: str):
|
|
615
|
+
"""建立 MySQL / PostgreSQL 直连(PEP 249)。
|
|
616
|
+
|
|
617
|
+
按 URL 的 drivername 精确选驱动(绝不静默偷换):pymysql / psycopg 3 /
|
|
618
|
+
psycopg2。连接参数由 SQLAlchemy URL 解析,URL query(charset、ssl、
|
|
619
|
+
application_name 等)完整透传给驱动——用户显式声明优先于内置默认
|
|
620
|
+
connect_timeout=30。凭证不出配置文件。执行路径与测试连接共用。
|
|
621
|
+
"""
|
|
622
|
+
import importlib
|
|
623
|
+
|
|
624
|
+
from sqlalchemy.engine import make_url
|
|
625
|
+
|
|
626
|
+
drivername = _url_drivername(conn_str)
|
|
627
|
+
module_name, display, install_hint = PEP249_DRIVERS[drivername]
|
|
628
|
+
try:
|
|
629
|
+
driver = importlib.import_module(module_name)
|
|
630
|
+
except ImportError as exc:
|
|
631
|
+
raise RuntimeError(
|
|
632
|
+
f"数据源类型为 {kind}(驱动:{display}),需要安装对应的"
|
|
633
|
+
f" Python 驱动库(pip 包,无需系统级驱动):{install_hint},"
|
|
634
|
+
"安装后重启服务"
|
|
635
|
+
) from exc
|
|
636
|
+
|
|
637
|
+
u = make_url(conn_str.strip())
|
|
638
|
+
# 数据库参数名:pymysql=database,psycopg/psycopg2=dbname
|
|
639
|
+
db_key = "database" if module_name == "pymysql" else "dbname"
|
|
640
|
+
conn_kwargs = {
|
|
641
|
+
"host": u.host,
|
|
642
|
+
"port": u.port or (3306 if kind == "mysql" else 5432),
|
|
643
|
+
"user": u.username,
|
|
644
|
+
"password": u.password,
|
|
645
|
+
db_key: u.database,
|
|
646
|
+
"connect_timeout": 30,
|
|
647
|
+
}
|
|
648
|
+
conn_kwargs = {k: v for k, v in conn_kwargs.items() if v is not None}
|
|
649
|
+
# URL query 完整透传(值保持字符串,出错显式抛优于静默丢弃);
|
|
650
|
+
# 用户显式声明覆盖内置默认(如 connect_timeout)
|
|
651
|
+
conn_kwargs.update(u.query)
|
|
652
|
+
try:
|
|
653
|
+
return driver.connect(**conn_kwargs)
|
|
654
|
+
except Exception as exc:
|
|
655
|
+
# 驱动库本身 pip 可装,连接失败基本是地址/凭证/网络问题,原样抛出
|
|
656
|
+
raise RuntimeError(f"连接 {kind} 数据源失败:{exc}") from exc
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def _execute_pep249(
|
|
660
|
+
kind: str, conn_str: str, task_type: str, script: str
|
|
661
|
+
) -> Dict[str, Any]:
|
|
662
|
+
"""MySQL / PostgreSQL 直连路径:纯 Python pip 驱动(PEP 249)。
|
|
663
|
+
|
|
664
|
+
结果集语义与 SQL Server 路径一致:限量采集(存储过程任务收集过程
|
|
665
|
+
输出与返回值,SQL 脚本任务保留 SELECT 前 N 行;多结果集经 nextset 遍历)。
|
|
666
|
+
"""
|
|
667
|
+
conn = None
|
|
668
|
+
try:
|
|
669
|
+
conn = _pep249_connect(kind, conn_str)
|
|
670
|
+
cursor = conn.cursor()
|
|
671
|
+
try:
|
|
672
|
+
cursor.execute(script)
|
|
673
|
+
|
|
674
|
+
result_sets = _fetch_result_sets(cursor, PROC_OUTPUT_ROW_LIMIT)
|
|
675
|
+
|
|
676
|
+
conn.commit()
|
|
677
|
+
rowcount = cursor.rowcount
|
|
678
|
+
finally:
|
|
679
|
+
cursor.close()
|
|
680
|
+
|
|
681
|
+
return _result_from_sets(script, rowcount, result_sets, task_type)
|
|
682
|
+
finally:
|
|
683
|
+
_close_quietly(conn)
|