astsight 0.1.0__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.
Files changed (158) hide show
  1. astsight/__init__.py +18 -0
  2. astsight/__main__.py +4 -0
  3. astsight/agent/__init__.py +44 -0
  4. astsight/agent/case_design.py +421 -0
  5. astsight/agent/casegen.py +196 -0
  6. astsight/agent/data_prep.py +265 -0
  7. astsight/agent/diagnosis.py +221 -0
  8. astsight/agent/errors.py +15 -0
  9. astsight/agent/flow.py +1345 -0
  10. astsight/agent/jar.py +235 -0
  11. astsight/agent/mock_semantics.py +136 -0
  12. astsight/agent/mockplan.py +481 -0
  13. astsight/agent/models.py +285 -0
  14. astsight/agent/repair.py +538 -0
  15. astsight/agent/rule_analysis.py +150 -0
  16. astsight/agent/semantic.py +250 -0
  17. astsight/agent/sut.py +442 -0
  18. astsight/artifacts.py +73 -0
  19. astsight/cases/__init__.py +5 -0
  20. astsight/cases/adapters.py +79 -0
  21. astsight/cases/context.py +764 -0
  22. astsight/cases/data_refs.py +167 -0
  23. astsight/cases/deleted_cleanup.py +121 -0
  24. astsight/cases/draft.py +575 -0
  25. astsight/cases/expressions.py +256 -0
  26. astsight/cases/proposal.py +1500 -0
  27. astsight/cases/regexsample.py +242 -0
  28. astsight/cases/relations.py +193 -0
  29. astsight/cases/requirements.py +269 -0
  30. astsight/cases/store.py +362 -0
  31. astsight/cases/strength.py +77 -0
  32. astsight/cases/templates.py +613 -0
  33. astsight/cases/validate.py +738 -0
  34. astsight/cases/validate_assertions.py +733 -0
  35. astsight/cases/validate_base.py +418 -0
  36. astsight/cases/validate_coverage.py +288 -0
  37. astsight/cases/validate_data.py +227 -0
  38. astsight/cases/validate_dubbo.py +300 -0
  39. astsight/cases/validate_mqmock.py +349 -0
  40. astsight/cases/validate_profile.py +168 -0
  41. astsight/cases/validate_rules.py +280 -0
  42. astsight/cases/validate_semantics.py +199 -0
  43. astsight/cases/validate_steps.py +510 -0
  44. astsight/changes/__init__.py +13 -0
  45. astsight/changes/contract_diff.py +310 -0
  46. astsight/changes/deleted.py +161 -0
  47. astsight/changes/git_diff.py +182 -0
  48. astsight/changes/impact.py +464 -0
  49. astsight/changes/symbol_diff.py +431 -0
  50. astsight/changes/transport_contracts.py +385 -0
  51. astsight/cli.py +1537 -0
  52. astsight/codegen/__init__.py +5 -0
  53. astsight/codegen/pytest_gen.py +1814 -0
  54. astsight/commands/__init__.py +1 -0
  55. astsight/commands/_shared.py +42 -0
  56. astsight/commands/data.py +490 -0
  57. astsight/commands/init.py +172 -0
  58. astsight/commands/mock.py +333 -0
  59. astsight/commands/rules.py +360 -0
  60. astsight/data/__init__.py +124 -0
  61. astsight/data/annotations.py +458 -0
  62. astsight/data/apply.py +310 -0
  63. astsight/data/catalog.py +402 -0
  64. astsight/data/codeconst.py +1281 -0
  65. astsight/data/connection.py +74 -0
  66. astsight/data/dbml.py +727 -0
  67. astsight/data/ddl.py +642 -0
  68. astsight/data/dialects.py +156 -0
  69. astsight/data/fixtures.py +193 -0
  70. astsight/data/plan.py +444 -0
  71. astsight/data/reflect.py +667 -0
  72. astsight/data/render.py +133 -0
  73. astsight/data/seed.py +142 -0
  74. astsight/data/semantics.py +211 -0
  75. astsight/data/states.py +1214 -0
  76. astsight/data/validate.py +234 -0
  77. astsight/evaluation.py +205 -0
  78. astsight/execute/__init__.py +6 -0
  79. astsight/execute/diagnose.py +192 -0
  80. astsight/execute/dubbo_targets.py +734 -0
  81. astsight/execute/runner.py +357 -0
  82. astsight/feedback.py +573 -0
  83. astsight/inventory.py +406 -0
  84. astsight/llm/__init__.py +28 -0
  85. astsight/llm/client.py +634 -0
  86. astsight/mock/__init__.py +122 -0
  87. astsight/mock/evidence.py +388 -0
  88. astsight/mock/gripmock_binary.py +246 -0
  89. astsight/mock/grpc_descriptor.py +299 -0
  90. astsight/mock/grpc_runtime.py +423 -0
  91. astsight/mock/identity.py +482 -0
  92. astsight/mock/matching.py +75 -0
  93. astsight/mock/plan.py +1246 -0
  94. astsight/mock/replies.py +84 -0
  95. astsight/mock/routes.py +231 -0
  96. astsight/mock/runtime.py +225 -0
  97. astsight/mock/semantic.py +539 -0
  98. astsight/mock/server.py +1481 -0
  99. astsight/mock/sessions.py +222 -0
  100. astsight/mq/__init__.py +1 -0
  101. astsight/mq/inject/capture.py +337 -0
  102. astsight/mq/inject/sitecustomize.py +14 -0
  103. astsight/persistence.py +86 -0
  104. astsight/pipeline.py +1733 -0
  105. astsight/profile/__init__.py +36 -0
  106. astsight/profile/builder.py +297 -0
  107. astsight/profile/callsite.py +46 -0
  108. astsight/profile/downstream.py +1967 -0
  109. astsight/profile/dubbo.py +2141 -0
  110. astsight/profile/grpc_downstream.py +758 -0
  111. astsight/profile/javaclass.py +431 -0
  112. astsight/profile/javadeps.py +277 -0
  113. astsight/profile/javatypes.py +1037 -0
  114. astsight/profile/langroutes.py +1051 -0
  115. astsight/profile/langscan.py +1363 -0
  116. astsight/profile/mq.py +804 -0
  117. astsight/profile/openapi.py +288 -0
  118. astsight/report/__init__.py +5 -0
  119. astsight/report/merge.py +1098 -0
  120. astsight/rules/__init__.py +102 -0
  121. astsight/rules/conflicts.py +269 -0
  122. astsight/rules/context.py +552 -0
  123. astsight/rules/contract.py +233 -0
  124. astsight/rules/contract_model.py +1361 -0
  125. astsight/rules/coverage.py +127 -0
  126. astsight/rules/diff.py +143 -0
  127. astsight/rules/draft.py +152 -0
  128. astsight/rules/grounding.py +110 -0
  129. astsight/rules/relations.py +319 -0
  130. astsight/rules/render.py +413 -0
  131. astsight/rules/store.py +547 -0
  132. astsight/rules/validate.py +399 -0
  133. astsight/sidecar/__init__.py +37 -0
  134. astsight/sidecar/dubbo.py +449 -0
  135. astsight/sidecar/package.py +251 -0
  136. astsight/sidecar/triple.py +258 -0
  137. astsight-0.1.0.dist-info/METADATA +1348 -0
  138. astsight-0.1.0.dist-info/RECORD +158 -0
  139. astsight-0.1.0.dist-info/WHEEL +5 -0
  140. astsight-0.1.0.dist-info/entry_points.txt +2 -0
  141. astsight-0.1.0.dist-info/top_level.txt +3 -0
  142. codegraph/__init__.py +55 -0
  143. codegraph/bridge/codegraph_worker.mjs +548 -0
  144. codegraph/client.py +158 -0
  145. codegraph/embedded.py +561 -0
  146. codegraph/memory.py +89 -0
  147. codegraph/route_repair.py +1680 -0
  148. codegraph/runtime.py +270 -0
  149. contracts/__init__.py +245 -0
  150. contracts/base.py +37 -0
  151. contracts/cases.py +100 -0
  152. contracts/data.py +209 -0
  153. contracts/entities.py +436 -0
  154. contracts/enums.py +355 -0
  155. contracts/mock.py +350 -0
  156. contracts/mock_plan.py +209 -0
  157. contracts/mock_semantic.py +89 -0
  158. contracts/rules.py +340 -0
