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,636 @@
1
+ """The pass that finds ORM and builder statements in the parsed Go files of one run: where a library call
2
+ executes, wrappers and their callers, row-loading calls inside loops, the model tables, and the counts that
3
+ go into the inventory summary. The translation itself is in orm_go.py."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ from collections import defaultdict
9
+ from dataclasses import dataclass, field
10
+
11
+ from tree_sitter import Node, Query, QueryCursor
12
+
13
+ from .base import RawSite, trim
14
+ from .go import FUNC_DECL, LANG, GoFile, _strip_parens, _txt, call_args, callee_name, param_names, param_type
15
+ from . import orm_ent
16
+ from . import orm_go as O
17
+ from . import orm_go_types as T
18
+ from .orm_go import (ALL_TERMINALS, ASSOC_TERMINALS, DEFER_CLOSE, DEFER_OPEN, EMPTY, ENT_BUILD, ENT_TERMINALS, EXECUTOR,
19
+ RAW_TERMINALS, TERMINALS, TOK, TOKEN, TRANSLATED, Cond, Ev, OrmSite, Q, Stmt, Template, Unresolved,
20
+ chain_of, marker, render)
21
+ from .orm_go_types import Model, TypeRef, Types
22
+
23
+
24
+ FOR_LOOPS = Query(LANG, "(for_statement) @f")
25
+
26
+
27
+ def _fill(text: str, fills: dict[str, str]) -> str:
28
+ """Put a caller's conditions where a wrapper's condition parameters stood; an empty one leaves no trace."""
29
+ if TOK not in text:
30
+ return text
31
+ out = TOKEN.sub(lambda m: fills.get(m.group(0), m.group(0)) or EMPTY, text)
32
+ if EMPTY in out:
33
+ hole = rf"\(*{DEFER_OPEN}?{EMPTY}{DEFER_CLOSE}?\)*"
34
+ out = re.sub(rf"\s+AND\s+{hole}", "", out)
35
+ out = re.sub(rf"{hole}\s+AND\s+", "", out)
36
+ out = re.sub(hole, "", out)
37
+ return out
38
+
39
+
40
+ def finalize(sql: str) -> str:
41
+ """Wrapper tokens nobody filled become run-time parts; deferred conditional predicates become markers."""
42
+ sql = TOKEN.sub(lambda m: marker(m.group(2) if m.group(1) == "P" else m.group(2) + "()"), sql)
43
+ sql = re.sub(rf"{DEFER_OPEN}([^{DEFER_CLOSE}]*){DEFER_CLOSE}", lambda m: marker(m.group(1)), sql)
44
+ sql = sql.replace(EMPTY, "")
45
+ sql = re.sub(r"\s+WHERE\s*(?=$|GROUP BY|ORDER BY|LIMIT)", " ", sql)
46
+ return sql.strip()
47
+
48
+
49
+ class Run(Ev):
50
+ """One pass over the parsed Go files of a repository."""
51
+
52
+ def __init__(self, ctx, types: Types):
53
+ super().__init__(ctx, types)
54
+ self.site_calls: set[tuple[str, int]] = set()
55
+ self._calls_by_func: dict[str, dict[int, list[Node]]] = {}
56
+ self._reach_memo: dict[int, list[tuple[OrmSite, int]]] = {}
57
+ self._done: set[tuple[str, int, int]] = set()
58
+ self._loop_bodies: dict[str, list[tuple[int, int, Node]]] = {}
59
+ self.wrappers_found = 0
60
+ self.ent_schema: orm_ent.Schema | None = None # read once, on the first ent call
61
+
62
+ # ---- a statement of the library, found ------------------------------------------------------
63
+ def body_loop(self, gf: GoFile, node: Node) -> Node | None:
64
+ """The innermost `for` whose body (not its header) holds the node. Function declarations do not nest,
65
+ so a loop body that holds the node is in the node's own function (a closure in a loop counts)."""
66
+ bodies = self._loop_bodies.get(gf.rel)
67
+ if bodies is None:
68
+ bodies = []
69
+ if b"for " in gf.src:
70
+ for loop in QueryCursor(FOR_LOOPS).captures(gf.root).get("f", []):
71
+ body = loop.child_by_field_name("body")
72
+ if body is not None:
73
+ bodies.append((body.start_byte, body.end_byte, loop))
74
+ bodies.sort(key=lambda b: b[0])
75
+ self._loop_bodies[gf.rel] = bodies
76
+ best = None
77
+ pos = node.start_byte
78
+ for start, end, loop in bodies:
79
+ if start > pos:
80
+ break
81
+ if pos < end and node.end_byte <= end:
82
+ best = loop
83
+ return best
84
+
85
+ @staticmethod
86
+ def sink_text(call: Node, name: str) -> str:
87
+ root, ops = chain_of(call)
88
+ if not ops:
89
+ return trim(_txt(call.child_by_field_name("function") or call), 80)
90
+ head = ""
91
+ if root is not None:
92
+ head = _txt(root.child_by_field_name("function") or root) if root.type == "call_expression" else _txt(root)
93
+ head = trim(head.split("(")[0], 48)
94
+ return f"{head}.{name}" if head else name
95
+
96
+ def visit(self, gf: GoFile, call: Node) -> None:
97
+ fn = call.child_by_field_name("function")
98
+ name, recv, _dotted = callee_name(fn)
99
+ if not name or recv is None:
100
+ return
101
+ args = call_args(call)
102
+ if name in ALL_TERMINALS or name in ASSOC_TERMINALS:
103
+ base = self.eval(gf, recv, call, None)
104
+ if isinstance(base, Q):
105
+ lib = base.lib
106
+ if name in TERMINALS.get(lib, ()) or (base.assoc and name in ASSOC_TERMINALS):
107
+ if lib in ("squirrel", "bun", "goqu") and self._inner_terminal(call, lib):
108
+ return
109
+ self.finish(base, name, args, call, gf)
110
+ return
111
+ if name in RAW_TERMINALS.get(lib, ()):
112
+ if not gf.test:
113
+ self.stats.raw[lib] += 1 # the SQL is a string: the Go extractor reports it
114
+ return
115
+ if EXECUTOR.search(name):
116
+ for a in args:
117
+ a = _strip_parens(a)
118
+ if a is None or a.type not in ("identifier", "call_expression", "selector_expression"):
119
+ continue
120
+ v = self.eval(gf, a, call, None)
121
+ if isinstance(v, Q) and v.lib in ("squirrel", "sqlbuilder", "xbuilder", "goqu") and "factory" not in v.flags:
122
+ self.finish(v, name, args, call, gf)
123
+ return
124
+ if "ent" in self.types.libs and (name in ENT_TERMINALS or name in orm_ent.TERMINALS or name in orm_ent.GETS):
125
+ root, ops = chain_of(call)
126
+ built = any(op in ENT_BUILD for op, _a, _c in ops[:-1])
127
+ if not any("ent" in p.split("/") for p in gf.imports.values()) or orm_ent.GENERATED.encode() in gf.src[:400]:
128
+ return # ent's own generated code runs these chains for the application: not its statements
129
+ if self.ent_schema is None:
130
+ self.ent_schema = orm_ent.Schema(self.ctx)
131
+ if name in orm_ent.GETS and not built:
132
+ # client.Scan.Get(ctx, id): a read by id; counted only when the receiver is an entity's client
133
+ if root is None or root.type != "selector_expression" or _txt(root.child_by_field_name("field")) not in self.ent_schema.by_name:
134
+ return
135
+ elif not built and not (root is not None and root.type == "identifier"
136
+ and (name in orm_ent.TERMINALS or name in orm_ent.WRITE_TERMINALS)):
137
+ return
138
+ if not built and name not in orm_ent.GETS and orm_ent._builder_ops(gf, root, call, self.ent_schema) is None:
139
+ return # a terminal on a value that is not an ent builder
140
+ if not self.ent_schema:
141
+ self.count("ent", gf, call, "no generated ent package found")
142
+ return
143
+ try:
144
+ got = orm_ent.translate(self.ent_schema, gf, call, root, ops)
145
+ except orm_ent.Untranslated as e:
146
+ self.count("ent", gf, call, str(e))
147
+ return
148
+ (self.stats.seen_tests if gf.test else self.stats.seen)["ent"] += 1
149
+ stmts = [Stmt(sql, op, target, "medium" if any("run-time part" in n for n in notes) else "high", notes, self.ent_schema.dialect)
150
+ for sql, op, target, notes in got]
151
+ self.emit(gf, call, stmts, "ent", self.sink_text(call, name))
152
+
153
+ @staticmethod
154
+ def _inner_terminal(call: Node, lib: str) -> bool:
155
+ """`q.QueryRow().Scan(&x)`: the inner call is reported with the outer one."""
156
+ p = call.parent
157
+ if p is None or p.type != "selector_expression" or p.parent is None or p.parent.type != "call_expression":
158
+ return False
159
+ fld = p.child_by_field_name("field")
160
+ return fld is not None and _txt(fld) in TERMINALS.get(lib, ())
161
+
162
+ def count(self, lib: str, gf: GoFile, call: Node, reason: str) -> None:
163
+ (self.stats.seen_tests if gf.test else self.stats.seen)[lib] += 1
164
+ if not gf.test:
165
+ reason, _, detail = reason.partition(" | ")
166
+ self.stats.reasons[lib][reason] += 1
167
+ self.stats.untranslated.append((lib, gf.rel, call.start_point[0] + 1, reason, detail))
168
+
169
+ def finish(self, q: Q, name: str, args: list[Node], call: Node, gf: GoFile) -> None:
170
+ lib = q.lib
171
+ if lib not in TRANSLATED:
172
+ self.count(lib, gf, call, "library not translated")
173
+ return
174
+ try:
175
+ stmts = self.statements(q, name, args, call, gf)
176
+ except Unresolved as e:
177
+ if str(e) == "wrapper":
178
+ func = gf._enclosing(call, FUNC_DECL)
179
+ if func is not None:
180
+ self.add_template(Template(gf, func, q, name, args, call, lib))
181
+ self.site_calls.add((gf.rel, call.start_byte))
182
+ return
183
+ e = Unresolved("the model is a parameter of an anonymous function")
184
+ self.count(lib, gf, call, str(e))
185
+ return
186
+ (self.stats.seen_tests if gf.test else self.stats.seen)[lib] += 1
187
+ before = len(self.sites)
188
+ self.emit(gf, call, stmts, lib, self.sink_text(call, name))
189
+ if name in ("ToSql", "MustSql", "Build", "BuildWithFlavor", "ToSQL", "ToBoundSQL"):
190
+ p = call.parent
191
+ if p is not None and p.type == "expression_list" and p.parent is not None \
192
+ and p.parent.type in ("short_var_declaration", "assignment_statement"):
193
+ left = p.parent.child_by_field_name("left")
194
+ if left is not None and left.named_children and left.named_children[0].type == "identifier":
195
+ self.replaced.add((gf.rel, gf.symbol(call), _txt(left.named_children[0])))
196
+ if len(self.sites) > before: # the site that now stands for the call the variable goes to
197
+ self.replaced_by.setdefault((gf.rel, gf.symbol(call), _txt(left.named_children[0])), self.sites[before])
198
+
199
+ def emit(self, gf: GoFile, call: Node, stmts: list[Stmt], lib: str, sink: str, notes: list[str] | None = None,
200
+ in_loop: bool | None = None, loop_copy: bool = False) -> None:
201
+ func = gf._enclosing(call, FUNC_DECL)
202
+ loop = self.body_loop(gf, call) is not None if in_loop is None else in_loop
203
+ wrote = False
204
+ for st in stmts:
205
+ sql = finalize(st.sql)
206
+ if not sql:
207
+ continue
208
+ wrote = True
209
+ orm = {"library": lib, "model_or_table": st.target, "operation": st.operation, "confidence": st.confidence}
210
+ all_notes = (notes or []) + st.notes
211
+ if all_notes:
212
+ orm["notes"] = "; ".join(dict.fromkeys(all_notes))
213
+ if lib == "bun":
214
+ orm["mechanism"] = "query_builder"
215
+ elif lib == "ent":
216
+ orm["mechanism"] = "orm_api_in_loop" if loop else "orm_api"
217
+ site = OrmSite(
218
+ file=gf.rel, line=call.start_point[0] + 1, end_line=call.end_point[0] + 1, language="go", kind="call",
219
+ sink=sink, symbol=gf.symbol(call), sql=sql, resolution="orm", expr=trim(_txt(call)), in_loop=loop,
220
+ engine_hint=st.engine or gf.file_engine(), is_test=gf.test, known_sink=True, orm=orm)
221
+ self.sites.append(site)
222
+ if not gf.test:
223
+ self.stats.statements[lib] += 1
224
+ if func is not None and not loop_copy:
225
+ self.by_func[(gf.rel, func.id)].append(site)
226
+ if wrote and not gf.test and not loop_copy:
227
+ self.stats.emitted[lib] += 1
228
+ self.site_calls.add((gf.rel, call.start_byte))
229
+
230
+ # ---- wrappers ----------------------------------------------------------------------------
231
+ def add_template(self, t: Template) -> None:
232
+ nm = t.func.child_by_field_name("name")
233
+ if nm is None:
234
+ return
235
+ self.templates[(t.gf.rel, t.func.id)].append(t)
236
+ self.template_names.add(_txt(nm))
237
+ self.wrappers_found += 1
238
+
239
+ def instantiate(self) -> None:
240
+ for _ in range(max(O.WRAPPER_ROUNDS, 1)):
241
+ before = self.wrappers_found
242
+ names = set(self.template_names)
243
+ for gf in self.files():
244
+ for call in gf.calls:
245
+ name = callee_name(call.child_by_field_name("function"))[0]
246
+ if name not in names:
247
+ continue
248
+ try:
249
+ hit = self.types.callee(gf, call)
250
+ if hit is None:
251
+ continue
252
+ for t in list(self.templates.get((hit[0].rel, hit[1].id), ())):
253
+ key = (gf.rel, call.start_byte, id(t))
254
+ if key in self._done:
255
+ continue
256
+ self._done.add(key)
257
+ self._instantiate(gf, call, t)
258
+ except Exception: # one odd call must not stop the inventory
259
+ self.stats.errors += 1
260
+ if self.wrappers_found == before:
261
+ break
262
+
263
+ def _bind(self, gf: GoFile, call: Node, func: Node) -> dict:
264
+ bind: dict = {}
265
+ tps = self.types.type_params(func)
266
+ for p, g in zip(tps, T.call_type_args(call)):
267
+ bind[("typeparam", p)] = [TypeRef(g, gf)]
268
+ names = param_names(func)
269
+ params = func.child_by_field_name("parameters")
270
+ variadic = bool(params is not None and params.named_children
271
+ and params.named_children[-1].type == "variadic_parameter_declaration")
272
+ args = call_args(call)
273
+ for i, pname in enumerate(names):
274
+ if not pname:
275
+ continue
276
+ vals = args[i:] if variadic and i == len(names) - 1 else args[i:i + 1]
277
+ bind[("param", pname)] = [(gf, a, call) for a in vals]
278
+ ptype = param_type(func, pname)
279
+ for p in tps: # a type parameter the arguments decide: `func Load[T any](bean *T)`
280
+ if ("typeparam", p) not in bind and vals and re.search(rf"\b{re.escape(p)}\b", ptype):
281
+ ref = self.types.type_of(gf, vals[0], call)
282
+ arg = _strip_parens(vals[0])
283
+ if ref is None and arg is not None and arg.type == "func_literal" and ptype.startswith("func("):
284
+ # `db.Iterate(ctx, cond, func(ctx context.Context, row *Spec) error {...})`: the callback's parameter
285
+ want = T.type_args("[" + ptype[5: ptype.rfind(")")] + "]") if ptype.count("(") == 1 else []
286
+ params = arg.child_by_field_name("parameters")
287
+ given = []
288
+ for q in (params.named_children if params is not None else ()):
289
+ typ = q.child_by_field_name("type")
290
+ given.extend([_txt(typ) if typ is not None else ""] * max(1, len(q.children_by_field_name("name"))))
291
+ for w, g in zip(want, given):
292
+ if re.search(rf"\b{re.escape(p)}\b", w) and g:
293
+ ref = TypeRef(g, gf)
294
+ break
295
+ if ref is not None:
296
+ bind[("typeparam", p)] = [TypeRef(T.base_type(ref.text)[0], ref.gf)]
297
+ return bind
298
+
299
+ def _open_tokens(self, gf: GoFile, call: Node, bind: dict, lib: str) -> bool:
300
+ """True when what this caller passes is itself a parameter of the caller: a wrapper of the wrapper."""
301
+ func = gf._enclosing(call, FUNC_DECL)
302
+ if func is None:
303
+ return False
304
+ tps = set(self.types.type_params(func))
305
+ for values in bind.values():
306
+ for b in values:
307
+ if isinstance(b, TypeRef):
308
+ if T.base_type(b.text)[0] in tps:
309
+ return True
310
+ elif self.model_token(b[0], b[1], b[2]) is not None and self.types.model(self.types.type_of(b[0], b[1], b[2]), lib) is None:
311
+ return True
312
+ return False
313
+
314
+ def _fills(self, gf: GoFile, call: Node, t: Template, bind: dict) -> dict[str, str]:
315
+ fills: dict[str, str] = {}
316
+ for m in TOKEN.finditer(t.q.all_text()):
317
+ if m.group(0) in fills:
318
+ continue
319
+ kind, body = m.group(1), m.group(2)
320
+ pname, _, method = body.partition(".")
321
+ vals = bind.get(("param", pname)) or []
322
+ if not vals:
323
+ continue
324
+ _g, arg, _a = vals[0]
325
+ a = _strip_parens(arg)
326
+ if a is not None and a.type == "nil":
327
+ fills[m.group(0)] = ""
328
+ continue
329
+ if kind == "P":
330
+ v = self.eval(gf, arg, call, None)
331
+ if isinstance(v, Cond):
332
+ fills[m.group(0)] = v.text
333
+ elif isinstance(v, Q) and render(v):
334
+ fills[m.group(0)] = f"({render(v)})"
335
+ else:
336
+ fills[m.group(0)] = self.text(gf, arg, call)
337
+ continue
338
+ hit = self.types.method(self.types.type_of(gf, arg, call), method)
339
+ v = None
340
+ if hit is not None and hit[1].type in FUNC_DECL:
341
+ v = self._inline(hit[0], hit[1], {}, 0)
342
+ if v is None:
343
+ v = self._returned_text(hit[0], hit[1])
344
+ fills[m.group(0)] = v.text if isinstance(v, Cond) else v if isinstance(v, str) else marker(f"{_txt(arg)}.{method}()")
345
+ return fills
346
+
347
+ @staticmethod
348
+ def _returned_text(cgf: GoFile, func: Node) -> str | None:
349
+ """The string a method returns, when it has one return and that is a string the source decides."""
350
+ body = func.child_by_field_name("body")
351
+ returns = []
352
+ stack = [body] if body is not None else []
353
+ while stack:
354
+ n = stack.pop()
355
+ if n.type == "return_statement":
356
+ returns.append(n)
357
+ elif n.type != "func_literal":
358
+ stack.extend(n.children)
359
+ if len(returns) != 1 or not returns[0].named_children or not returns[0].named_children[0].named_children:
360
+ return None
361
+ res = cgf.resolve(returns[0].named_children[0].named_children[0], returns[0], 0)
362
+ return res.text if res is not None and not res.dynamic else None
363
+
364
+ def _instantiate(self, gf: GoFile, call: Node, t: Template) -> None:
365
+ bind = self._bind(gf, call, t.func)
366
+ fills = self._fills(gf, call, t, bind)
367
+ q = t.q.clone()
368
+ q.map_text(lambda text: _fill(text, fills))
369
+ needed = self._needed(t)
370
+ if self._open_tokens(gf, call, {k: v for k, v in bind.items() if k in needed}, t.lib):
371
+ outer = gf._enclosing(call, FUNC_DECL)
372
+ if outer is not None and outer.id != t.func.id:
373
+ nested = Template(gf, outer, q, t.name, t.args, t.call, t.lib)
374
+ nested.inner = (t, bind) # resolved when the outer function's caller is known
375
+ self.add_template(nested)
376
+ self.site_calls.add((gf.rel, call.start_byte))
377
+ return
378
+ self.stats.wrapper_calls += 1
379
+ base, full = t, bind
380
+ chain = []
381
+ while getattr(base, "inner", None) is not None:
382
+ inner_t, inner_bind = base.inner
383
+ chain.append(inner_bind)
384
+ base = inner_t
385
+ for inner_bind in chain: # from the outermost wrapper inwards
386
+ full = self._compose(inner_bind, full)
387
+ try:
388
+ stmts = self.statements(q, base.name, base.args, base.call, base.gf, full)
389
+ except Unresolved as e:
390
+ self.count(t.lib, gf, call, "wrapper call: " + ("the caller's model is not known" if str(e) == "wrapper" else str(e)))
391
+ return
392
+ (self.stats.seen_tests if gf.test else self.stats.seen)[t.lib] += 1
393
+ fn = call.child_by_field_name("function")
394
+ where = f"{base.gf.rel}:{base.call.start_point[0] + 1}"
395
+ self.emit(gf, call, stmts, t.lib, trim(_txt(fn) if fn is not None else "", 80),
396
+ notes=[f"through the wrapper {base.gf.symbol(base.call)} ({where})"])
397
+
398
+ def _needed(self, t: Template) -> set:
399
+ """The tokens a template's statement depends on: the wrapper's `any` parameters and type parameters."""
400
+ out = set()
401
+ func = t.func
402
+ for pname in param_names(func):
403
+ if pname and T.base_type(param_type(func, pname))[0] in ("any", "interface{}"):
404
+ out.add(("param", pname))
405
+ for p in self.types.type_params(func):
406
+ out.add(("typeparam", p))
407
+ return out
408
+
409
+ def _compose(self, inner_bind: dict, outer_bind: dict) -> dict:
410
+ """Bindings of an inner wrapper, with the values that were the outer wrapper's own parameters replaced
411
+ by what the outer wrapper's caller passed."""
412
+ out: dict = {}
413
+ for tok, values in inner_bind.items():
414
+ new = []
415
+ for b in values:
416
+ if isinstance(b, TypeRef):
417
+ hit = outer_bind.get(("typeparam", T.base_type(b.text)[0]))
418
+ new.extend(hit if hit else [b])
419
+ else:
420
+ tk = self.model_token(b[0], b[1], b[2])
421
+ hit = outer_bind.get(tk) if tk is not None else None
422
+ new.extend(hit if hit else [b])
423
+ out[tok] = new
424
+ return out
425
+
426
+ # ---- loops -------------------------------------------------------------------------------
427
+ def calls_in(self, gf: GoFile, func: Node) -> list[Node]:
428
+ got = self._calls_by_func.get(gf.rel)
429
+ if got is None:
430
+ got = defaultdict(list)
431
+ for c in gf.calls:
432
+ f = gf._enclosing(c, FUNC_DECL)
433
+ if f is not None:
434
+ got[f.id].append(c)
435
+ self._calls_by_func[gf.rel] = got
436
+ return got.get(func.id, [])
437
+
438
+ def reach(self, cgf: GoFile, func: Node, hops: int, seen: frozenset = frozenset()) -> list[tuple[OrmSite, int]]:
439
+ """Reads that run when a function is called: its own, and those of functions it calls with certainty."""
440
+ key = (func.id, hops)
441
+ if key in self._reach_memo:
442
+ return self._reach_memo[key]
443
+ out: list[tuple[OrmSite, int]] = [(s, 0) for s in self.by_func.get((cgf.rel, func.id), ())
444
+ if s.orm and s.orm["operation"] in ("select", "count", "exist", "sum")]
445
+ if hops > 0:
446
+ for c in self.calls_in(cgf, func):
447
+ if (cgf.rel, c.start_byte) in self.site_calls:
448
+ continue
449
+ hit = self.types.callee(cgf, c)
450
+ if hit is None or hit[1].type not in FUNC_DECL or hit[1].id in seen or hit[1].id == func.id:
451
+ continue
452
+ out.extend((s, d + 1) for s, d in self.reach(hit[0], hit[1], hops - 1, seen | {func.id}))
453
+ if not seen:
454
+ self._reach_memo[key] = out
455
+ return out
456
+
457
+ def files(self) -> list[GoFile]:
458
+ return [gf for gf in self.ctx.files.values() if O.IN_TESTS or not gf.test]
459
+
460
+ def _loader_names(self) -> set[str]:
461
+ """Names of functions that may reach a read within the hop limit: only calls to these are resolved."""
462
+ by_file = {gf.rel: gf for gf in self.ctx.files.values()}
463
+ names: set[str] = set()
464
+ for (rel, fid), sites in self.by_func.items():
465
+ if not any(s.orm and s.orm["operation"] in ("select", "count", "exist", "sum") for s in sites):
466
+ continue
467
+ gf = by_file.get(rel)
468
+ for n in (gf.root.named_children if gf is not None else ()):
469
+ if n.id == fid:
470
+ nm = n.child_by_field_name("name")
471
+ if nm is not None:
472
+ names.add(_txt(nm))
473
+ for _ in range(max(O.LOOP_HOPS - 1, 0)):
474
+ more: set[str] = set()
475
+ for gf in self.ctx.files.values():
476
+ if gf.test and not O.IN_TESTS:
477
+ continue
478
+ for n in gf.root.named_children:
479
+ if n.type not in FUNC_DECL:
480
+ continue
481
+ nm = n.child_by_field_name("name")
482
+ if nm is None or _txt(nm) in names:
483
+ continue
484
+ if any(callee_name(c.child_by_field_name("function"))[0] in names for c in self.calls_in(gf, n)):
485
+ more.add(_txt(nm))
486
+ if not more:
487
+ break
488
+ names |= more
489
+ return names
490
+
491
+ def loop_sites(self) -> None:
492
+ if O.LOOP_HOPS <= 0:
493
+ return
494
+ names = self._loader_names()
495
+ for gf in self.files():
496
+ for call in gf.calls:
497
+ if callee_name(call.child_by_field_name("function"))[0] not in names:
498
+ continue
499
+ loop = self.body_loop(gf, call)
500
+ if loop is None or (gf.rel, call.start_byte) in self.site_calls:
501
+ continue
502
+ try:
503
+ hit = self.types.callee(gf, call)
504
+ if hit is None or hit[1].type not in FUNC_DECL:
505
+ continue
506
+ found = self.reach(hit[0], hit[1], O.LOOP_HOPS - 1)
507
+ except Exception:
508
+ self.stats.errors += 1
509
+ continue
510
+ if not found:
511
+ continue
512
+ fn = call.child_by_field_name("function")
513
+ done: set[str] = set()
514
+ for site, hops in sorted(found, key=lambda x: x[1]):
515
+ if site.sql in done or len(done) >= O.LOOP_STATEMENTS:
516
+ continue
517
+ done.add(site.sql)
518
+ orm = site.orm or {}
519
+ note = (f"N+1: this call runs once per iteration of the loop at line {loop.start_point[0] + 1}; the statement is in "
520
+ f"{site.symbol or site.file} ({site.file}:{site.line})" + (f", {hops} call(s) further down" if hops else ""))
521
+ st = Stmt(site.sql, orm.get("operation", "select"), orm.get("model_or_table", ""), "medium" if hops == 0 else "low",
522
+ [note], site.engine_hint)
523
+ self.emit(gf, call, [st], orm.get("library", ""), trim(_txt(fn) if fn is not None else "", 80), in_loop=True,
524
+ loop_copy=True)
525
+ if not gf.test:
526
+ self.stats.loop_sites += 1
527
+
528
+
529
+ LAST: dict = {"summary": {}, "tables": [], "untranslated": [], "replaced": []}
530
+
531
+
532
+ def apply_settings(settings: dict | None) -> None:
533
+ settings = settings or {}
534
+ O.MARKER_CHARS = int(settings.get("orm_marker_chars", O.DEFAULT_MARKER_CHARS))
535
+ O.WRAPPER_ROUNDS = int(settings.get("orm_wrapper_rounds", O.DEFAULT_WRAPPER_ROUNDS))
536
+ O.LOOP_HOPS = int(settings.get("orm_loop_hops", O.DEFAULT_LOOP_HOPS))
537
+ O.LOOP_STATEMENTS = int(settings.get("orm_loop_statements", O.DEFAULT_LOOP_STATEMENTS))
538
+ O.IN_TESTS = bool(settings.get("orm_in_tests", False))
539
+ T.DEPTH = int(settings.get("orm_depth", T.DEFAULT_DEPTH))
540
+
541
+
542
+ def extract(ctx, existing: list[RawSite]) -> list[RawSite]:
543
+ """ORM and builder sites of the parsed Go files, added to the Go extractor's own sites. An existing
544
+ site that only said "the SQL is in a variable" is dropped where the builder behind that variable is now
545
+ written out (`sql, args, _ := query.ToSql()` then `db.Select(&rows, sql, args...)`)."""
546
+ LAST["summary"], LAST["tables"], LAST["untranslated"], LAST["replaced"] = {}, [], [], []
547
+ types = Types(ctx)
548
+ if not types.libs:
549
+ return existing
550
+ held_globals = set(ctx.used_globals)
551
+ run = Run(ctx, types)
552
+ for gf in run.files():
553
+ for call in gf.calls:
554
+ try:
555
+ run.visit(gf, call)
556
+ except Exception: # one odd call must not stop the inventory
557
+ run.stats.errors += 1
558
+ run.instantiate()
559
+ try:
560
+ run.loop_sites()
561
+ except Exception:
562
+ run.stats.errors += 1
563
+ ctx.used_globals.clear()
564
+ ctx.used_globals.update(held_globals)
565
+
566
+ dropped = 0
567
+ kept: list[RawSite] = []
568
+ LAST["replaced"] = []
569
+ for s in existing:
570
+ key = (s.file, s.symbol, s.expr.strip())
571
+ if s.sql is None and key in run.replaced:
572
+ dropped += 1
573
+ new = run.replaced_by.get(key)
574
+ if new is not None:
575
+ # kept in the list as a ghost: discover gives it the id it had and passes that id to `new`
576
+ LAST["replaced"].append((s, new))
577
+ kept.append(s)
578
+ continue
579
+ kept.append(s)
580
+
581
+ st = run.stats
582
+ libs = sorted(set(st.seen) | set(st.seen_tests) | set(st.emitted) | set(st.raw))
583
+ summary = {}
584
+ for lib in libs:
585
+ summary[lib] = {
586
+ "calls_seen": st.seen[lib], "calls_seen_in_tests": st.seen_tests[lib], "calls_translated": st.emitted[lib],
587
+ "sites_emitted": st.statements[lib], "calls_not_translated": st.seen[lib] - st.emitted[lib],
588
+ "reasons": dict(st.reasons[lib].most_common()),
589
+ "raw_sql_calls": st.raw[lib], # Exec/Query/Raw with a SQL string: reported by the string extractor
590
+ }
591
+ LAST["summary"] = {
592
+ "orm_calls": {lib: st.seen[lib] for lib in libs if st.seen[lib]},
593
+ "orm_calls_in_tests": {lib: st.seen_tests[lib] for lib in libs if st.seen_tests[lib]},
594
+ "orm": summary,
595
+ "orm_go": {"test_files_translated": O.IN_TESTS, "wrappers": run.wrappers_found, "wrapper_calls": st.wrapper_calls, "loop_sites": st.loop_sites,
596
+ "unresolved_sites_replaced": dropped, "errors": st.errors,
597
+ "xorm_mapper": ("gonic" if types.xorm_gonic else "snake") if "xorm" in types.libs else ""},
598
+ }
599
+ LAST["untranslated"] = st.untranslated
600
+ LAST["tables"] = model_tables(types)
601
+ return kept + run.sites
602
+
603
+
604
+ def summary_extras() -> dict:
605
+ return dict(LAST["summary"])
606
+
607
+
608
+ def model_tables(types: Types) -> list:
609
+ """Tables the project declares as Go structs (tagged for xorm or GORM, or used in a statement)."""
610
+ seen: dict[tuple[str, str], Model] = {}
611
+ for m in types.tagged_models():
612
+ seen[(m.dir, m.name)] = m
613
+ for m in types._model_cache.values():
614
+ if m is not None and m.used and m.cols:
615
+ seen.setdefault((m.dir, m.name), m)
616
+ out = []
617
+ for m in seen.values():
618
+ if not re.fullmatch(r"[A-Za-z_][\w.]*", m.table):
619
+ continue
620
+ out.append(GoTable(name=m.table, defined_at=[m.defined_at], primary_key=", ".join(m.pk),
621
+ columns=[{"name": c.name, "type": c.type} for c in m.cols], indexes=list(m.indexes)))
622
+ return out
623
+
624
+
625
+ def _table_base():
626
+ from .schema import Table
627
+ return Table
628
+
629
+
630
+ @dataclass
631
+ class GoTable(_table_base()):
632
+ indexes: list[dict] = field(default_factory=list)
633
+
634
+
635
+ def tables() -> list:
636
+ return list(LAST["tables"])