mtkit 1.16.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.
- mtkit/__init__.py +36 -0
- mtkit/__main__.py +6 -0
- mtkit/asset.py +101 -0
- mtkit/audit.py +220 -0
- mtkit/builder.py +100 -0
- mtkit/cli.py +885 -0
- mtkit/conf.py +63 -0
- mtkit/coverage.py +175 -0
- mtkit/db.py +676 -0
- mtkit/evolve.py +142 -0
- mtkit/extract/__init__.py +17 -0
- mtkit/extract/code_facts.py +631 -0
- mtkit/extract/docx_loader.py +115 -0
- mtkit/extract/xmind_loader.py +125 -0
- mtkit/generate/__init__.py +10 -0
- mtkit/generate/llm.py +360 -0
- mtkit/generate/prompts.py +178 -0
- mtkit/generate/skeleton.py +59 -0
- mtkit/normalize.py +480 -0
- mtkit/parsers.py +318 -0
- mtkit/review.py +274 -0
- mtkit/selfheal.py +110 -0
- mtkit/tb.py +191 -0
- mtkit/track.py +309 -0
- mtkit/validator.py +174 -0
- mtkit/writer.py +137 -0
- mtkit-1.16.1.dist-info/METADATA +150 -0
- mtkit-1.16.1.dist-info/RECORD +31 -0
- mtkit-1.16.1.dist-info/WHEEL +5 -0
- mtkit-1.16.1.dist-info/entry_points.txt +2 -0
- mtkit-1.16.1.dist-info/top_level.txt +1 -0
mtkit/db.py
ADDED
|
@@ -0,0 +1,676 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
Database access layer: unified readonly provider abstraction over 4 data sources.
|
|
4
|
+
|
|
5
|
+
Strictly readonly: only SELECT/EXPLAIN/DESC/DESCRIBE/SHOW style statements are allowed,
|
|
6
|
+
any write operation or DDL is rejected.
|
|
7
|
+
|
|
8
|
+
provider types (db.json type field):
|
|
9
|
+
- cli : external CLI command template (mysql/sqlcmd/psql/in-house CLI), run via subprocess
|
|
10
|
+
- driver: Python driver direct connection (importlib dynamic load, optional dependency, e.g. pymysql)
|
|
11
|
+
- http : HTTP API gateway (self-built query platform, POST {url} returns JSON)
|
|
12
|
+
- file : offline data source file (schema.json), usable without network
|
|
13
|
+
|
|
14
|
+
db.json config examples:
|
|
15
|
+
{"type": "cli", "connect": {"cmd": "mysql -h{host} -u{user} -p{pass} {db} -N -e \"{sql}\"",
|
|
16
|
+
"host": "10.0.0.1", "user": "ro", "pass": "${DB_PASS}", "db": "bill_db"}}
|
|
17
|
+
{"type": "driver", "driver": "pymysql", "host": "10.0.0.1", "user": "ro", "password": "${DB_PASS}", "db": "bill_db"}
|
|
18
|
+
{"type": "http", "url": "https://gateway.example.com/query", "token": "${DB_TOKEN}"}
|
|
19
|
+
{"type": "file", "path": "schema.json"}
|
|
20
|
+
|
|
21
|
+
Passwords/tokens support ${ENV_VAR} environment variable references, never plaintext.
|
|
22
|
+
"""
|
|
23
|
+
import importlib
|
|
24
|
+
import io
|
|
25
|
+
import json
|
|
26
|
+
import os
|
|
27
|
+
import re
|
|
28
|
+
import subprocess
|
|
29
|
+
|
|
30
|
+
# ---------------------------------------------------------------- readonly whitelist
|
|
31
|
+
|
|
32
|
+
_ALLOWED_PREFIX = re.compile(r"^\s*(SELECT|EXPLAIN|DESC|DESCRIBE|SHOW)\b", re.IGNORECASE)
|
|
33
|
+
_FORBIDDEN_WORDS = re.compile(
|
|
34
|
+
r"\b(INSERT|UPDATE|DELETE|DROP|ALTER|TRUNCATE|CREATE|GRANT|REPLACE|RENAME"
|
|
35
|
+
r"|LOAD|LOCK|MERGE|UPSERT)\b",
|
|
36
|
+
re.IGNORECASE,
|
|
37
|
+
)
|
|
38
|
+
_INTO_FILE_PATTERN = re.compile(r"INTO\s+(OUTFILE|DUMPFILE)", re.IGNORECASE)
|
|
39
|
+
|
|
40
|
+
# shell escape characters rejected for the cli provider (command template runs under shell=True);
|
|
41
|
+
# inside the template's double quotes these break out of the quoting in bash and cmd.exe
|
|
42
|
+
_SHELL_ESCAPE_PATTERN = re.compile(r'["`$]|\\["$`\\]')
|
|
43
|
+
|
|
44
|
+
# extract table names from SQL (identifier after FROM/JOIN; schema.table -> table), for offline static check
|
|
45
|
+
_TABLE_NAME_PATTERN = re.compile(
|
|
46
|
+
r"\b(?:FROM|JOIN)\s+[`\"'\[{]?(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)[`\"'\]}]?",
|
|
47
|
+
re.IGNORECASE,
|
|
48
|
+
)
|
|
49
|
+
# extract column names from SELECT (between SELECT and FROM)
|
|
50
|
+
_SELECT_COLUMNS_PATTERN = re.compile(r"SELECT\s+(.*?)\s+FROM", re.DOTALL | re.IGNORECASE)
|
|
51
|
+
_COLUMN_TOKEN_PATTERN = re.compile(r"([A-Za-z_][A-Za-z0-9_]*)", re.IGNORECASE)
|
|
52
|
+
# SQL keyword prefixes: these tokens are not column names
|
|
53
|
+
_SQL_COLUMN_SKIP = frozenset({
|
|
54
|
+
"TOP", "OFFSET", "FETCH", "DISTINCT", "ALL", "NEXT", "FIRST", "ONLY", "ROWS", "PERCENT",
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
# string literal mask sentinel (W-01/02/03: literal keywords must not affect readonly checks)
|
|
58
|
+
_MASK_SENTINEL = "__MTKIT_LIT__"
|
|
59
|
+
_STRING_LITERAL_PATTERN = re.compile(
|
|
60
|
+
r"'(?:[^']|'')*'|\"(?:[^\"]|\"\")*\"", re.DOTALL,
|
|
61
|
+
)
|
|
62
|
+
_SQL_COMMENT_PATTERN = re.compile(r"--[^\n]*|/\*.*?\*/", re.DOTALL)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _mask_sql(sql):
|
|
66
|
+
"""Mask string literals and comments with a harmless sentinel (readonly checks only)."""
|
|
67
|
+
masked = _STRING_LITERAL_PATTERN.sub(_MASK_SENTINEL, sql)
|
|
68
|
+
masked = _SQL_COMMENT_PATTERN.sub(" ", masked)
|
|
69
|
+
return masked
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def tables_of(sql):
|
|
73
|
+
"""Extract the table name set from SQL (schema.table -> table)."""
|
|
74
|
+
return set(_TABLE_NAME_PATTERN.findall(sql))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _column_tokens(segment):
|
|
78
|
+
"""Tokenize a SELECT segment into column candidates:
|
|
79
|
+
- cut at AS alias, take only the expression part
|
|
80
|
+
- drop functions/params (anything with parens)
|
|
81
|
+
- drop qualified prefix(table.col -> col)
|
|
82
|
+
- drop keyword prefixes(TOP/OFFSET/FETCH/DISTINCT...)
|
|
83
|
+
"""
|
|
84
|
+
tokens = []
|
|
85
|
+
for part in segment.split(","):
|
|
86
|
+
part = part.strip()
|
|
87
|
+
if not part or part == "*" or "(" in part:
|
|
88
|
+
continue
|
|
89
|
+
# cut at AS alias
|
|
90
|
+
as_match = re.search(r"\s+AS\s+", part, re.IGNORECASE)
|
|
91
|
+
if as_match:
|
|
92
|
+
part = part[: as_match.start()].strip()
|
|
93
|
+
candidates = _COLUMN_TOKEN_PATTERN.findall(part)
|
|
94
|
+
cleaned = []
|
|
95
|
+
for token in candidates:
|
|
96
|
+
upper = token.upper()
|
|
97
|
+
if upper in _SQL_COLUMN_SKIP:
|
|
98
|
+
continue
|
|
99
|
+
cleaned.append(token)
|
|
100
|
+
if cleaned:
|
|
101
|
+
tokens.append(cleaned[-1])
|
|
102
|
+
return tokens
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def columns_of(sql):
|
|
106
|
+
"""Extract bare SELECT column names (no function/alias/param/table qualifier/keyword prefix)."""
|
|
107
|
+
match = _SELECT_COLUMNS_PATTERN.search(sql)
|
|
108
|
+
if not match:
|
|
109
|
+
return set()
|
|
110
|
+
return set(_column_tokens(match.group(1)))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def qualified_columns(sql):
|
|
114
|
+
"""Extract table-qualified columns (table.col -> (table, col)), for JOIN column-level check routing."""
|
|
115
|
+
match = _SELECT_COLUMNS_PATTERN.search(sql)
|
|
116
|
+
if not match:
|
|
117
|
+
return []
|
|
118
|
+
result = []
|
|
119
|
+
for part in match.group(1).split(","):
|
|
120
|
+
part = part.strip()
|
|
121
|
+
if not part or part == "*" or "(" in part:
|
|
122
|
+
continue
|
|
123
|
+
as_match = re.search(r"\s+AS\s+", part, re.IGNORECASE)
|
|
124
|
+
if as_match:
|
|
125
|
+
part = part[: as_match.start()].strip()
|
|
126
|
+
qualified = re.search(r"(?:^|[\s.(])([A-Za-z_][A-Za-z0-9_]*)\.([A-Za-z_][A-Za-z0-9_]*)$", part)
|
|
127
|
+
if qualified:
|
|
128
|
+
result.append((qualified.group(1), qualified.group(2)))
|
|
129
|
+
return result
|
|
130
|
+
|
|
131
|
+
# environment variable reference ${VAR}
|
|
132
|
+
_ENV_PATTERN = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def check_readonly(sql):
|
|
136
|
+
"""Validate SQL is readonly, return (ok, reason).
|
|
137
|
+
|
|
138
|
+
rules (mask string literals and comments first, then check):
|
|
139
|
+
1. must start with SELECT/EXPLAIN/DESC/DESCRIBE/SHOW
|
|
140
|
+
2. must not contain write operation/DDL keywords
|
|
141
|
+
3. INTO OUTFILE/DUMPFILE is forbidden
|
|
142
|
+
"""
|
|
143
|
+
if not sql or not sql.strip():
|
|
144
|
+
return False, "空 SQL"
|
|
145
|
+
masked = _mask_sql(sql)
|
|
146
|
+
if not _ALLOWED_PREFIX.match(masked):
|
|
147
|
+
return False, "仅允许 SELECT/EXPLAIN/DESC/DESCRIBE/SHOW 开头的只读语句"
|
|
148
|
+
if _FORBIDDEN_WORDS.search(masked):
|
|
149
|
+
return False, "语句包含写操作/DDL 关键字,已拒绝"
|
|
150
|
+
if _INTO_FILE_PATTERN.search(masked):
|
|
151
|
+
return False, "禁止 INTO OUTFILE/DUMPFILE"
|
|
152
|
+
return True, ""
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def check_cli_shell_safe(sql):
|
|
156
|
+
"""Validate SQL has no shell escaping for the cli provider (shell=True execution).
|
|
157
|
+
|
|
158
|
+
escape characters are checked on the raw SQL (string literals included, they reach
|
|
159
|
+
the shell inside the template's double quotes):
|
|
160
|
+
1. no double quotes / backticks / $ / backslash-escape sequences (break the template quoting)
|
|
161
|
+
2. no embedded newlines
|
|
162
|
+
3. semicolons only allowed as the single trailing terminator (checked on the masked SQL,
|
|
163
|
+
so semicolons inside string literals pass)
|
|
164
|
+
"""
|
|
165
|
+
if _SHELL_ESCAPE_PATTERN.search(sql):
|
|
166
|
+
return False, "SQL 含 shell 特殊字符(\" ` $ 或 \\ 转义),已拒绝(cli 数据源)"
|
|
167
|
+
if "\n" in sql or "\r" in sql:
|
|
168
|
+
return False, "SQL 含换行符,已拒绝(cli 数据源)"
|
|
169
|
+
masked = _mask_sql(sql).strip()
|
|
170
|
+
if masked.endswith(";"):
|
|
171
|
+
masked = masked[:-1]
|
|
172
|
+
if ";" in masked:
|
|
173
|
+
return False, "SQL 含多条语句(仅允许末尾单个分号)"
|
|
174
|
+
return True, ""
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _resolve_env(value):
|
|
178
|
+
"""Recursively resolve ${ENV_VAR} environment variable references in config."""
|
|
179
|
+
if isinstance(value, str):
|
|
180
|
+
return _ENV_PATTERN.sub(lambda m: os.environ.get(m.group(1), ""), value)
|
|
181
|
+
if isinstance(value, dict):
|
|
182
|
+
return {k: _resolve_env(v) for k, v in value.items()}
|
|
183
|
+
if isinstance(value, list):
|
|
184
|
+
return [_resolve_env(v) for v in value]
|
|
185
|
+
return value
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def load_db_config(path):
|
|
189
|
+
"""Load db.json config and resolve environment variables.
|
|
190
|
+
|
|
191
|
+
:return: {"type": ..., ...} full config (dict)
|
|
192
|
+
"""
|
|
193
|
+
if not os.path.isfile(path):
|
|
194
|
+
raise ValueError("数据库配置不存在: %s" % path)
|
|
195
|
+
with open(path, "r", encoding="utf-8-sig") as fp:
|
|
196
|
+
config = json.load(fp)
|
|
197
|
+
config = _resolve_env(config)
|
|
198
|
+
if not config.get("type"):
|
|
199
|
+
raise ValueError("db.json 缺少 type 字段(cli/driver/http/file)")
|
|
200
|
+
# file type relative path resolves against the db.json directory (works across cwd);
|
|
201
|
+
# both spellings accepted: top-level "path" or "connect.path", normalized into connect.path
|
|
202
|
+
if config.get("type") == "file":
|
|
203
|
+
connect = config.setdefault("connect", {})
|
|
204
|
+
data_path = connect.get("path") or config.get("path") or ""
|
|
205
|
+
if data_path and not os.path.isabs(data_path):
|
|
206
|
+
data_path = os.path.join(os.path.dirname(os.path.abspath(path)), data_path)
|
|
207
|
+
if data_path:
|
|
208
|
+
connect["path"] = data_path
|
|
209
|
+
config.pop("path", None)
|
|
210
|
+
return config
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def build_provider(config):
|
|
214
|
+
"""Build a provider instance from config.
|
|
215
|
+
|
|
216
|
+
:param config: load_db_config output (or pass a dict directly)
|
|
217
|
+
"""
|
|
218
|
+
provider_type = (config.get("type") or "").lower()
|
|
219
|
+
connect = dict(config.get("connect") or {})
|
|
220
|
+
cfg = dict(config)
|
|
221
|
+
cfg.pop("connect", None)
|
|
222
|
+
cfg.update(connect)
|
|
223
|
+
if provider_type == "cli":
|
|
224
|
+
return CliDbProvider(cfg)
|
|
225
|
+
if provider_type == "driver":
|
|
226
|
+
return DriverDbProvider(cfg)
|
|
227
|
+
if provider_type == "http":
|
|
228
|
+
return HttpDbProvider(cfg)
|
|
229
|
+
if provider_type == "file":
|
|
230
|
+
return FileDbProvider(cfg)
|
|
231
|
+
raise ValueError("不支持的 db 类型: %s(支持 cli/driver/http/file)" % provider_type)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
# ---------------------------------------------------------------- provider abstraction
|
|
235
|
+
|
|
236
|
+
class DbProvider(object):
|
|
237
|
+
"""Database provider abstract base class (readonly)."""
|
|
238
|
+
|
|
239
|
+
def __init__(self, config):
|
|
240
|
+
self.config = config or {}
|
|
241
|
+
|
|
242
|
+
def check_connection(self):
|
|
243
|
+
raise NotImplementedError
|
|
244
|
+
|
|
245
|
+
def list_tables(self):
|
|
246
|
+
raise NotImplementedError
|
|
247
|
+
|
|
248
|
+
def describe(self, table):
|
|
249
|
+
"""Return table structure: columns list ([{name, type, key}] or text lines)."""
|
|
250
|
+
raise NotImplementedError
|
|
251
|
+
|
|
252
|
+
def explain(self, sql):
|
|
253
|
+
"""Dry-run validation (execution plan); raise NotImplementedError when unsupported."""
|
|
254
|
+
raise NotImplementedError
|
|
255
|
+
|
|
256
|
+
def query(self, sql):
|
|
257
|
+
"""Readonly query; return {"columns": [...], "rows": [[...]]} or plain text."""
|
|
258
|
+
raise NotImplementedError
|
|
259
|
+
|
|
260
|
+
def dump_schema(self):
|
|
261
|
+
"""Dump schema snapshot: {db, tables: [{name, columns, indexes}]}."""
|
|
262
|
+
schema = {"db": self.config.get("db") or "", "tables": []}
|
|
263
|
+
for name in self.list_tables():
|
|
264
|
+
schema["tables"].append({
|
|
265
|
+
"name": name,
|
|
266
|
+
"columns": self.describe(name) or [],
|
|
267
|
+
"indexes": [],
|
|
268
|
+
})
|
|
269
|
+
return schema
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _check_then_run(func):
|
|
273
|
+
"""Decorator: run the readonly check first, then execute."""
|
|
274
|
+
def wrapper(self, sql, *args, **kwargs):
|
|
275
|
+
ok, reason = check_readonly(sql)
|
|
276
|
+
if not ok:
|
|
277
|
+
raise ValueError("只读校验失败: " + reason)
|
|
278
|
+
return func(self, sql, *args, **kwargs)
|
|
279
|
+
return wrapper
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
# ---------------------------------------------------------------- cli provider
|
|
283
|
+
|
|
284
|
+
class CliDbProvider(DbProvider):
|
|
285
|
+
"""External CLI command template (any database CLI tool).
|
|
286
|
+
|
|
287
|
+
config (after connect expansion):
|
|
288
|
+
- cmd: required, command template supporting {sql} and any config field placeholders
|
|
289
|
+
- tables_sql/describe_sql/explain_sql: optional, default SHOW TABLES/DESC {table}/EXPLAIN {sql}
|
|
290
|
+
"""
|
|
291
|
+
|
|
292
|
+
def __init__(self, config):
|
|
293
|
+
super(CliDbProvider, self).__init__(config)
|
|
294
|
+
self.cmd = config.get("cmd") or ""
|
|
295
|
+
if not self.cmd:
|
|
296
|
+
raise ValueError("cli provider 需要 cmd 命令模板")
|
|
297
|
+
if '"{sql}"' not in self.cmd:
|
|
298
|
+
raise ValueError('cli 命令模板必须用双引号包裹 {sql} 占位符(如 -e "{sql}"),防止 shell 注入')
|
|
299
|
+
self.tables_sql = config.get("tables_sql") or "SHOW TABLES"
|
|
300
|
+
self.describe_sql = config.get("describe_sql") or "DESC {table}"
|
|
301
|
+
self.explain_sql = config.get("explain_sql") or "EXPLAIN {sql}"
|
|
302
|
+
|
|
303
|
+
def _run(self, sql, timeout=60):
|
|
304
|
+
ok, reason = check_readonly(sql)
|
|
305
|
+
if not ok:
|
|
306
|
+
raise ValueError("只读校验失败: " + reason)
|
|
307
|
+
ok, reason = check_cli_shell_safe(sql)
|
|
308
|
+
if not ok:
|
|
309
|
+
raise ValueError(reason)
|
|
310
|
+
try:
|
|
311
|
+
cmd = self.cmd.format(sql=sql, **self.config)
|
|
312
|
+
except KeyError as exc:
|
|
313
|
+
raise ValueError("命令模板占位符缺少配置: %s" % exc)
|
|
314
|
+
proc = subprocess.run(
|
|
315
|
+
cmd, shell=True, capture_output=True, text=True, timeout=timeout,
|
|
316
|
+
encoding="utf-8", errors="replace",
|
|
317
|
+
)
|
|
318
|
+
if proc.returncode != 0:
|
|
319
|
+
detail = (proc.stderr or proc.stdout or "").strip()
|
|
320
|
+
raise RuntimeError("命令执行失败(%d): %s" % (proc.returncode, detail))
|
|
321
|
+
return proc.stdout
|
|
322
|
+
|
|
323
|
+
def check_connection(self):
|
|
324
|
+
self._run("SELECT 1")
|
|
325
|
+
return "OK"
|
|
326
|
+
|
|
327
|
+
def list_tables(self):
|
|
328
|
+
text = self._run(self.tables_sql)
|
|
329
|
+
return [line.strip() for line in text.splitlines() if line.strip()]
|
|
330
|
+
|
|
331
|
+
def describe(self, table):
|
|
332
|
+
text = self._run(self.describe_sql.format(table=table))
|
|
333
|
+
return [{"name": line.strip()} for line in text.splitlines() if line.strip()]
|
|
334
|
+
|
|
335
|
+
def explain(self, sql):
|
|
336
|
+
return self._run(self.explain_sql.format(sql=sql))
|
|
337
|
+
|
|
338
|
+
def query(self, sql):
|
|
339
|
+
return self._run(sql)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
# ---------------------------------------------------------------- driver provider
|
|
343
|
+
|
|
344
|
+
# dialect default probe SQL & connect param mapping (mysql / sqlserver)
|
|
345
|
+
_DIALECT_SQL = {
|
|
346
|
+
"mysql": {
|
|
347
|
+
"tables_sql": "SHOW TABLES",
|
|
348
|
+
"describe_sql": "DESC {table}",
|
|
349
|
+
"explain_sql": "EXPLAIN {sql}",
|
|
350
|
+
"params": {},
|
|
351
|
+
},
|
|
352
|
+
"sqlserver": {
|
|
353
|
+
"tables_sql": "SELECT name FROM sys.tables",
|
|
354
|
+
"describe_sql": "SELECT column_name, data_type, column_key FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '{table}'",
|
|
355
|
+
"explain_sql": "",
|
|
356
|
+
"params": {"host": "server", "db": "database"},
|
|
357
|
+
},
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
# internal config keys not passed to driver connect()
|
|
361
|
+
_CONNECT_EXCLUDED = {"type", "driver", "readonly", "dialect", "tables_sql", "describe_sql", "explain_sql"}
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
class DriverDbProvider(DbProvider):
|
|
365
|
+
"""Python driver direct connection (optional dependency, importlib dynamic load, e.g. pymysql).
|
|
366
|
+
|
|
367
|
+
dialect(mysql/sqlserver) decides default probe SQL and connect param mapping;
|
|
368
|
+
custom tables_sql/describe_sql/explain_sql still override.
|
|
369
|
+
"""
|
|
370
|
+
|
|
371
|
+
def __init__(self, config):
|
|
372
|
+
super(DriverDbProvider, self).__init__(config)
|
|
373
|
+
driver_name = config.get("driver") or "pymysql"
|
|
374
|
+
self.dialect = (config.get("dialect") or "mysql").lower()
|
|
375
|
+
dialect_conf = _DIALECT_SQL.get(self.dialect) or _DIALECT_SQL["mysql"]
|
|
376
|
+
param_map = dialect_conf.get("params") or {}
|
|
377
|
+
try:
|
|
378
|
+
module = importlib.import_module(driver_name)
|
|
379
|
+
except ImportError:
|
|
380
|
+
raise RuntimeError(
|
|
381
|
+
"缺少数据库驱动 %s,请先安装: pip install %s" % (driver_name, driver_name)
|
|
382
|
+
)
|
|
383
|
+
connect = getattr(module, "connect")
|
|
384
|
+
kwargs = {
|
|
385
|
+
(param_map.get(k) or k): v
|
|
386
|
+
for k, v in config.items()
|
|
387
|
+
if k not in _CONNECT_EXCLUDED and v not in (None, "")
|
|
388
|
+
}
|
|
389
|
+
self.conn = connect(**kwargs)
|
|
390
|
+
self.tables_sql = config.get("tables_sql") or dialect_conf.get("tables_sql") or "SHOW TABLES"
|
|
391
|
+
self.describe_sql = config.get("describe_sql") or dialect_conf.get("describe_sql") or "DESC {table}"
|
|
392
|
+
self.explain_sql = config.get("explain_sql") or dialect_conf.get("explain_sql") or "EXPLAIN {sql}"
|
|
393
|
+
self._describe_cache = {}
|
|
394
|
+
|
|
395
|
+
@property
|
|
396
|
+
def schema(self):
|
|
397
|
+
"""Real-time schema snapshot (describe cache), for review column-level checks."""
|
|
398
|
+
return {
|
|
399
|
+
"db": self.config.get("db") or self.config.get("database") or "",
|
|
400
|
+
"tables": [
|
|
401
|
+
{"name": name, "columns": self._describe_cached(name)}
|
|
402
|
+
for name in self.list_tables()
|
|
403
|
+
],
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
def _describe_cached(self, table):
|
|
407
|
+
if table not in self._describe_cache:
|
|
408
|
+
self._describe_cache[table] = self.describe(table)
|
|
409
|
+
return self._describe_cache[table]
|
|
410
|
+
|
|
411
|
+
def _query_rows(self, sql):
|
|
412
|
+
ok, reason = check_readonly(sql)
|
|
413
|
+
if not ok:
|
|
414
|
+
raise ValueError("只读校验失败: " + reason)
|
|
415
|
+
cur = self.conn.cursor()
|
|
416
|
+
cur.execute(sql)
|
|
417
|
+
rows = cur.fetchall()
|
|
418
|
+
columns = [d[0] for d in (cur.description or [])]
|
|
419
|
+
cur.close()
|
|
420
|
+
return {"columns": columns, "rows": [list(r) for r in rows]}
|
|
421
|
+
|
|
422
|
+
def check_connection(self):
|
|
423
|
+
self._query_rows("SELECT 1")
|
|
424
|
+
return "OK"
|
|
425
|
+
|
|
426
|
+
def list_tables(self):
|
|
427
|
+
result = self._query_rows(self.tables_sql)
|
|
428
|
+
return [str(row[0]) for row in result["rows"] if row]
|
|
429
|
+
|
|
430
|
+
def describe(self, table):
|
|
431
|
+
result = self._query_rows(self.describe_sql.format(table=table))
|
|
432
|
+
columns = []
|
|
433
|
+
for row in result["rows"]:
|
|
434
|
+
if not row:
|
|
435
|
+
continue
|
|
436
|
+
item = {"name": str(row[0])}
|
|
437
|
+
if len(row) > 1:
|
|
438
|
+
item["type"] = str(row[1])
|
|
439
|
+
if len(row) > 3:
|
|
440
|
+
item["key"] = str(row[3])
|
|
441
|
+
columns.append(item)
|
|
442
|
+
return columns
|
|
443
|
+
|
|
444
|
+
def explain(self, sql):
|
|
445
|
+
if not self.explain_sql:
|
|
446
|
+
# sqlserver has no native EXPLAIN: degrade to query
|
|
447
|
+
return self.query(sql)
|
|
448
|
+
result = self._query_rows(self.explain_sql.format(sql=sql))
|
|
449
|
+
return json.dumps(result, ensure_ascii=False, default=str)
|
|
450
|
+
|
|
451
|
+
def query(self, sql):
|
|
452
|
+
result = self._query_rows(sql)
|
|
453
|
+
return json.dumps(result, ensure_ascii=False, default=str)
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
# ---------------------------------------------------------------- http provider
|
|
457
|
+
|
|
458
|
+
class HttpDbProvider(DbProvider):
|
|
459
|
+
"""HTTP API gateway (self-built query platform/data gateway).
|
|
460
|
+
|
|
461
|
+
config:
|
|
462
|
+
- url: required, query endpoint
|
|
463
|
+
- token/headers: optional, auth
|
|
464
|
+
- response convention: {"code": 0, "data": {"columns": [...], "rows": [[...]]}} or plain text
|
|
465
|
+
"""
|
|
466
|
+
|
|
467
|
+
def __init__(self, config):
|
|
468
|
+
super(HttpDbProvider, self).__init__(config)
|
|
469
|
+
self.url = config.get("url") or ""
|
|
470
|
+
if not self.url:
|
|
471
|
+
raise ValueError("http provider 需要 url 查询接口")
|
|
472
|
+
self.headers = dict(config.get("headers") or {})
|
|
473
|
+
token = config.get("token") or ""
|
|
474
|
+
if token:
|
|
475
|
+
self.headers.setdefault("Authorization", "Bearer " + token)
|
|
476
|
+
|
|
477
|
+
def _post(self, sql, timeout=60):
|
|
478
|
+
import urllib.request
|
|
479
|
+
|
|
480
|
+
ok, reason = check_readonly(sql)
|
|
481
|
+
if not ok:
|
|
482
|
+
raise ValueError("只读校验失败: " + reason)
|
|
483
|
+
payload = json.dumps({"sql": sql}).encode("utf-8")
|
|
484
|
+
req = urllib.request.Request(
|
|
485
|
+
self.url, data=payload, headers={
|
|
486
|
+
"Content-Type": "application/json",
|
|
487
|
+
**self.headers,
|
|
488
|
+
}, method="POST",
|
|
489
|
+
)
|
|
490
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
491
|
+
body = resp.read().decode("utf-8", errors="replace")
|
|
492
|
+
try:
|
|
493
|
+
data = json.loads(body)
|
|
494
|
+
except ValueError:
|
|
495
|
+
return {"columns": ["result"], "rows": [[body]]}
|
|
496
|
+
inner = data.get("data") if isinstance(data, dict) else None
|
|
497
|
+
if isinstance(inner, dict) and "rows" in inner:
|
|
498
|
+
return inner
|
|
499
|
+
if isinstance(inner, list):
|
|
500
|
+
return {"columns": [], "rows": [inner]}
|
|
501
|
+
return {"columns": ["result"], "rows": [[body]]}
|
|
502
|
+
|
|
503
|
+
def check_connection(self):
|
|
504
|
+
self._post("SELECT 1")
|
|
505
|
+
return "OK"
|
|
506
|
+
|
|
507
|
+
def list_tables(self):
|
|
508
|
+
result = self._post("SHOW TABLES")
|
|
509
|
+
return [str(row[0]) for row in result.get("rows") or [] if row]
|
|
510
|
+
|
|
511
|
+
def describe(self, table):
|
|
512
|
+
result = self._post("DESC %s" % table)
|
|
513
|
+
return [{"name": str(row[0])} for row in result.get("rows") or [] if row]
|
|
514
|
+
|
|
515
|
+
def explain(self, sql):
|
|
516
|
+
result = self._post("EXPLAIN %s" % sql)
|
|
517
|
+
return json.dumps(result, ensure_ascii=False)
|
|
518
|
+
|
|
519
|
+
def query(self, sql):
|
|
520
|
+
result = self._post(sql)
|
|
521
|
+
return json.dumps(result, ensure_ascii=False)
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
# ---------------------------------------------------------------- file provider
|
|
525
|
+
|
|
526
|
+
class FileDbProvider(DbProvider):
|
|
527
|
+
"""Offline data source file (schema.json), usable without network.
|
|
528
|
+
|
|
529
|
+
file format:
|
|
530
|
+
{"db": "bill_db", "tables": [{"name": "fs_task",
|
|
531
|
+
"columns": [{"name": "id", "type": "bigint", "key": "PRI"}], "indexes": ["idx_code"]}]}
|
|
532
|
+
|
|
533
|
+
explain/query are static checks: extract SQL table names and compare against the schema list.
|
|
534
|
+
"""
|
|
535
|
+
|
|
536
|
+
def __init__(self, config):
|
|
537
|
+
super(FileDbProvider, self).__init__(config)
|
|
538
|
+
path = config.get("path") or ""
|
|
539
|
+
if not path:
|
|
540
|
+
raise ValueError("file provider 需要 path 数据源文件")
|
|
541
|
+
if not os.path.isfile(path):
|
|
542
|
+
raise ValueError("数据源文件不存在: %s" % path)
|
|
543
|
+
with open(path, "r", encoding="utf-8-sig") as fp:
|
|
544
|
+
data = json.load(fp)
|
|
545
|
+
self.schema = data or {}
|
|
546
|
+
self._table_names = [t.get("name") for t in (self.schema.get("tables") or [])]
|
|
547
|
+
|
|
548
|
+
def check_connection(self):
|
|
549
|
+
return "OK(离线数据源, %d 张表)" % len(self._table_names)
|
|
550
|
+
|
|
551
|
+
def dump_schema(self):
|
|
552
|
+
"""Offline data source returns the schema structure from the file directly."""
|
|
553
|
+
return {
|
|
554
|
+
"db": self.schema.get("db") or self.config.get("db") or "",
|
|
555
|
+
"tables": [
|
|
556
|
+
{"name": t.get("name") or "?",
|
|
557
|
+
"columns": t.get("columns") or [],
|
|
558
|
+
"indexes": t.get("indexes") or []}
|
|
559
|
+
for t in (self.schema.get("tables") or [])
|
|
560
|
+
],
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
def list_tables(self):
|
|
564
|
+
return list(self._table_names)
|
|
565
|
+
|
|
566
|
+
def describe(self, table):
|
|
567
|
+
for item in self.schema.get("tables") or []:
|
|
568
|
+
if item.get("name") == table:
|
|
569
|
+
return item.get("columns") or []
|
|
570
|
+
return []
|
|
571
|
+
|
|
572
|
+
def explain(self, sql):
|
|
573
|
+
return self._static_check(sql)
|
|
574
|
+
|
|
575
|
+
def query(self, sql):
|
|
576
|
+
return self._static_check(sql)
|
|
577
|
+
|
|
578
|
+
def _static_check(self, sql):
|
|
579
|
+
"""Static check: table names and columns compared against the schema list (JOIN qualifier routing)."""
|
|
580
|
+
names = tables_of(sql)
|
|
581
|
+
if not names:
|
|
582
|
+
return json.dumps({"columns": [], "rows": [], "note": "未提取到表名,跳过比对"},
|
|
583
|
+
ensure_ascii=False)
|
|
584
|
+
unknown = [n for n in names if n not in self._table_names]
|
|
585
|
+
if unknown:
|
|
586
|
+
raise RuntimeError("表不存在: %s(已知表: %s)" % (", ".join(unknown),
|
|
587
|
+
", ".join(self._table_names) or "无"))
|
|
588
|
+
# column-level check (file data source only); qualified columns only check the qualifying table, unqualified columns pass when any referenced table has it
|
|
589
|
+
columns_by_table = {
|
|
590
|
+
(t.get("name") or ""): {(c.get("name") or "") for c in (t.get("columns") or [])}
|
|
591
|
+
for t in (self.schema.get("tables") or [])
|
|
592
|
+
}
|
|
593
|
+
checked = set()
|
|
594
|
+
for table, column in qualified_columns(sql):
|
|
595
|
+
known = columns_by_table.get(table)
|
|
596
|
+
if known is not None and column not in known:
|
|
597
|
+
raise RuntimeError("列不存在: 表 %s 无列 %s" % (table, column))
|
|
598
|
+
checked.add(column)
|
|
599
|
+
for column in columns_of(sql):
|
|
600
|
+
if column in checked:
|
|
601
|
+
continue
|
|
602
|
+
hit = any(
|
|
603
|
+
column in (columns_by_table.get(t) or set())
|
|
604
|
+
for t in names
|
|
605
|
+
)
|
|
606
|
+
if not hit and any((columns_by_table.get(t) or set()) for t in names):
|
|
607
|
+
raise RuntimeError("列不存在: 引用表 %s 无列 %s" % (", ".join(names), column))
|
|
608
|
+
return json.dumps({"columns": [], "rows": [], "note": "表名匹配: %s" % ", ".join(names)},
|
|
609
|
+
ensure_ascii=False)
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
# ---------------------------------------------------------------- contract SQL verify
|
|
613
|
+
|
|
614
|
+
def verify_contract_sqls(provider, contract, table_routes=None):
|
|
615
|
+
"""Verify all SQL in a contract (readonly + executability); with multiple providers, route by SQL table name.
|
|
616
|
+
|
|
617
|
+
:param provider: DbProvider instance or a list of instances
|
|
618
|
+
:param contract: contract JSON dict (chapters/cases/sql)
|
|
619
|
+
:param table_routes: {table: provider index} routing table (default auto-match by table name, fallback to the first)
|
|
620
|
+
:return: [{case, sql, status, error}] status: ok/rejected/fail
|
|
621
|
+
"""
|
|
622
|
+
providers = provider if isinstance(provider, (list, tuple)) else [provider]
|
|
623
|
+
if not providers:
|
|
624
|
+
raise ValueError("verify_contract_sqls 需要至少一个 provider")
|
|
625
|
+
|
|
626
|
+
def route(sql):
|
|
627
|
+
if table_routes:
|
|
628
|
+
for table in tables_of(sql):
|
|
629
|
+
if table in table_routes:
|
|
630
|
+
return providers[table_routes[table]]
|
|
631
|
+
names = tables_of(sql)
|
|
632
|
+
for candidate in providers:
|
|
633
|
+
known = getattr(candidate, "_table_names", None) or []
|
|
634
|
+
if known and names and names.issubset(set(known)):
|
|
635
|
+
return candidate
|
|
636
|
+
return providers[0]
|
|
637
|
+
|
|
638
|
+
results = []
|
|
639
|
+
for chapter in contract.get("chapters") or []:
|
|
640
|
+
for case in chapter.get("cases") or []:
|
|
641
|
+
for sql in case.get("sql") or []:
|
|
642
|
+
ok, reason = check_readonly(sql)
|
|
643
|
+
if not ok:
|
|
644
|
+
results.append({"case": case.get("t") or "", "sql": sql,
|
|
645
|
+
"status": "rejected", "error": reason})
|
|
646
|
+
continue
|
|
647
|
+
target = route(sql)
|
|
648
|
+
try:
|
|
649
|
+
try:
|
|
650
|
+
target.explain(sql)
|
|
651
|
+
except NotImplementedError:
|
|
652
|
+
target.query(sql)
|
|
653
|
+
results.append({"case": case.get("t") or "", "sql": sql,
|
|
654
|
+
"status": "ok", "error": ""})
|
|
655
|
+
except Exception as exc: # 连接/执行/静态校验失败均记为 fail
|
|
656
|
+
results.append({"case": case.get("t") or "", "sql": sql,
|
|
657
|
+
"status": "fail", "error": str(exc)})
|
|
658
|
+
return results
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
def schema_to_text(schema):
|
|
662
|
+
"""Convert a schema snapshot to text (for LLM prompt injection)."""
|
|
663
|
+
lines = []
|
|
664
|
+
db = schema.get("db")
|
|
665
|
+
if db:
|
|
666
|
+
lines.append("数据库: %s" % db)
|
|
667
|
+
for table in schema.get("tables") or []:
|
|
668
|
+
name = table.get("name") or "?"
|
|
669
|
+
columns = table.get("columns") or []
|
|
670
|
+
col_text = ", ".join(
|
|
671
|
+
(c.get("name") or "") + (":%s" % c.get("type") if c.get("type") else "")
|
|
672
|
+
+ (":%s" % c.get("key") if c.get("key") else "")
|
|
673
|
+
for c in columns
|
|
674
|
+
)
|
|
675
|
+
lines.append("表[%s]: %s" % (name, col_text or "(无列信息)"))
|
|
676
|
+
return "\n".join(lines)
|