astsight/data/ddl.py ADDED
@@ -0,0 +1,642 @@
1
+ """DDL 解析(C5a 的结构事实源)。
2
+
3
+ v1 覆盖常见 `CREATE TABLE` 与 `ALTER TABLE ... ADD CONSTRAINT/COLUMN`:
4
+ 列、类型、NOT NULL、DEFAULT、PK、UNIQUE、REFERENCES、CHECK(IN)、注释。
5
+ 无法识别的语句只进 warnings,不猜结构。
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from dataclasses import dataclass, field
11
+ from typing import Any
12
+
13
+ MAX_DDL_BYTES = 5 * 1024 * 1024
14
+ MAX_TABLES = 500
15
+ MAX_COLUMNS_PER_TABLE = 500
16
+
17
+ _CONSTRAINT_KEYWORDS = {
18
+ "CONSTRAINT",
19
+ "PRIMARY",
20
+ "NOT",
21
+ "NULL",
22
+ "DEFAULT",
23
+ "UNIQUE",
24
+ "REFERENCES",
25
+ "CHECK",
26
+ "COLLATE",
27
+ "GENERATED",
28
+ "AUTOINCREMENT",
29
+ "AUTO_INCREMENT",
30
+ "COMMENT",
31
+ "ON",
32
+ }
33
+ _IDENT_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_$]*")
34
+ _ENUM_RE = re.compile(r"^ENUM\s*\((.*)\)$", re.IGNORECASE | re.DOTALL)
35
+ _CHECK_IN_RE = re.compile(
36
+ r"CHECK\s*\(\s*[\w\"`.\[\]]+\s+IN\s*\((.*)\)\s*\)",
37
+ re.IGNORECASE | re.DOTALL,
38
+ )
39
+
40
+
41
+ class DDLError(ValueError):
42
+ """DDL 不可解析/超出资源上限。"""
43
+
44
+
45
+ @dataclass
46
+ class ParsedColumn:
47
+ name: str
48
+ type: str = ""
49
+ nullable: bool = True
50
+ default: Any = None
51
+ primary_key: bool = False
52
+ unique: bool = False
53
+ comment: str = ""
54
+ enum_values: list[Any] = field(default_factory=list)
55
+ # DBML `Enum` 值上的 note;键统一为 str(value),与注释解析共用。
56
+ value_meanings: dict[str, str] = field(default_factory=dict)
57
+
58
+
59
+ @dataclass
60
+ class ParsedForeignKey:
61
+ child_table: str
62
+ child_columns: list[str]
63
+ parent_table: str
64
+ parent_columns: list[str]
65
+
66
+
67
+ @dataclass
68
+ class ParsedTable:
69
+ name: str
70
+ columns: list[ParsedColumn] = field(default_factory=list)
71
+ primary_key: list[str] = field(default_factory=list)
72
+ foreign_keys: list[ParsedForeignKey] = field(default_factory=list)
73
+ comment: str = ""
74
+
75
+ def column_index(self) -> dict[str, ParsedColumn]:
76
+ return {column.name: column for column in self.columns}
77
+
78
+
79
+ @dataclass
80
+ class ParsedDDL:
81
+ tables: list[ParsedTable] = field(default_factory=list)
82
+ warnings: list[str] = field(default_factory=list)
83
+
84
+ def table_index(self) -> dict[str, ParsedTable]:
85
+ return {table.name: table for table in self.tables}
86
+
87
+ @property
88
+ def foreign_keys(self) -> list[ParsedForeignKey]:
89
+ return [fk for table in self.tables for fk in table.foreign_keys]
90
+
91
+
92
+ def _strip_comments(text: str) -> str:
93
+ out: list[str] = []
94
+ index = 0
95
+ length = len(text)
96
+ quote: str | None = None
97
+ while index < length:
98
+ char = text[index]
99
+ if quote:
100
+ out.append(char)
101
+ if char == quote:
102
+ if index + 1 < length and text[index + 1] == quote:
103
+ out.append(text[index + 1])
104
+ index += 2
105
+ continue
106
+ quote = None
107
+ index += 1
108
+ continue
109
+ if char in {"'", '"', "`"}:
110
+ quote = char
111
+ out.append(char)
112
+ index += 1
113
+ continue
114
+ if char == "-" and text.startswith("--", index):
115
+ while index < length and text[index] != "\n":
116
+ index += 1
117
+ continue
118
+ if char == "/" and text.startswith("/*", index):
119
+ end = text.find("*/", index + 2)
120
+ index = length if end < 0 else end + 2
121
+ continue
122
+ out.append(char)
123
+ index += 1
124
+ return "".join(out)
125
+
126
+
127
+ def split_statements(text: str) -> list[str]:
128
+ cleaned = _strip_comments(text)
129
+ statements: list[str] = []
130
+ current: list[str] = []
131
+ depth = 0
132
+ quote: str | None = None
133
+ index = 0
134
+ while index < len(cleaned):
135
+ char = cleaned[index]
136
+ if quote:
137
+ current.append(char)
138
+ if char == quote:
139
+ if index + 1 < len(cleaned) and cleaned[index + 1] == quote:
140
+ current.append(cleaned[index + 1])
141
+ index += 2
142
+ continue
143
+ quote = None
144
+ index += 1
145
+ continue
146
+ if char in {"'", '"', "`"}:
147
+ quote = char
148
+ current.append(char)
149
+ elif char == "[":
150
+ quote = "]"
151
+ current.append(char)
152
+ elif char == "(":
153
+ depth += 1
154
+ current.append(char)
155
+ elif char == ")":
156
+ depth = max(0, depth - 1)
157
+ current.append(char)
158
+ elif char == ";" and depth == 0:
159
+ statement = "".join(current).strip()
160
+ if statement:
161
+ statements.append(statement)
162
+ current = []
163
+ else:
164
+ current.append(char)
165
+ index += 1
166
+ tail = "".join(current).strip()
167
+ if tail:
168
+ statements.append(tail)
169
+ return statements
170
+
171
+
172
+ def _split_top_level(text: str, separator: str = ",") -> list[str]:
173
+ parts: list[str] = []
174
+ current: list[str] = []
175
+ depth = 0
176
+ quote: str | None = None
177
+ index = 0
178
+ while index < len(text):
179
+ char = text[index]
180
+ if quote:
181
+ current.append(char)
182
+ if char == quote:
183
+ if index + 1 < len(text) and text[index + 1] == quote:
184
+ current.append(text[index + 1])
185
+ index += 2
186
+ continue
187
+ quote = None
188
+ index += 1
189
+ continue
190
+ if char in {"'", '"', "`"}:
191
+ quote = char
192
+ current.append(char)
193
+ elif char == "[":
194
+ quote = "]"
195
+ current.append(char)
196
+ elif char == "(":
197
+ depth += 1
198
+ current.append(char)
199
+ elif char == ")":
200
+ depth = max(0, depth - 1)
201
+ current.append(char)
202
+ elif char == separator and depth == 0:
203
+ part = "".join(current).strip()
204
+ if part:
205
+ parts.append(part)
206
+ current = []
207
+ else:
208
+ current.append(char)
209
+ index += 1
210
+ tail = "".join(current).strip()
211
+ if tail:
212
+ parts.append(tail)
213
+ return parts
214
+
215
+
216
+ def _unquote(value: str) -> str:
217
+ value = value.strip()
218
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"', "`"}:
219
+ body = value[1:-1]
220
+ quote = value[0]
221
+ return body.replace(quote + quote, quote)
222
+ if len(value) >= 2 and value[0] == "[" and value[-1] == "]":
223
+ return value[1:-1]
224
+ return value
225
+
226
+
227
+ def _read_identifier(text: str, index: int) -> tuple[str, int]:
228
+ while index < len(text) and text[index].isspace():
229
+ index += 1
230
+ if index >= len(text):
231
+ return "", index
232
+ char = text[index]
233
+ if char in {"'", '"', "`"}:
234
+ quote = char
235
+ end = index + 1
236
+ while end < len(text):
237
+ if text[end] == quote:
238
+ if end + 1 < len(text) and text[end + 1] == quote:
239
+ end += 2
240
+ continue
241
+ return text[index + 1 : end], end + 1
242
+ end += 1
243
+ return text[index + 1 :], len(text)
244
+ if char == "[":
245
+ end = text.find("]", index + 1)
246
+ if end < 0:
247
+ return text[index + 1 :], len(text)
248
+ return text[index + 1 : end], end + 1
249
+ match = _IDENT_RE.match(text, index)
250
+ if not match:
251
+ return "", index
252
+ return match.group(0), match.end()
253
+
254
+
255
+ def _read_identifier_list(text: str) -> list[str]:
256
+ return [name for name in (_unquote(item) for item in _split_top_level(text)) if name]
257
+
258
+
259
+ def _normalize_type(raw: str) -> str:
260
+ value = " ".join(raw.split())
261
+ if re.match(r"^ENUM\s*\(", value, re.IGNORECASE):
262
+ return "ENUM" + value[value.find("(") :]
263
+ return value.upper()
264
+
265
+
266
+ def _parse_enum_values(raw: str) -> list[Any]:
267
+ inner = raw.strip()
268
+ if inner.startswith("(") and inner.endswith(")"):
269
+ inner = inner[1:-1]
270
+ values: list[Any] = []
271
+ for item in _split_top_level(inner):
272
+ item = item.strip()
273
+ if not item:
274
+ continue
275
+ values.append(_unquote(item))
276
+ return values
277
+
278
+
279
+ def normalize_type(raw: str) -> str:
280
+ """公开的类型规范化:DBML/反射与 DDL 解析共用。"""
281
+ return _normalize_type(raw)
282
+
283
+
284
+ def parse_enum_values(raw: str) -> list[Any]:
285
+ """从 ``(a, b)`` 或 ``ENUM(a, b)`` 中解析枚举值。"""
286
+ return _parse_enum_values(raw)
287
+
288
+
289
+ def _parse_default(text: str, index: int) -> tuple[Any, int]:
290
+ while index < len(text) and text[index].isspace():
291
+ index += 1
292
+ if index >= len(text):
293
+ return None, index
294
+ if text[index] in {"'", '"'}:
295
+ quote = text[index]
296
+ end = index + 1
297
+ while end < len(text):
298
+ if text[end] == quote:
299
+ if end + 1 < len(text) and text[end + 1] == quote:
300
+ end += 2
301
+ continue
302
+ return text[index + 1 : end], end + 1
303
+ end += 1
304
+ return text[index + 1 :], len(text)
305
+ if text[index] == "(":
306
+ depth = 0
307
+ end = index
308
+ while end < len(text):
309
+ if text[end] == "(":
310
+ depth += 1
311
+ elif text[end] == ")":
312
+ depth -= 1
313
+ if depth == 0:
314
+ return text[index : end + 1], end + 1
315
+ end += 1
316
+ return text[index:], len(text)
317
+ match = re.match(r"[^\s,]+", text[index:])
318
+ if not match:
319
+ return None, index
320
+ token = match.group(0)
321
+ return token, index + len(token)
322
+
323
+
324
+ def _find_keyword(text: str, keywords: set[str], start: int = 0) -> int:
325
+ """在括号深度 0 找到第一个独立关键字。"""
326
+ depth = 0
327
+ quote: str | None = None
328
+ index = start
329
+ while index < len(text):
330
+ char = text[index]
331
+ if quote:
332
+ if char == quote:
333
+ if index + 1 < len(text) and text[index + 1] == quote:
334
+ index += 2
335
+ continue
336
+ quote = None
337
+ index += 1
338
+ continue
339
+ if char in {"'", '"', "`"}:
340
+ quote = char
341
+ index += 1
342
+ continue
343
+ if char == "[":
344
+ quote = "]"
345
+ index += 1
346
+ continue
347
+ if char == "(":
348
+ depth += 1
349
+ index += 1
350
+ continue
351
+ if char == ")":
352
+ depth = max(0, depth - 1)
353
+ index += 1
354
+ continue
355
+ if depth == 0 and (char.isalpha() or char == "_"):
356
+ match = _IDENT_RE.match(text, index)
357
+ if match:
358
+ word = match.group(0).upper()
359
+ if word in keywords:
360
+ return index
361
+ index = match.end()
362
+ continue
363
+ index += 1
364
+ return -1
365
+
366
+
367
+ def _extract_parens(text: str, start: int = 0) -> tuple[str, int, int]:
368
+ """返回 (括号内文本, 左括号位置, 右括号位置)。"""
369
+ left = text.find("(", start)
370
+ if left < 0:
371
+ return "", -1, -1
372
+ depth = 0
373
+ quote: str | None = None
374
+ index = left
375
+ while index < len(text):
376
+ char = text[index]
377
+ if quote:
378
+ if char == quote:
379
+ quote = None
380
+ index += 1
381
+ continue
382
+ if char in {"'", '"', "`"}:
383
+ quote = char
384
+ elif char == "(":
385
+ depth += 1
386
+ elif char == ")":
387
+ depth -= 1
388
+ if depth == 0:
389
+ return text[left + 1 : index], left, index
390
+ index += 1
391
+ return "", left, -1
392
+
393
+
394
+ def _read_keyword_value(text: str, keyword: str) -> str | None:
395
+ pattern = re.compile(rf"\b{keyword}\b\s*(?:=\s*)?(.+)$", re.IGNORECASE | re.DOTALL)
396
+ match = pattern.search(text)
397
+ if not match:
398
+ return None
399
+ value = match.group(1).strip()
400
+ value = value.rstrip(",").strip()
401
+ return _unquote(value)
402
+
403
+
404
+ def _parse_column(part: str) -> ParsedColumn | None:
405
+ text = re.sub(r"^CONSTRAINT\s+\S+\s+", "", part.strip(), flags=re.IGNORECASE)
406
+ name, index = _read_identifier(text, 0)
407
+ if not name:
408
+ return None
409
+ remainder = text[index:].strip()
410
+ if re.match(r"^(PRIMARY\s+KEY|UNIQUE|FOREIGN\s+KEY|CHECK)\b", remainder, re.IGNORECASE):
411
+ return None
412
+ stop = _find_keyword(remainder, _CONSTRAINT_KEYWORDS)
413
+ raw_type = remainder if stop < 0 else remainder[:stop]
414
+ type_text = _normalize_type(raw_type).rstrip(",")
415
+ column = ParsedColumn(name=name, type=type_text)
416
+ upper = remainder.upper()
417
+ column.nullable = not bool(re.search(r"\bNOT\s+NULL\b", upper))
418
+ if re.search(r"\bPRIMARY\s+KEY\b", upper):
419
+ column.primary_key = True
420
+ column.nullable = False
421
+ if re.search(r"\bUNIQUE\b", upper):
422
+ column.unique = True
423
+ default_match = re.search(r"\bDEFAULT\b", remainder, re.IGNORECASE)
424
+ if default_match:
425
+ value, _ = _parse_default(remainder, default_match.end())
426
+ column.default = value
427
+ comment = _read_keyword_value(remainder, "COMMENT")
428
+ if comment:
429
+ column.comment = comment[:1_000]
430
+ enum_match = _ENUM_RE.match(type_text)
431
+ if enum_match:
432
+ column.enum_values = _parse_enum_values(enum_match.group(1))
433
+ check_match = _CHECK_IN_RE.search(remainder.strip().rstrip(","))
434
+ if check_match and not column.enum_values:
435
+ column.enum_values = _parse_enum_values(check_match.group(1))
436
+ return column
437
+
438
+
439
+ def _parse_pk_columns(part: str) -> list[str]:
440
+ inner, _, _ = _extract_parens(part)
441
+ return _read_identifier_list(inner)
442
+
443
+
444
+ def _parse_references(rest: str) -> tuple[str, list[str]]:
445
+ match = re.search(r"\bREFERENCES\b", rest, re.IGNORECASE)
446
+ if not match:
447
+ return "", []
448
+ parent, index = _read_identifier(rest, match.end())
449
+ inner, _, _ = _extract_parens(rest, index)
450
+ return parent, _read_identifier_list(inner)
451
+
452
+
453
+ def _parse_table_constraint(
454
+ part: str, table: ParsedTable
455
+ ) -> bool:
456
+ text = re.sub(r"^CONSTRAINT\s+\S+\s+", "", part.strip(), flags=re.IGNORECASE)
457
+ upper = text.upper()
458
+ if upper.startswith("PRIMARY KEY"):
459
+ table.primary_key = _parse_pk_columns(text)
460
+ for name in table.primary_key:
461
+ column = table.column_index().get(name)
462
+ if column is not None:
463
+ column.primary_key = True
464
+ column.nullable = False
465
+ return True
466
+ if upper.startswith("UNIQUE"):
467
+ for name in _parse_pk_columns(text):
468
+ column = table.column_index().get(name)
469
+ if column is not None:
470
+ column.unique = True
471
+ return True
472
+ if upper.startswith("FOREIGN KEY"):
473
+ child_inner, _, closed = _extract_parens(text)
474
+ if closed < 0:
475
+ return True
476
+ parent, parent_columns = _parse_references(text[closed + 1 :])
477
+ child_columns = _read_identifier_list(child_inner)
478
+ if child_columns and parent and parent_columns:
479
+ table.foreign_keys.append(
480
+ ParsedForeignKey(
481
+ child_table=table.name,
482
+ child_columns=child_columns,
483
+ parent_table=parent,
484
+ parent_columns=parent_columns,
485
+ )
486
+ )
487
+ return True
488
+ if upper.startswith("CHECK"):
489
+ check_match = _CHECK_IN_RE.search(text.rstrip(","))
490
+ if check_match:
491
+ values = _parse_enum_values(check_match.group(1))
492
+ name_match = re.search(
493
+ r"CHECK\s*\(\s*[\"`\[]?([A-Za-z_][\w$]*)", text, re.IGNORECASE
494
+ )
495
+ if name_match:
496
+ column = table.column_index().get(name_match.group(1))
497
+ if column is not None and not column.enum_values:
498
+ column.enum_values = values
499
+ return True
500
+ return False
501
+
502
+
503
+ def _parse_create_table(statement: str, warnings: list[str]) -> ParsedTable | None:
504
+ match = re.search(r"\bCREATE\s+(?:TEMP(?:ORARY)?\s+)?TABLE\b", statement, re.IGNORECASE)
505
+ if not match:
506
+ return None
507
+ rest = statement[match.end() :].lstrip()
508
+ rest = re.sub(r"^IF\s+NOT\s+EXISTS\s+", "", rest, flags=re.IGNORECASE)
509
+ name, index = _read_identifier(rest, 0)
510
+ if not name:
511
+ warnings.append("create_table_name_missing")
512
+ return None
513
+ inner, _, closed = _extract_parens(rest, index)
514
+ if closed < 0:
515
+ warnings.append(f"create_table_unclosed:{name}")
516
+ return None
517
+ table = ParsedTable(name=name)
518
+ table.comment = _read_keyword_value(rest[closed + 1 :], "COMMENT") or ""
519
+ for part in _split_top_level(inner):
520
+ if _parse_table_constraint(part, table):
521
+ continue
522
+ column = _parse_column(part)
523
+ if column is None:
524
+ warnings.append(f"column_unparsed:{name}:{part[:60]}")
525
+ continue
526
+ table.columns.append(column)
527
+ if re.search(r"\bREFERENCES\b", part, re.IGNORECASE):
528
+ _inline_reference(column, part, table)
529
+ if not table.primary_key:
530
+ table.primary_key = [
531
+ column.name for column in table.columns if column.primary_key
532
+ ]
533
+ if len(table.columns) > MAX_COLUMNS_PER_TABLE:
534
+ raise DDLError(
535
+ f"{name} 列数 {len(table.columns)} 超过上限 {MAX_COLUMNS_PER_TABLE}"
536
+ )
537
+ return table
538
+
539
+
540
+ def _inline_reference(column: ParsedColumn, part: str, table: ParsedTable) -> None:
541
+ rest = part[part.upper().find("REFERENCES") :] if "REFERENCES" in part.upper() else ""
542
+ parent, parent_columns = _parse_references(rest)
543
+ if parent and parent_columns:
544
+ table.foreign_keys.append(
545
+ ParsedForeignKey(
546
+ child_table=table.name,
547
+ child_columns=[column.name],
548
+ parent_table=parent,
549
+ parent_columns=parent_columns,
550
+ )
551
+ )
552
+
553
+
554
+ def _parse_alter_table(
555
+ statement: str, tables: dict[str, ParsedTable], warnings: list[str]
556
+ ) -> None:
557
+ match = re.search(r"\bALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?", statement, re.IGNORECASE)
558
+ if not match:
559
+ return
560
+ name, index = _read_identifier(statement, match.end())
561
+ table = tables.get(name)
562
+ if table is None:
563
+ warnings.append(f"alter_table_unknown:{name}")
564
+ return
565
+ rest = statement[index:].strip()
566
+ rest = re.sub(r"^ADD\s+", "", rest, flags=re.IGNORECASE)
567
+ if re.match(r"^(CONSTRAINT\s+\S+\s+)?FOREIGN\s+KEY\b", rest, re.IGNORECASE):
568
+ _parse_table_constraint(rest, table)
569
+ return
570
+ if re.match(r"^COLUMN\b", rest, re.IGNORECASE):
571
+ rest = re.sub(r"^COLUMN\s+", "", rest, flags=re.IGNORECASE)
572
+ if re.match(r"^(PRIMARY\s+KEY|UNIQUE|CHECK)\b", rest, re.IGNORECASE):
573
+ _parse_table_constraint(rest, table)
574
+ return
575
+ column = _parse_column(rest)
576
+ if column is not None:
577
+ table.columns.append(column)
578
+ if column.primary_key and column.name not in table.primary_key:
579
+ table.primary_key.append(column.name)
580
+ _inline_reference(column, rest, table)
581
+ return
582
+ warnings.append(f"alter_table_unparsed:{name}:{rest[:60]}")
583
+
584
+
585
+ def parse_ddl(text: str, *, dialect: str = "sqlite") -> ParsedDDL:
586
+ if len(text.encode("utf-8")) > MAX_DDL_BYTES:
587
+ raise DDLError(f"DDL 过大: {len(text.encode('utf-8'))} bytes")
588
+ result = ParsedDDL()
589
+ tables: dict[str, ParsedTable] = {}
590
+ for statement in split_statements(text):
591
+ head = statement.lstrip().upper()
592
+ if head.startswith("CREATE"):
593
+ if "TABLE" not in head:
594
+ result.warnings.append(f"statement_unsupported:{head[:40]}")
595
+ continue
596
+ table = _parse_create_table(statement, result.warnings)
597
+ if table is None:
598
+ continue
599
+ if table.name in tables:
600
+ result.warnings.append(f"table_duplicate:{table.name}")
601
+ continue
602
+ tables[table.name] = table
603
+ if len(tables) > MAX_TABLES:
604
+ raise DDLError(f"表数量超过上限 {MAX_TABLES}")
605
+ continue
606
+ if head.startswith("ALTER"):
607
+ _parse_alter_table(statement, tables, result.warnings)
608
+ continue
609
+ if head.startswith(("PRAGMA", "SET", "BEGIN", "COMMIT", "INSERT")):
610
+ continue
611
+ result.warnings.append(f"statement_unsupported:{head[:40]}")
612
+ for table in tables.values():
613
+ unique: list[ParsedForeignKey] = []
614
+ seen: set[tuple[Any, ...]] = set()
615
+ for fk in table.foreign_keys:
616
+ key = (
617
+ fk.child_table,
618
+ tuple(fk.child_columns),
619
+ fk.parent_table,
620
+ tuple(fk.parent_columns),
621
+ )
622
+ if key in seen:
623
+ continue
624
+ seen.add(key)
625
+ unique.append(fk)
626
+ table.foreign_keys = unique
627
+ result.tables = list(tables.values())
628
+ return result
629
+
630
+
631
+ __all__ = [
632
+ "DDLError",
633
+ "MAX_DDL_BYTES",
634
+ "ParsedColumn",
635
+ "ParsedDDL",
636
+ "ParsedForeignKey",
637
+ "ParsedTable",
638
+ "normalize_type",
639
+ "parse_ddl",
640
+ "parse_enum_values",
641
+ "split_statements",
642
+ ]