codecop 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 (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,526 @@
1
+ """MyBatis mapper XML: every <select|insert|update|delete id=...> statement as a site, with its dynamic SQL rendered.
2
+
3
+ A mapper file (`<mapper namespace="...">`) is read with the standard library's expat (no DTD is fetched). Each
4
+ statement becomes one site per variant, at the statement tag's line, with sink `namespace.id`:
5
+
6
+ * `#{x}` (a bound value) becomes the value part «x»; `${x}` (text pasted into the SQL) becomes the run-time part «x»
7
+ and the site's mechanism is `orm_raw_fragment`.
8
+ * `<include refid>` is inlined from `<sql id>` of the same mapper or of another namespace, with its `<property>`
9
+ values substituted for `${name}`.
10
+ * `<where>`, `<set>` and `<trim prefix suffix prefixOverrides suffixOverrides>` behave as MyBatis does.
11
+ * `<if>` and `<choose><when><otherwise>` give a family of variants: the base (every `<if>` false, every
12
+ `<choose>` on its `<otherwise>`), then one alternative at a time (one `<if>` true with the ones around it, one
13
+ `<when>` taken), never every combination. Capped by `[discover] max_variants`; the condition of each variant is in
14
+ the site's orm notes.
15
+ * `<foreach>` over a single bound value is the value list `(«collection»)`; any other body is rendered once.
16
+ * `<bind>` and `<selectKey>` are left out of the statement text.
17
+
18
+ The parsed mappers are also what `orm_mybatis` links the Java mapper calls to (`load`), and their result maps give
19
+ column lists for the tables the statements read (`tables`).
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import re
25
+ import xml.parsers.expat
26
+ from pathlib import Path
27
+
28
+ from .base import RawSite, is_test_path, read_text, trim
29
+
30
+ # ---- the tree ---------------------------------------------------------------------------------------------------
31
+
32
+
33
+ class El:
34
+ __slots__ = ("tag", "attrs", "children", "line", "end_line")
35
+
36
+ def __init__(self, tag: str, attrs: dict, line: int):
37
+ self.tag, self.attrs, self.line, self.end_line = tag, attrs, line, line
38
+ self.children: list = [] # El or str
39
+
40
+
41
+ def parse(text: str) -> El | None:
42
+ """The document as a tree with line numbers, or None when it is not well-formed XML."""
43
+ p = xml.parsers.expat.ParserCreate()
44
+ root = El("#doc", {}, 1)
45
+ stack = [root]
46
+
47
+ def start(tag, attrs):
48
+ el = El(tag, attrs, p.CurrentLineNumber)
49
+ stack[-1].children.append(el)
50
+ stack.append(el)
51
+
52
+ def end(tag):
53
+ el = stack.pop()
54
+ el.end_line = p.CurrentLineNumber
55
+
56
+ def chars(data):
57
+ kids = stack[-1].children
58
+ if kids and isinstance(kids[-1], str):
59
+ kids[-1] += data
60
+ else:
61
+ kids.append(data)
62
+
63
+ p.StartElementHandler, p.EndElementHandler, p.CharacterDataHandler = start, end, chars
64
+ p.UseForeignDTD(False)
65
+ try:
66
+ p.Parse(text, True)
67
+ except xml.parsers.expat.ExpatError:
68
+ return None
69
+ return root
70
+
71
+
72
+ def _find(el: El, tag: str) -> El | None:
73
+ for c in el.children:
74
+ if isinstance(c, El) and c.tag == tag:
75
+ return c
76
+ return None
77
+
78
+
79
+ # ---- mappers ----------------------------------------------------------------------------------------------------
80
+ STATEMENT_TAGS = ("select", "insert", "update", "delete")
81
+
82
+
83
+ class Stmt:
84
+ __slots__ = ("mapper", "id", "op", "el", "line", "end_line", "variants", "more", "dollar", "table", "model",
85
+ "database_id", "result_map")
86
+
87
+ def __init__(self, mapper: "Mapper", el: El):
88
+ self.mapper, self.el = mapper, el
89
+ self.id = el.attrs.get("id", "")
90
+ self.op = el.tag
91
+ self.line, self.end_line = el.line, el.end_line
92
+ self.variants: list[tuple[str, str]] = [] # (sql, condition)
93
+ self.more = 0 # alternatives past the cap
94
+ self.dollar = False
95
+ self.table = ""
96
+ typ = el.attrs.get("resultType") or el.attrs.get("parameterType") or ""
97
+ self.model = typ.rsplit(".", 1)[-1]
98
+ self.database_id = el.attrs.get("databaseId", "")
99
+ self.result_map = el.attrs.get("resultMap", "")
100
+
101
+
102
+ class Mapper:
103
+ def __init__(self, rel: str, namespace: str, root: El):
104
+ self.rel, self.namespace, self.root = rel, namespace, root
105
+ self.sql: dict[str, El] = {}
106
+ self.result_maps: dict[str, El] = {}
107
+ self.statements: list[Stmt] = []
108
+ self.by_id: dict[str, list[Stmt]] = {}
109
+
110
+
111
+ _CACHE: dict[tuple, dict[str, list[Mapper]]] = {}
112
+
113
+
114
+ def is_mapper_text(text: str) -> bool:
115
+ return "<mapper" in text and ("mybatis" in text or "ibatis" in text or re.search(r"<mapper\s+namespace\s*=", text) is not None)
116
+
117
+
118
+ def load(root: Path, files: list[str]) -> dict[str, list[Mapper]]:
119
+ """Every mapper of the repository by namespace (several files may share one), rendered. Cached per run."""
120
+ key = (str(root), len(files), files[0] if files else "", files[-1] if files else "")
121
+ got = _CACHE.get(key)
122
+ if got is not None:
123
+ return got
124
+ _CACHE.clear()
125
+ out: dict[str, list[Mapper]] = {}
126
+ for rel in files:
127
+ if not rel.endswith(".xml"):
128
+ continue
129
+ text = read_text(root / rel)
130
+ if text is None or not is_mapper_text(text):
131
+ continue
132
+ doc = parse(text)
133
+ mapper_el = _find(doc, "mapper") if doc is not None else None
134
+ if mapper_el is None:
135
+ continue
136
+ m = Mapper(rel, mapper_el.attrs.get("namespace", ""), mapper_el)
137
+ for c in mapper_el.children:
138
+ if not isinstance(c, El):
139
+ continue
140
+ if c.tag == "sql" and c.attrs.get("id"):
141
+ m.sql[c.attrs["id"]] = c
142
+ elif c.tag == "resultMap" and c.attrs.get("id"):
143
+ m.result_maps[c.attrs["id"]] = c
144
+ elif c.tag in STATEMENT_TAGS and c.attrs.get("id"):
145
+ s = Stmt(m, c)
146
+ m.statements.append(s)
147
+ m.by_id.setdefault(s.id, []).append(s)
148
+ out.setdefault(m.namespace, []).append(m)
149
+ for mappers in out.values():
150
+ for m in mappers:
151
+ for s in m.statements:
152
+ try:
153
+ render_statement(s, out)
154
+ except RecursionError:
155
+ s.variants = []
156
+ _CACHE[key] = out
157
+ return out
158
+
159
+
160
+ # ---- dynamic SQL ------------------------------------------------------------------------------------------------
161
+ BIND = re.compile(r"#\{\s*([^},]*?)\s*(?:,[^}]*)?\}")
162
+ PASTE = re.compile(r"\$\{\s*([^}]*?)\s*\}")
163
+ MAX_INCLUDE_DEPTH = 12
164
+ DECISIONS = ("if", "choose")
165
+
166
+
167
+ def _inline(el: El, mappers: dict, mapper: Mapper, props: dict, depth: int = 0) -> list:
168
+ """The children of `el` with every <include> replaced by its fragment (copied, so each use is its own node)."""
169
+ out: list = []
170
+ for c in el.children:
171
+ if isinstance(c, str):
172
+ out.append(_props(c, props))
173
+ continue
174
+ if c.tag == "include":
175
+ frag, owner = _fragment(c.attrs.get("refid", ""), mappers, mapper)
176
+ if frag is None or depth > MAX_INCLUDE_DEPTH:
177
+ out.append("«include " + c.attrs.get("refid", "") + "»")
178
+ continue
179
+ inner = dict(props)
180
+ for p in c.children:
181
+ if isinstance(p, El) and p.tag == "property":
182
+ inner[p.attrs.get("name", "")] = _props(p.attrs.get("value", ""), props)
183
+ out.extend(_inline(frag, mappers, owner, inner, depth + 1))
184
+ continue
185
+ if c.tag in ("bind", "selectKey"):
186
+ continue
187
+ copy = El(c.tag, {k: _props(v, props) for k, v in c.attrs.items()}, c.line)
188
+ copy.children = _inline(c, mappers, mapper, props, depth)
189
+ out.append(copy)
190
+ return out
191
+
192
+
193
+ def _props(text: str, props: dict) -> str:
194
+ if not props or "${" not in text:
195
+ return text
196
+ return PASTE.sub(lambda m: props.get(m.group(1), m.group(0)), text)
197
+
198
+
199
+ def _fragment(refid: str, mappers: dict, mapper: Mapper) -> tuple[El | None, Mapper]:
200
+ if refid in mapper.sql:
201
+ return mapper.sql[refid], mapper
202
+ for m in mappers.get(mapper.namespace, ()):
203
+ if refid in m.sql:
204
+ return m.sql[refid], m
205
+ ns, _, sid = refid.rpartition(".")
206
+ for m in mappers.get(ns, ()):
207
+ if sid in m.sql:
208
+ return m.sql[sid], m
209
+ return None, mapper
210
+
211
+
212
+ def _decisions(nodes: list, parents: tuple, out: list) -> None:
213
+ """Every <if> and <choose> in document order, with the decisions that enclose it: (node, parents)."""
214
+ for n in nodes:
215
+ if not isinstance(n, El):
216
+ continue
217
+ if n.tag == "if" and _always(n):
218
+ _decisions(n.children, parents, out)
219
+ elif n.tag == "if":
220
+ out.append((n, parents))
221
+ _decisions(n.children, parents + ((n, True),), out)
222
+ elif n.tag == "choose":
223
+ out.append((n, parents))
224
+ branches = [b for b in n.children if isinstance(b, El) and b.tag in ("when", "otherwise")]
225
+ for k, b in enumerate(branches):
226
+ _decisions(b.children, parents + ((n, k),), out)
227
+ else:
228
+ _decisions(n.children, parents, out)
229
+
230
+
231
+ def _always(n: El) -> bool:
232
+ """`<if test="_parameter != null">`: MyBatis passes the parameter object, so the condition holds whenever the
233
+ statement is called with one (MyBatis Generator wraps every Example clause in it)."""
234
+ return _ws(n.attrs.get("test", "")) in ("_parameter != null", "_parameter!=null")
235
+
236
+
237
+ def _ws(text: str) -> str:
238
+ return " ".join(text.split())
239
+
240
+
241
+ class _Render:
242
+ def __init__(self, choice: dict):
243
+ self.choice = choice # id(node) -> True for an <if>, branch index for a <choose>
244
+ self.dollar = False
245
+
246
+ def nodes(self, nodes: list, items: dict) -> str:
247
+ return " ".join(p for p in (self.node(n, items) for n in nodes) if p)
248
+
249
+ def node(self, n, items: dict) -> str:
250
+ if isinstance(n, str):
251
+ return self.text(n, items)
252
+ t = n.tag
253
+ if t == "if":
254
+ return self.nodes(n.children, items) if self.choice.get(id(n)) is True or _always(n) else ""
255
+ if t == "choose":
256
+ branches = [b for b in n.children if isinstance(b, El) and b.tag in ("when", "otherwise")]
257
+ pick = self.choice.get(id(n))
258
+ if pick is None:
259
+ pick = next((k for k, b in enumerate(branches) if b.tag == "otherwise"), None)
260
+ return self.nodes(branches[pick].children, items) if pick is not None and pick < len(branches) else ""
261
+ if t in ("where", "set", "trim"):
262
+ if t == "where":
263
+ prefix, suffix, pre_over, suf_over = "WHERE", "", "AND |OR |AND\n|OR\n", ""
264
+ elif t == "set":
265
+ prefix, suffix, pre_over, suf_over = "SET", "", "", ","
266
+ else:
267
+ a = n.attrs
268
+ prefix, suffix = a.get("prefix", ""), a.get("suffix", "")
269
+ pre_over, suf_over = a.get("prefixOverrides", ""), a.get("suffixOverrides", "")
270
+ body = _ws(self.nodes(n.children, items))
271
+ body = _strip_over(body, pre_over, suf_over)
272
+ if not body:
273
+ return ""
274
+ return " ".join(p for p in (prefix, body, suffix) if p)
275
+ if t == "foreach":
276
+ a = n.attrs
277
+ coll = a.get("collection", "list")
278
+ item = a.get("item", "item")
279
+ body = _ws(self.nodes(n.children, {**items, item: coll}))
280
+ if re.fullmatch(r"«[^»]*»", body) and (body[1:-1] == coll or body[1:-1].startswith(coll + ".")
281
+ or body[1:-1].startswith(coll + "[")):
282
+ body = "«" + coll + "»" # a list of single values: one value list, any length
283
+ return a.get("open", "") + body + a.get("close", "")
284
+ if t in ("when", "otherwise"):
285
+ return self.nodes(n.children, items)
286
+ return self.nodes(n.children, items)
287
+
288
+ def text(self, s: str, items: dict) -> str:
289
+ def bind(m: re.Match) -> str:
290
+ name = m.group(1).strip()
291
+ head, dot, rest = name.partition(".")
292
+ if head in items:
293
+ name = items[head] + dot + rest if dot else items[head]
294
+ return "«" + name.replace("»", ">") + "»"
295
+
296
+ def paste(m: re.Match) -> str:
297
+ self.dollar = True
298
+ return bind(m)
299
+ s = BIND.sub(bind, s)
300
+ s = PASTE.sub(paste, s)
301
+ return s
302
+
303
+
304
+ def _strip_over(body: str, pre: str, suf: str) -> str:
305
+ for o in [x for x in pre.split("|") if x.strip()]:
306
+ if body.upper().startswith(o.strip().upper() + " ") or body.upper() == o.strip().upper():
307
+ body = body[len(o.strip()):].lstrip()
308
+ break
309
+ for o in [x for x in suf.split("|") if x.strip()]:
310
+ if body.upper().endswith(o.strip().upper()):
311
+ body = body[: len(body) - len(o.strip())].rstrip()
312
+ break
313
+ return body
314
+
315
+
316
+ def _max_variants() -> int:
317
+ from .arms import max_variants
318
+ return max_variants()
319
+
320
+
321
+ def render_family(nodes: list) -> tuple[list[tuple[str, str]], int, bool]:
322
+ """(variants [(sql, condition)], alternatives left out past the cap, `${}` seen)."""
323
+ points: list = []
324
+ _decisions(nodes, (), points)
325
+ # Decisions on the same condition are one decision: an insertSelective's `<if test="name != null">` around the
326
+ # column and around its value go together.
327
+ same: dict[tuple, list[El]] = {}
328
+ for node, _ in points:
329
+ same.setdefault(_key(node), []).append(node)
330
+
331
+ def taking(node: El, value) -> dict:
332
+ return {id(n): value for n in same[_key(node)]}
333
+
334
+ plans: list[tuple[dict, str]] = [({}, "")]
335
+ every: dict = {}
336
+ for node, _ in points:
337
+ every.update(taking(node, True if node.tag == "if" else 0))
338
+ if points:
339
+ plans.append((every, "every optional part present"))
340
+ done: set = set()
341
+ for node, parents in points:
342
+ if (_key(node), node.tag) in done and node.tag == "if":
343
+ continue
344
+ base: dict = {}
345
+ for p, v in parents:
346
+ base.update(taking(p, v))
347
+ conds = [_cond(p, v) for p, v in parents]
348
+ if node.tag == "if":
349
+ done.add((_key(node), "if"))
350
+ plans.append(({**base, **taking(node, True)}, " and ".join(conds + [_cond(node, True)])))
351
+ else:
352
+ branches = [b for b in node.children if isinstance(b, El) and b.tag in ("when", "otherwise")]
353
+ for k, b in enumerate(branches):
354
+ if b.tag == "when":
355
+ plans.append(({**base, **taking(node, k)}, " and ".join(conds + [_cond(node, k)])))
356
+ out: list[tuple[str, str]] = []
357
+ seen: set[str] = set()
358
+ dollar = False
359
+ limit = max(1, _max_variants())
360
+ more = 0
361
+ for choice, cond in plans:
362
+ r = _Render(choice)
363
+ sql = _tidy(r.nodes(nodes, {}))
364
+ dollar = dollar or r.dollar
365
+ if not sql or sql in seen or not _complete(sql):
366
+ continue
367
+ seen.add(sql)
368
+ if len(out) >= limit:
369
+ more += 1
370
+ continue
371
+ out.append((sql, cond or "base: every optional part left out"))
372
+ return out, more, dollar
373
+
374
+
375
+ def _key(node: El) -> tuple:
376
+ if node.tag == "if":
377
+ return ("if", _ws(node.attrs.get("test", "")))
378
+ return ("choose",) + tuple(_ws(b.attrs.get("test", "")) for b in node.children if isinstance(b, El) and b.tag == "when")
379
+
380
+
381
+ def _cond(node: El, value) -> str:
382
+ if node.tag == "if":
383
+ return "if " + _ws(node.attrs.get("test", ""))
384
+ branches = [b for b in node.children if isinstance(b, El) and b.tag in ("when", "otherwise")]
385
+ b = branches[value] if isinstance(value, int) and value < len(branches) else None
386
+ if b is None or b.tag == "otherwise":
387
+ return "otherwise"
388
+ return "when " + _ws(b.attrs.get("test", ""))
389
+
390
+
391
+ def _tidy(sql: str) -> str:
392
+ sql = _ws(sql)
393
+ sql = re.sub(r"\(\s+", "(", sql)
394
+ sql = re.sub(r"\s+\)", ")", sql)
395
+ sql = re.sub(r"\s+,", ",", sql)
396
+ return sql.strip().rstrip(";").strip()
397
+
398
+
399
+ def _complete(sql: str) -> bool:
400
+ """A variant that MyBatis would send: an UPDATE needs its SET list, an INSERT its column list."""
401
+ if re.match(r"(?is)^update\s+\S+\s*(where\b|$)", sql):
402
+ return False
403
+ if re.search(r"(?i)\bvalues\s*$|\(\s*\)\s*values", sql):
404
+ return False
405
+ if re.match(r"(?is)^\s*insert\b", sql) and not re.search(r"(?i)\b(values|select|set|default)\b", sql):
406
+ return False
407
+ return True
408
+
409
+
410
+ TABLE_RX = {"select": re.compile(r"(?is)\bfrom\s+([`\"\w.]+)"), "insert": re.compile(r"(?is)\binto\s+([`\"\w.]+)"),
411
+ "update": re.compile(r"(?is)^\s*update\s+([`\"\w.]+)"), "delete": re.compile(r"(?is)\bfrom\s+([`\"\w.]+)")}
412
+
413
+
414
+ def render_statement(s: Stmt, mappers: dict) -> None:
415
+ nodes = _inline(s.el, mappers, s.mapper, {})
416
+ s.variants, s.more, s.dollar = render_family(nodes)
417
+ if s.variants:
418
+ m = TABLE_RX[s.op].search(s.variants[0][0])
419
+ if m:
420
+ s.table = m.group(1).strip("`\"")
421
+
422
+
423
+ def engine_of(database_id: str) -> str:
424
+ d = database_id.lower()
425
+ if d.startswith(("mysql", "mariadb")):
426
+ return "mysql"
427
+ if d.startswith(("pg", "postgres")):
428
+ return "postgres"
429
+ if d.startswith("sqlite"):
430
+ return "sqlite"
431
+ return ""
432
+
433
+
434
+ def mechanism(s: Stmt) -> str:
435
+ return "orm_raw_fragment" if s.dollar else "sqlfile_query"
436
+
437
+
438
+ def notes(s: Stmt, cond: str, n: int) -> list[str]:
439
+ out = []
440
+ if n > 1 or s.more:
441
+ out.append(f"variant: {trim(cond, 200)}")
442
+ if s.more:
443
+ out.append(f"{s.more} more variants past [discover] max_variants")
444
+ if s.dollar:
445
+ out.append("${...} pastes text into the statement at run time")
446
+ if s.database_id:
447
+ out.append(f"databaseId {s.database_id}")
448
+ return out
449
+
450
+
451
+ # ---- sites ------------------------------------------------------------------------------------------------------
452
+ STATS_LAST: dict = {}
453
+
454
+
455
+ def extract(root: Path, files: list[str], rules) -> list[RawSite]:
456
+ mappers = load(root, files)
457
+ out: list[RawSite] = []
458
+ seen = unrendered = 0
459
+ for group in mappers.values():
460
+ for m in group:
461
+ test = is_test_path(m.rel)
462
+ for s in m.statements:
463
+ seen += 1
464
+ if not s.variants:
465
+ unrendered += 1
466
+ continue
467
+ for sql, cond in s.variants:
468
+ orm = {"library": "mybatis", "model_or_table": s.table or s.model, "operation": s.op,
469
+ "confidence": "high" if len(s.variants) == 1 and not s.dollar else "medium",
470
+ "mechanism": mechanism(s)}
471
+ ns = notes(s, cond, len(s.variants))
472
+ if ns:
473
+ orm["notes"] = "; ".join(ns)
474
+ out.append(RawSite(
475
+ file=m.rel, line=s.line, end_line=s.end_line, language="xml", kind="call",
476
+ sink=trim(f"{m.namespace.rsplit('.', 1)[-1]}.{s.id}", 80), symbol=f"{m.namespace}.{s.id}",
477
+ sql=sql, resolution="orm", expr=trim(f"<{s.op} id=\"{s.id}\">"), in_loop=False,
478
+ engine_hint=engine_of(s.database_id), is_test=test, known_sink=True, orm=orm))
479
+ STATS_LAST.clear()
480
+ STATS_LAST.update({"statements": seen, "not_rendered": unrendered, "sites": len(out)})
481
+ return out
482
+
483
+
484
+ def summary_extras() -> dict:
485
+ if not STATS_LAST.get("statements"):
486
+ return {}
487
+ n, bad = STATS_LAST["statements"], STATS_LAST["not_rendered"]
488
+ reasons = {"statement renders to no complete SQL": bad} if bad else {}
489
+ return {"orm_coverage": {"mybatis-xml": {"calls": n, "translated": n - bad, "sites": STATS_LAST.get("sites", 0), "not_translated": bad,
490
+ "reasons": reasons}}}
491
+
492
+
493
+ # ---- tables from result maps ------------------------------------------------------------------------------------
494
+ JDBC_TYPES = {"BIGINT": "bigint", "INTEGER": "integer", "INT": "integer", "SMALLINT": "smallint", "TINYINT": "smallint",
495
+ "BIT": "boolean", "BOOLEAN": "boolean", "VARCHAR": "varchar", "CHAR": "char", "LONGVARCHAR": "text",
496
+ "CLOB": "text", "NVARCHAR": "varchar", "DECIMAL": "decimal", "NUMERIC": "numeric", "DOUBLE": "double precision",
497
+ "FLOAT": "real", "REAL": "real", "DATE": "date", "TIME": "time", "TIMESTAMP": "timestamp",
498
+ "BLOB": "bytea", "LONGVARBINARY": "bytea", "VARBINARY": "bytea", "BINARY": "bytea", "OTHER": ""}
499
+
500
+
501
+ def tables() -> list:
502
+ """A table per single-table SELECT that maps its rows with a result map: the map's columns with their JDBC types.
503
+ Real DDL in the repository is preferred by the schema merge when both exist."""
504
+ from .schema import Table
505
+ out: dict[str, Table] = {}
506
+ for group in _CACHE.get(next(iter(_CACHE), None), {}).values() if _CACHE else ():
507
+ for m in group:
508
+ if is_test_path(m.rel):
509
+ continue
510
+ for s in m.statements:
511
+ if s.op != "select" or not s.result_map or not s.table or not s.variants:
512
+ continue
513
+ sql = s.variants[0][0]
514
+ if re.search(r"(?i)\bjoin\b|\bfrom\s+[\w.`\"]+\s*(?:\w+\s*)?,", sql):
515
+ continue
516
+ rm = m.result_maps.get(s.result_map)
517
+ if rm is None:
518
+ continue
519
+ cols = []
520
+ for c in rm.children:
521
+ if isinstance(c, El) and c.tag in ("id", "result") and c.attrs.get("column"):
522
+ cols.append({"name": c.attrs["column"], "type": JDBC_TYPES.get(c.attrs.get("jdbcType", "").upper(), "")})
523
+ if not cols or s.table in out:
524
+ continue
525
+ out[s.table] = Table(name=s.table, columns=cols, defined_at=[f"{m.rel}:{rm.line}"])
526
+ return list(out.values())