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,503 @@
1
+ """TypeScript ORM and query-builder calls turned into SQL sites: the shared part.
2
+
3
+ The libraries live in their own modules (`orm_ts_prisma`, `orm_ts_kysely`, `orm_ts_drizzle`, `orm_ts_typeorm`);
4
+ this file holds what they share: the limits (settings), SQL text helpers, the resolution of an argument to an
5
+ object literal (through local variables, spreads and later `where.x = y` assignments), the per-library
6
+ coverage counts, and the driver `Scan` that `typescript.extract` calls.
7
+
8
+ A synthesised site is a RawSite with `resolution: "orm"` and an `orm` object
9
+ `{library, model_or_table, operation, confidence, notes?}`. The SQL names real tables and columns; anything
10
+ decided at run time is a «run-time part» written so that the statement still parses (always in the place of an
11
+ identifier or a value). When the table or the operation cannot be told, no SQL is written: the call is counted
12
+ with the reason.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ import re
19
+ from collections import Counter
20
+
21
+ from tree_sitter import Node
22
+
23
+ from .base import RawSite, trim
24
+
25
+ # ---- settings (`[discover]` in codecop.toml, applied by `configure`) ---------------------------------------------
26
+ DEFAULTS = {
27
+ "orm_marker_chars": 80, # longest source expression kept inside one «run-time part»
28
+ "orm_max_relation_depth": 12, # nesting of include / relations followed from one call
29
+ "orm_max_statements_per_call": 200, # statements one call may yield (eager loading: one per relation level)
30
+ "orm_max_object_depth": 6, # variables / spreads followed while resolving one argument object
31
+ "orm_max_chain_statements": 400, # later statements of a function read for `qb = qb.where(...)`
32
+ "orm_max_reasons": 12, # reasons listed per library for calls not translated
33
+ }
34
+ SETTINGS = dict(DEFAULTS)
35
+
36
+
37
+ def configure(settings: dict | None) -> None:
38
+ """Take the `orm_*` keys of `[discover]`; everything else keeps its default."""
39
+ SETTINGS.clear()
40
+ SETTINGS.update(DEFAULTS)
41
+ for key in DEFAULTS:
42
+ if settings and settings.get(key) is not None:
43
+ SETTINGS[key] = int(settings[key])
44
+
45
+
46
+ UNWRAP = ("parenthesized_expression", "as_expression", "satisfies_expression", "non_null_expression",
47
+ "await_expression", "type_assertion", "instantiation_expression")
48
+ CONDITIONAL_TYPES = ("if_statement", "ternary_expression", "switch_statement", "catch_clause", "for_statement",
49
+ "for_in_statement", "while_statement", "do_statement", "switch_case")
50
+ FUNC_TYPES = ("function_declaration", "generator_function_declaration", "function_expression", "function",
51
+ "generator_function", "arrow_function", "method_definition")
52
+ CONFIDENCE = ("low", "medium", "high")
53
+
54
+
55
+ def txt(node: Node | None) -> str:
56
+ return node.text.decode("utf-8", "replace") if node is not None else ""
57
+
58
+
59
+ def unwrap(node: Node | None) -> Node | None:
60
+ while node is not None and node.type in UNWRAP and node.named_children:
61
+ node = node.named_children[-1] if node.type == "type_assertion" else node.named_children[0]
62
+ return node
63
+
64
+
65
+ _SPACE_IN = re.compile(r"(?<=[(\[{])\s+|\s+(?=[)\]},;])|,\s*(?=[)\]}])")
66
+
67
+
68
+ def norm_expr(text: str) -> str:
69
+ """Source text with its formatting taken out: line breaks, indentation, padding inside brackets, trailing
70
+ commas. Two layouts of one expression give one text, so a site's fingerprint does not move with a formatter."""
71
+ text = " ".join(text.split())
72
+ return _SPACE_IN.sub("", text)
73
+
74
+
75
+ def mark(text: str) -> str:
76
+ """A «run-time part» holding the source expression."""
77
+ return "«" + trim(norm_expr(text), SETTINGS["orm_marker_chars"]).replace("»", ">").replace("«", "<") + "»"
78
+
79
+
80
+ def mark_node(node: Node | None) -> str:
81
+ return mark(txt(node))
82
+
83
+
84
+ def quote(engine: str, name: str) -> str:
85
+ if name.startswith("«"):
86
+ return name
87
+ if engine == "mysql":
88
+ return "`" + name.replace("`", "``") + "`"
89
+ return '"' + name.replace('"', '""') + '"'
90
+
91
+
92
+ def qname(engine: str, dotted: str) -> str:
93
+ """`schema.table` or `table.column` quoted part by part; `*` stays."""
94
+ return ".".join(p if p == "*" else quote(engine, p) for p in dotted.split(".") if p)
95
+
96
+
97
+ def string_value(node: Node | None) -> str | None:
98
+ """The text of a string literal or of a template literal with no substitution; None otherwise."""
99
+ node = unwrap(node)
100
+ if node is None:
101
+ return None
102
+ if node.type == "string":
103
+ from .typescript import decode_string
104
+ return decode_string(node)
105
+ if node.type == "template_string" and not any(c.type == "template_substitution" for c in node.children):
106
+ from .typescript import decode_string
107
+ return decode_string(node)
108
+ return None
109
+
110
+
111
+ def sql_string(text: str) -> str:
112
+ return "'" + text.replace("'", "''") + "'"
113
+
114
+
115
+ def literal(node: Node | None) -> str | None:
116
+ """A literal as SQL (`'a'`, `3`, `TRUE`, `NULL`), or None when the node is not a literal."""
117
+ node = unwrap(node)
118
+ if node is None:
119
+ return None
120
+ t = node.type
121
+ s = string_value(node)
122
+ if s is not None:
123
+ return sql_string(s)
124
+ if t == "number":
125
+ return txt(node).replace("_", "")
126
+ if t == "unary_expression" and txt(node)[:1] == "-" and node.named_children and node.named_children[0].type == "number":
127
+ return "-" + txt(node.named_children[0])
128
+ if t in ("true", "false"):
129
+ return t.upper()
130
+ if t == "null":
131
+ return "NULL"
132
+ return None
133
+
134
+
135
+ def value(node: Node | None) -> str:
136
+ """A value as SQL: the literal, or a «run-time part» with the expression."""
137
+ got = literal(node)
138
+ return got if got is not None else mark_node(unwrap(node) or node)
139
+
140
+
141
+ def is_undefined(node: Node | None) -> bool:
142
+ node = unwrap(node)
143
+ return node is not None and node.type in ("undefined", "identifier") and txt(node) == "undefined"
144
+
145
+
146
+ def in_list(node: Node | None) -> str:
147
+ """The inside of `IN (...)`: literal elements when the array is written out, else one run-time part."""
148
+ node = unwrap(node)
149
+ if node is not None and node.type == "array":
150
+ items = [c for c in node.named_children if c.type != "comment"]
151
+ if items and all(c.type != "spread_element" for c in items):
152
+ return ", ".join(value(c) for c in items)
153
+ if not items:
154
+ return "NULL"
155
+ return mark_node(node)
156
+
157
+
158
+ # ---- objects ------------------------------------------------------------------------------------------------
159
+
160
+ class Obj:
161
+ """An argument resolved to an object literal: its entries in source order and the parts only known at run
162
+ time (spreads that are not literals, computed keys, properties assigned later under a condition)."""
163
+
164
+ __slots__ = ("entries", "extra", "maybe", "f")
165
+
166
+ def __init__(self, f):
167
+ self.entries: list[tuple[str, Node]] = []
168
+ self.extra: list[str] = []
169
+ self.maybe: list[tuple[str, Node, str]] = [] # (key, value, source text) assigned later under a condition
170
+ self.f = f
171
+
172
+ def get(self, key: str) -> Node | None:
173
+ hit = None
174
+ for k, v in self.entries:
175
+ if k == key:
176
+ hit = v
177
+ return hit
178
+
179
+ def keys(self) -> list[str]:
180
+ return list(dict.fromkeys(k for k, _ in self.entries))
181
+
182
+
183
+ def _conditional_between(node: Node, stop: Node | None) -> bool:
184
+ """Is `node` inside an if / loop / ternary that does not also hold `stop`'s scope?"""
185
+ n = node.parent
186
+ while n is not None and n is not stop:
187
+ if n.type in CONDITIONAL_TYPES:
188
+ return True
189
+ if n.type in FUNC_TYPES or n.type == "program":
190
+ return False
191
+ n = n.parent
192
+ return False
193
+
194
+
195
+ def as_object(f, node: Node | None, at: Node | None, depth: int = 0) -> Obj | None:
196
+ """The object literal an expression stands for: a literal, or a `const` bound to one (with the properties
197
+ assigned to it before `at`). None when it is not an object literal that can be read here."""
198
+ node = unwrap(node)
199
+ if node is None or depth > SETTINGS["orm_max_object_depth"]:
200
+ return None
201
+ if node.type == "object":
202
+ out = Obj(f)
203
+ for c in node.named_children:
204
+ if c.type == "pair":
205
+ k, v = c.child_by_field_name("key"), c.child_by_field_name("value")
206
+ if k is None or v is None:
207
+ continue
208
+ if k.type == "computed_property_name":
209
+ out.extra.append(txt(c))
210
+ else:
211
+ key = string_value(k)
212
+ out.entries.append((key if key is not None else txt(k), v))
213
+ elif c.type == "shorthand_property_identifier":
214
+ out.entries.append((txt(c), c))
215
+ elif c.type == "spread_element":
216
+ inner = unwrap(c.named_children[0]) if c.named_children else None
217
+ sub = as_object(f, inner, at, depth + 1) if inner is not None and inner.type in ("object", "identifier") else None
218
+ if sub is not None:
219
+ out.entries.extend(sub.entries)
220
+ out.extra.extend(sub.extra)
221
+ out.maybe.extend(sub.maybe)
222
+ else:
223
+ out.extra.append("..." + txt(inner))
224
+ elif c.type == "method_definition":
225
+ out.extra.append(txt(c.child_by_field_name("name")) + "()")
226
+ return out
227
+ if node.type in ("identifier", "shorthand_property_identifier"):
228
+ name = txt(node)
229
+ anchor = at or node
230
+ try:
231
+ decl = f._decl(name, anchor)
232
+ except Exception:
233
+ decl = None
234
+ if decl is None:
235
+ return None
236
+ first, _later, branched = decl
237
+ if branched or first.type != "variable_declarator":
238
+ return None
239
+ val = unwrap(first.child_by_field_name("value"))
240
+ if val is None or val.type != "object" or val.start_byte <= node.start_byte <= val.end_byte:
241
+ return None
242
+ out = as_object(f, val, first, depth + 1)
243
+ if out is None:
244
+ return None
245
+ # `where.status = status` between the declaration and the call
246
+ scope = first.parent
247
+ while scope is not None and scope.type not in FUNC_TYPES and scope.type != "program":
248
+ scope = scope.parent
249
+ if scope is not None and anchor.start_byte > first.end_byte:
250
+ budget = SETTINGS["orm_max_chain_statements"] * 50
251
+ stack = [scope]
252
+ while stack and budget > 0:
253
+ n = stack.pop()
254
+ budget -= 1
255
+ if n.end_byte < first.end_byte or n.start_byte > anchor.start_byte:
256
+ continue
257
+ if n.type in ("assignment_expression", "augmented_assignment_expression"):
258
+ left = n.child_by_field_name("left")
259
+ if left is not None and left.type in ("member_expression", "subscript_expression") and \
260
+ txt(left.child_by_field_name("object")) == name and n.start_byte > first.end_byte:
261
+ prop = left.child_by_field_name("property")
262
+ right = n.child_by_field_name("right")
263
+ if left.type == "member_expression" and prop is not None and right is not None \
264
+ and n.type == "assignment_expression":
265
+ if _conditional_between(n, scope):
266
+ out.maybe.append((txt(prop), right, txt(n)))
267
+ else:
268
+ out.entries.append((txt(prop), right))
269
+ else:
270
+ out.extra.append(txt(n))
271
+ continue
272
+ if n is not scope and n.type in FUNC_TYPES:
273
+ continue
274
+ stack.extend(reversed(n.children))
275
+ return out
276
+ return None
277
+
278
+
279
+ def array_items(node: Node | None) -> list[Node] | None:
280
+ """The elements of an array literal, or None when the node is not one (or holds a spread)."""
281
+ node = unwrap(node)
282
+ if node is None or node.type != "array":
283
+ return None
284
+ items = [c for c in node.named_children if c.type != "comment"]
285
+ if any(c.type == "spread_element" for c in items):
286
+ return None
287
+ return items
288
+
289
+
290
+ def typed_template(f, node: Node) -> tuple[str, str] | None:
291
+ """sql<T>`...` (which the grammar reads as `sql < T > template`): (resolved text, alias of a trailing .as())."""
292
+ text = txt(node)
293
+ if not re.match(r"^\(?\s*sql\s*<", text):
294
+ return None
295
+ stack = [node]
296
+ tpl = None
297
+ while stack:
298
+ n = stack.pop()
299
+ if n.type == "template_string":
300
+ tpl = n
301
+ break
302
+ stack.extend(reversed(n.children))
303
+ if tpl is None:
304
+ return None
305
+ try:
306
+ res = f._template(tpl, tpl, 0, tagged=True)
307
+ except Exception:
308
+ return None
309
+ if res is None or not res.text.strip():
310
+ return None
311
+ m = re.search(r"`\s*\)?\s*\.as\(\s*['\"]([\w$]+)['\"]\s*\)\s*$", text)
312
+ return res.text.strip(), (m.group(1) if m else "")
313
+
314
+
315
+ def list_items(f, node: Node | None, at: Node) -> tuple[list[Node], list[Node]] | None:
316
+ """A list held in a name: (its elements with the unconditional `.push(...)` after it, the conditional pushes).
317
+ None when the name is not bound to an array literal here."""
318
+ node = unwrap(node)
319
+ if node is None or node.type != "identifier":
320
+ return None
321
+ name = txt(node)
322
+ try:
323
+ decl = f._decl(name, at)
324
+ except Exception:
325
+ decl = None
326
+ if decl is None or decl[2] or decl[0].type != "variable_declarator":
327
+ return None
328
+ value = unwrap(decl[0].child_by_field_name("value"))
329
+ if value is None or value.type != "array" or any(c.type == "spread_element" for c in value.named_children):
330
+ return None
331
+ sure = [c for c in value.named_children if c.type != "comment"]
332
+ maybe: list[Node] = []
333
+ scope = decl[0].parent
334
+ while scope is not None and scope.type not in FUNC_TYPES and scope.type != "program":
335
+ scope = scope.parent
336
+ if scope is None:
337
+ return sure, maybe
338
+ budget = SETTINGS["orm_max_chain_statements"] * 50
339
+ stack = [scope]
340
+ while stack and budget > 0:
341
+ n = stack.pop()
342
+ budget -= 1
343
+ if n.end_byte < decl[0].end_byte or n.start_byte > at.start_byte:
344
+ continue
345
+ if n.type == "call_expression" and n.start_byte > decl[0].end_byte:
346
+ fn = unwrap(n.child_by_field_name("function"))
347
+ if fn is not None and fn.type == "member_expression" and txt(fn.child_by_field_name("object")) == name \
348
+ and txt(fn.child_by_field_name("property")) == "push":
349
+ args = n.child_by_field_name("arguments")
350
+ items = [a for a in args.named_children if a.type != "comment"] if args is not None else []
351
+ (maybe if _conditional_between(n, scope) else sure).extend(items)
352
+ continue
353
+ if n is not scope and n.type in FUNC_TYPES:
354
+ continue
355
+ stack.extend(reversed(n.children))
356
+ return sure, maybe
357
+
358
+
359
+ def callback_body(node: Node | None) -> Node | None:
360
+ """The expression an arrow function returns: `(x) => expr`, `(x) => { return expr }`, `(x) => (expr)`."""
361
+ node = unwrap(node)
362
+ if node is None or node.type not in ("arrow_function", "function_expression", "function"):
363
+ return None
364
+ body = node.child_by_field_name("body")
365
+ if body is None:
366
+ return None
367
+ if body.type != "statement_block":
368
+ return unwrap(body)
369
+ returns = [c for c in body.named_children if c.type == "return_statement"]
370
+ if len(returns) == 1 and returns[0].named_children:
371
+ return unwrap(returns[0].named_children[0])
372
+ return None
373
+
374
+
375
+ # ---- coverage -----------------------------------------------------------------------------------------------
376
+
377
+ class Stats:
378
+ """Per library: calls seen, calls translated, sites written, and why the others were not translated."""
379
+
380
+ def __init__(self):
381
+ self.seen: Counter[str] = Counter()
382
+ self.done: Counter[str] = Counter()
383
+ self.sites: Counter[str] = Counter()
384
+ self.reasons: dict[str, Counter[str]] = {}
385
+ self.missed: list[dict] = [] # every call not translated: library, file, line, reason
386
+
387
+ def see(self, lib: str, test: bool) -> None:
388
+ self.seen[(lib, test)] += 1
389
+
390
+ def ok(self, lib: str, test: bool, sites: int) -> None:
391
+ self.done[(lib, test)] += 1
392
+ self.sites[(lib, test)] += sites
393
+
394
+ def miss(self, lib: str, test: bool, reason: str, rel: str = "", line: int = 0) -> None:
395
+ self.reasons.setdefault((lib, test), Counter())[reason] += 1
396
+ self.missed.append({"library": lib, "file": rel, "line": line, "reason": reason, "is_test": test})
397
+
398
+ def summary(self) -> dict:
399
+ out: dict = {}
400
+ for (lib, test), n in sorted(self.seen.items()):
401
+ key = "in_tests" if test else "app"
402
+ row = out.setdefault(lib, {})
403
+ done = self.done.get((lib, test), 0)
404
+ row[key] = {
405
+ "calls_seen": n, "calls_translated": done, "sites": self.sites.get((lib, test), 0),
406
+ "calls_not_translated": n - done,
407
+ "share_translated": round(done / n, 3) if n else 0.0,
408
+ "not_translated_reasons": dict(self.reasons.get((lib, test), Counter()).most_common(SETTINGS["orm_max_reasons"])),
409
+ "examples": {r: next((f"{m['file']}:{m['line']}" for m in self.missed
410
+ if m["library"] == lib and m["is_test"] == test and m["reason"] == r), "")
411
+ for r in self.reasons.get((lib, test), ())},
412
+ }
413
+ return out
414
+
415
+
416
+ def engine_of(f) -> str:
417
+ """The engine of a file that talks to a relational store through an ORM or a builder: its own imports, else the
418
+ one relational driver its package depends on."""
419
+ return f.file_engine() or f.ctx.package_engine(f.rel, relational=True)
420
+
421
+
422
+ def engine_of_builder(f) -> str:
423
+ """The engine of a file that uses a builder which speaks any dialect (Kysely is also used to write ClickHouse
424
+ SQL): the one engine its imports name, else the one engine its package depends on, else unknown, which
425
+ leaves the statement to the usual evidence (receiver, tables, project default)."""
426
+ named = getattr(f, "_import_engines", set())
427
+ if len(named) == 1:
428
+ return next(iter(named))
429
+ return "" if named else f.ctx.package_engine(f.rel, relational=False)
430
+
431
+
432
+ def make_site(f, node: Node, sink: str, engine: str, sql: str, expr: Node | None, *, library: str, table: str,
433
+ operation: str, confidence: str = "high", notes: list[str] | None = None) -> RawSite:
434
+ orm = {"library": library, "model_or_table": table, "operation": operation, "confidence": confidence}
435
+ if notes:
436
+ orm["notes"] = "; ".join(dict.fromkeys(notes))
437
+ return RawSite(
438
+ file=f.rel, line=node.start_point[0] + 1, end_line=node.end_point[0] + 1, language="typescript", kind="call",
439
+ sink=trim(re.sub(r"\s+", "", sink), 80), symbol=f.symbol(node), sql=sql, resolution="orm",
440
+ expr=trim(norm_expr(txt(expr))) if expr is not None else "", in_loop=f.in_loop(node),
441
+ engine_hint=engine, is_test=f.test, known_sink=True, orm=orm,
442
+ )
443
+
444
+
445
+ LAST_MISSED: list[dict] = [] # the calls of the last run that were not translated (for measuring recall)
446
+
447
+
448
+ # ---- driver -------------------------------------------------------------------------------------------------
449
+
450
+ class Scan:
451
+ """What `typescript.extract` drives: `offer` every source file it reads, then `sites()` and `summary()`."""
452
+
453
+ def __init__(self, ctx, root, files):
454
+ import importlib
455
+ self.ctx, self.root = ctx, root
456
+ self.stats = Stats()
457
+ self.wanted: dict[str, set[str]] = {}
458
+ self.libs = []
459
+ self.errors = 0
460
+ for name in ("prisma", "kysely", "drizzle", "typeorm", "sequelize", "knex"):
461
+ try:
462
+ mod = importlib.import_module(f"{__package__}.orm_ts_{name}")
463
+ lib = mod.Library(ctx, root, files, self.stats)
464
+ except ModuleNotFoundError:
465
+ continue
466
+ except Exception: # one odd schema must not stop the inventory
467
+ if os.environ.get("CODECOP_ORM_DEBUG"):
468
+ raise
469
+ self.errors += 1
470
+ continue
471
+ if lib.active:
472
+ self.libs.append(lib)
473
+
474
+ def offer(self, rel: str, src: bytes, deps: frozenset[str]) -> None:
475
+ for lib in self.libs:
476
+ if lib.wants(rel, src, deps):
477
+ self.wanted.setdefault(rel, set()).add(lib.name)
478
+
479
+ def sites(self) -> list[RawSite]:
480
+ out: list[RawSite] = []
481
+ for lib in self.libs:
482
+ try:
483
+ lib.prepare(self.wanted)
484
+ except Exception:
485
+ self.errors += 1
486
+ for rel in sorted(self.wanted):
487
+ f = self.ctx.file(rel)
488
+ if f is None:
489
+ continue
490
+ for lib in self.libs:
491
+ if lib.name not in self.wanted[rel]:
492
+ continue
493
+ try:
494
+ out.extend(lib.sites(f))
495
+ except Exception: # one odd file must not stop the inventory
496
+ if os.environ.get("CODECOP_ORM_DEBUG"):
497
+ raise
498
+ self.errors += 1
499
+ return out
500
+
501
+ def summary(self) -> dict:
502
+ LAST_MISSED[:] = self.stats.missed
503
+ return {"orm": self.stats.summary(), "orm_errors": self.errors}