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,307 @@
1
+ """Coverage counts for database access through ORMs and query builders (JVM and Rust).
2
+
3
+ Every ORM extractor says, per library: calls seen, calls turned into at least one site, sites emitted, calls
4
+ not translated and why. Nothing is dropped silently: a call that cannot be translated is counted with a reason.
5
+ The inventory summary gets `orm_calls` (library -> calls seen in application code, the original summary shape),
6
+ `orm_calls_in_tests`, and `orm_coverage` (library -> the detail).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections import Counter
12
+
13
+ # How many reasons are listed per library. A setting: `[discover] orm_top_reasons`.
14
+ DEFAULT_TOP_REASONS = 12
15
+ TOP_REASONS = DEFAULT_TOP_REASONS
16
+ # How many places are named per reason (file:line of a call that was not translated). A setting:
17
+ # `[discover] orm_reason_examples`.
18
+ DEFAULT_REASON_EXAMPLES = 3
19
+ REASON_EXAMPLES = DEFAULT_REASON_EXAMPLES
20
+
21
+
22
+ class Stats:
23
+ def __init__(self) -> None:
24
+ self.calls: Counter[str] = Counter()
25
+ self.test_calls: Counter[str] = Counter()
26
+ self.translated: Counter[str] = Counter()
27
+ self.test_translated: Counter[str] = Counter()
28
+ self.sites: Counter[str] = Counter()
29
+ self.reasons: dict[str, Counter[str]] = {}
30
+ self.misses: list[dict] = [] # every call not translated: library, file, line, reason (for sampling)
31
+
32
+ def clear(self) -> None:
33
+ self.__init__()
34
+
35
+ def seen(self, library: str, is_test: bool = False) -> None:
36
+ (self.test_calls if is_test else self.calls)[library] += 1
37
+
38
+ def hit(self, library: str, n_sites: int = 1, is_test: bool = False) -> None:
39
+ if is_test:
40
+ self.test_translated[library] += 1
41
+ else:
42
+ self.translated[library] += 1
43
+ self.sites[library] += n_sites
44
+
45
+ def miss(self, library: str, reason: str, file: str = "", line: int = 0, is_test: bool = False) -> None:
46
+ if is_test:
47
+ return
48
+ self.reasons.setdefault(library, Counter())[reason] += 1
49
+ self.misses.append({"library": library, "file": file, "line": line, "reason": reason})
50
+
51
+ def summary(self) -> dict:
52
+ if not self.calls and not self.test_calls:
53
+ return {}
54
+ coverage = {}
55
+ for lib in sorted(self.calls):
56
+ calls, done = self.calls[lib], self.translated[lib]
57
+ reasons = self.reasons.get(lib, Counter())
58
+ examples: dict[str, list[str]] = {}
59
+ for m in self.misses:
60
+ if m["library"] == lib and m["file"] and len(examples.setdefault(m["reason"], [])) < REASON_EXAMPLES:
61
+ examples[m["reason"]].append(f"{m['file']}:{m['line']}")
62
+ top = dict(reasons.most_common()) # cut to the setting once, in finish()
63
+ coverage[lib] = {
64
+ "calls": calls, "translated": done, "sites": self.sites[lib],
65
+ "not_translated": sum(reasons.values()),
66
+ "share_translated": round(done / calls, 3) if calls else None,
67
+ "translated_in_tests": self.test_translated[lib],
68
+ "reasons": top,
69
+ "examples": {r: examples.get(r, []) for r in top if examples.get(r)},
70
+ }
71
+ return {"orm_calls": dict(self.calls.most_common()), "orm_calls_in_tests": dict(self.test_calls.most_common()),
72
+ "orm_coverage": coverage}
73
+
74
+
75
+ # ---- one shape for every translator ------------------------------------------------------------------------
76
+ # Whether ORM and builder calls in test files become sites: `[discover] orm_in_tests` (the old Python name
77
+ # `orm_tests` is still read). Off by default: a test's statements are never ranked, and in some repositories
78
+ # there are as many of them as application ones. Strings of SQL in tests are reported either way, with `is_test`.
79
+ IN_TESTS = False
80
+ # Counts with a "<library>-<kind>" name are kinds of one library (jpa-lazy, jpa-criteria, jdbi-stringtemplate).
81
+ _KINDS = ("jpa", "jdbi", "spring-data")
82
+
83
+
84
+ def apply_settings(settings: dict | None) -> None:
85
+ global IN_TESTS, TOP_REASONS, REASON_EXAMPLES
86
+ settings = settings or {}
87
+ IN_TESTS = bool(settings.get("orm_in_tests", settings.get("orm_tests", False)))
88
+ TOP_REASONS = int(settings.get("orm_top_reasons", DEFAULT_TOP_REASONS))
89
+ REASON_EXAMPLES = int(settings.get("orm_reason_examples", DEFAULT_REASON_EXAMPLES))
90
+
91
+
92
+ def _row(language: str) -> dict:
93
+ return {"language": language, "calls_seen": 0, "translated": 0, "sites": 0, "not_translated": 0, "reasons": [],
94
+ "in_tests": {"seen": 0, "translated": 0, "skipped": 0}, "raw_passthrough": 0}
95
+
96
+
97
+ def _reasons(counts: dict | None, examples: dict | None = None) -> list[dict]:
98
+ """[{reason, count, example}], most frequent first; `example` is one file:line or ""."""
99
+ out = []
100
+ for reason, n in sorted((counts or {}).items(), key=lambda kv: (-kv[1], kv[0])):
101
+ ex = (examples or {}).get(reason) or ""
102
+ out.append({"reason": reason, "count": n, "example": ex[0] if isinstance(ex, list) else ex})
103
+ return out
104
+
105
+
106
+ def _raw_passthrough(reasons: list[dict]) -> int:
107
+ return sum(r["count"] for r in reasons if "raw sql" in r["reason"].lower())
108
+
109
+
110
+ def _tests(seen: int | None, translated: int | None) -> dict:
111
+ """Calls in test code: all skipped unless `orm_in_tests`. `seen` is None when test files were not read."""
112
+ if IN_TESTS:
113
+ return {"seen": seen, "translated": translated, "skipped": 0}
114
+ return {"seen": seen, "translated": 0, "skipped": seen}
115
+
116
+
117
+ def _add(a, b):
118
+ return None if a is None or b is None else a + b
119
+
120
+
121
+ def _fold(into: dict, row: dict, kind: str) -> None:
122
+ """Add a kind's counts (jpa-lazy) to its library's row, keeping the kind's own figures under `kinds`."""
123
+ for key in ("calls_seen", "translated", "sites", "not_translated", "raw_passthrough"):
124
+ into[key] += row[key]
125
+ for key in ("seen", "translated", "skipped"):
126
+ into["in_tests"][key] = _add(into["in_tests"][key], row["in_tests"][key])
127
+ merged = {r["reason"]: dict(r) for r in into["reasons"]}
128
+ for r in row["reasons"]:
129
+ if r["reason"] in merged:
130
+ merged[r["reason"]]["count"] += r["count"]
131
+ else:
132
+ merged[r["reason"]] = dict(r)
133
+ into["reasons"] = sorted(merged.values(), key=lambda r: (-r["count"], r["reason"]))
134
+ into.setdefault("kinds", {})[kind] = {k: row[k] for k in ("calls_seen", "translated", "sites", "not_translated")}
135
+
136
+
137
+ def unify(language: str, extras: dict, go_untranslated: list | None = None) -> dict:
138
+ """One extractor's ORM counts as `{library: row}` in the one documented shape, taking the extractor's own
139
+ keys (`orm`, `orm_calls`, `orm_calls_in_tests`, `orm_coverage`, `orm_go`) out of `extras`.
140
+
141
+ row = {language, calls_seen, translated, sites, not_translated, reasons[{reason, count, example}],
142
+ in_tests{seen, translated, skipped}, raw_passthrough, kinds?, details?}. Counts are calls in
143
+ application code except `sites` (statements emitted) and `in_tests` (calls in test code)."""
144
+ calls = extras.pop("orm_calls", None) or {}
145
+ in_tests = extras.pop("orm_calls_in_tests", None) or {}
146
+ detail = extras.pop("orm", None) or {}
147
+ coverage = extras.pop("orm_coverage", None) or {}
148
+ go = extras.pop("orm_go", None)
149
+ rows: dict[str, dict] = {}
150
+ for lib, c in calls.items():
151
+ if isinstance(c, dict): # Python: the library's whole account under orm_calls
152
+ row = rows[lib] = _row(language)
153
+ row.update(calls_seen=c.get("calls_seen", 0), translated=c.get("calls_translated", 0), sites=c.get("sites_emitted", 0),
154
+ not_translated=c.get("calls_not_translated", 0),
155
+ reasons=_reasons(c.get("not_translated_reasons"), c.get("not_translated_examples")))
156
+ row["raw_passthrough"] = _raw_passthrough(row["reasons"])
157
+ # test files are read only with orm_in_tests, so calls in them are not counted when it is off
158
+ row["in_tests"] = {"seen": None, "translated": None if IN_TESTS else 0, "skipped": 0 if IN_TESTS else None,
159
+ "files_skipped": c.get("test_files_not_read", 0)}
160
+ row["details"] = {k: v for k, v in c.items() if k not in (
161
+ "calls_seen", "calls_translated", "sites_emitted", "calls_not_translated", "not_translated_reasons",
162
+ "not_translated_examples", "share_translated")}
163
+ for lib, d in detail.items():
164
+ row = rows[lib] = _row(language)
165
+ if "app" in d or "in_tests" in d: # TypeScript: {app, in_tests}
166
+ app, tst = d.get("app") or {}, d.get("in_tests") or {}
167
+ row.update(calls_seen=app.get("calls_seen", 0), translated=app.get("calls_translated", 0), sites=app.get("sites", 0),
168
+ not_translated=app.get("calls_not_translated", 0), reasons=_reasons(app.get("not_translated_reasons"), app.get("examples")))
169
+ row["in_tests"] = _tests(tst.get("calls_seen", 0), tst.get("calls_translated", 0))
170
+ row["raw_passthrough"] = _raw_passthrough(row["reasons"])
171
+ else: # Go: flat per library
172
+ examples: dict[str, str] = {}
173
+ for u in go_untranslated or ():
174
+ if u[0] == lib:
175
+ examples.setdefault(u[3], f"{u[1]}:{u[2]}")
176
+ row.update(calls_seen=d.get("calls_seen", 0), translated=d.get("calls_translated", 0), sites=d.get("sites_emitted", 0),
177
+ not_translated=d.get("calls_not_translated", 0), reasons=_reasons(d.get("reasons"), examples),
178
+ raw_passthrough=d.get("raw_sql_calls", 0))
179
+ seen = d.get("calls_seen_in_tests", 0)
180
+ row["in_tests"] = _tests(seen, None) # the Go pass counts test calls and translates them only with the setting
181
+ for lib, c in coverage.items(): # Java and Rust
182
+ row = rows[lib] = _row(language)
183
+ row.update(calls_seen=c.get("calls", 0), translated=c.get("translated", 0), sites=c.get("sites", 0),
184
+ not_translated=c.get("not_translated", 0),
185
+ reasons=_reasons(c.get("reasons"), c.get("examples")))
186
+ row["raw_passthrough"] = _raw_passthrough(row["reasons"])
187
+ row["in_tests"] = _tests(in_tests.get(lib, 0), c.get("translated_in_tests"))
188
+ for lib, n in calls.items(): # counted by a pattern, no translator: every call is untranslated
189
+ if lib not in rows and isinstance(n, int) and not isinstance(n, bool):
190
+ row = rows[lib] = _row(language)
191
+ row.update(calls_seen=n, not_translated=n,
192
+ reasons=[{"reason": "library not translated: its calls are counted only", "count": n, "example": ""}] if n else [])
193
+ row["in_tests"] = _tests(in_tests.get(lib, 0), 0)
194
+ for lib, n in in_tests.items(): # seen in test code only
195
+ if lib not in rows and isinstance(n, int):
196
+ rows[lib] = _row(language)
197
+ rows[lib]["in_tests"] = _tests(n, None)
198
+ for lib in sorted(rows): # jpa-lazy, jpa-criteria ... are kinds of jpa
199
+ base = next((b for b in _KINDS if lib.startswith(b + "-")), "")
200
+ if base:
201
+ _fold(rows.setdefault(base, _row(language)), rows.pop(lib), lib[len(base) + 1:])
202
+ if go:
203
+ extras.setdefault("_orm_details", {})["go"] = go
204
+ return rows
205
+
206
+
207
+ def finish(libraries: dict, details: dict, dropped: dict) -> dict:
208
+ """`summary.orm` and the flat `summary.orm_calls`. `dropped`: what the one-site-per-call rule removed."""
209
+ for lib, n in (dropped.get("test_sites_skipped") or {}).items():
210
+ row = libraries.get(lib)
211
+ if row is not None:
212
+ row["in_tests"]["sites_skipped"] = n
213
+ for row in libraries.values():
214
+ row["reasons_total"] = len(row["reasons"])
215
+ row["reasons"] = row["reasons"][:TOP_REASONS]
216
+ keys = ("calls_seen", "translated", "sites", "not_translated", "raw_passthrough")
217
+ totals = {k: sum(r[k] for r in libraries.values()) for k in keys}
218
+ totals["libraries"] = len(libraries)
219
+ for k in ("seen", "translated", "skipped"):
220
+ vals = [r["in_tests"][k] for r in libraries.values()]
221
+ totals["in_tests_" + k] = sum(v for v in vals if v is not None)
222
+ totals["raw_sites_replaced"] = dropped.get("raw_sites_replaced", 0) # an unresolved raw site at a call a translator wrote out
223
+ totals["orm_sites_dropped_for_literal_sql"] = dropped.get("orm_sites_dropped", 0)
224
+ totals["nested_calls_merged"] = dropped.get("nested_calls_merged", 0) # execute(text("...")): the call that runs it is the site
225
+ orm = {"libraries": libraries, "totals": totals, "in_tests": IN_TESTS}
226
+ if details:
227
+ orm["details"] = details
228
+ return {"orm": orm, "orm_calls": {lib: r["calls_seen"] for lib, r in sorted(libraries.items(), key=lambda kv: -kv[1]["calls_seen"])}}
229
+
230
+
231
+ def one_site_per_call(raw: list, ghosts: dict | None = None) -> tuple[list, dict]:
232
+ """One call, one site, in every language. Where a raw-string extractor and a translator both report the
233
+ same call (same file, line and enclosing function):
234
+ - the translator's site wins when it produced SQL and the raw site has none (`session.execute(select(...))`
235
+ seen as "SQL in a variable" and as a SELECT);
236
+ - the raw site wins when its string is literal SQL (the translator saw the call's shape, the string is the
237
+ statement that runs);
238
+ - `execute(text("SELECT ..."))`: the call that runs the string is the site, the wrapper inside it is not.
239
+ Also the test-code rule: a site a translator synthesised from a call in test code is dropped unless
240
+ `orm_in_tests`; a site that was a string first (JPQL in an annotation) stays, as raw strings in tests do.
241
+
242
+ With `ghosts` (a dict), a site that lost to another stays in the returned list and is entered there as
243
+ id(site) -> the site that replaced it: discover gives it the id it always had, hands that id to its
244
+ replacement as `previous_ids`, and does not emit it. Without, the losers are left out.
245
+ Returns (sites, {raw_sites_replaced, orm_sites_dropped, nested_calls_merged, test_sites_skipped{library: n}})."""
246
+ skipped: Counter[str] = Counter()
247
+ if not IN_TESTS:
248
+ kept = []
249
+ for r in raw:
250
+ if r.is_test and r.resolution == "orm" and r.orm and not r.orm.get("id_from") and not r.orm.get("source"):
251
+ skipped[r.orm.get("library", "")] += 1
252
+ else:
253
+ kept.append(r)
254
+ raw = kept
255
+ by_place: dict[tuple, list] = {}
256
+ for r in raw:
257
+ if r.kind == "call":
258
+ by_place.setdefault((r.file, r.line, r.symbol), []).append(r)
259
+ lost: dict[int, object] = {} # id(site that lost) -> the site that stands for the call
260
+ replaced = dropped = nested = 0
261
+ for group in by_place.values():
262
+ if len(group) < 2:
263
+ continue
264
+ strings = [r for r in group if r.sql and not r.orm]
265
+ for outer in strings:
266
+ for inner in strings:
267
+ if (inner is not outer and id(outer) not in lost and id(inner) not in lost and inner.sql == outer.sql
268
+ and inner.sink != outer.sink and inner.sink and inner.sink.rsplit(".", 1)[-1] + "(" in outer.expr):
269
+ lost[id(inner)] = outer
270
+ nested += 1
271
+ made = [r for r in group if r.resolution == "orm" and r.sql and not (r.orm or {}).get("id_from")]
272
+ plain = [r for r in group if r.resolution != "orm" and not r.orm and id(r) not in lost]
273
+ if not made or not plain:
274
+ continue
275
+ literal = [r for r in plain if r.sql and r.resolution in ("literal", "constant", "template", "file")]
276
+ for r in made:
277
+ winner = next((x for x in literal if x.end_line == r.end_line), None)
278
+ if winner is not None:
279
+ lost[id(r)] = winner
280
+ dropped += 1
281
+ standing = [r for r in made if id(r) not in lost]
282
+ if standing:
283
+ for r in plain:
284
+ if r.sql is None:
285
+ lost[id(r)] = standing[0]
286
+ replaced += 1
287
+ counts = {"raw_sites_replaced": replaced, "orm_sites_dropped": dropped, "nested_calls_merged": nested,
288
+ "test_sites_skipped": dict(skipped)}
289
+ if ghosts is not None:
290
+ ghosts.update(lost)
291
+ return raw, counts
292
+ return [r for r in raw if id(r) not in lost], counts
293
+
294
+
295
+ def merge_extras(into: dict, more: dict) -> None:
296
+ """Add one extractor's summary counts to the inventory's: per-library dictionaries are merged, so a
297
+ repository in two languages keeps both languages' libraries."""
298
+ for key, value in more.items():
299
+ cur = into.get(key)
300
+ if isinstance(cur, dict) and isinstance(value, dict) and (key == "orm" or key.startswith("orm_") or key == "named_queries"):
301
+ for k, v in value.items():
302
+ if isinstance(cur.get(k), int) and isinstance(v, int):
303
+ cur[k] += v
304
+ else:
305
+ cur[k] = v
306
+ else:
307
+ into[key] = value
@@ -0,0 +1,29 @@
1
+ """The hooks discovery calls for the JVM and Rust ORM extractors: their table definitions and their settings.
2
+
3
+ The extractors (orm_java, orm_rust) read the mappings while they look for call sites; discovery collects the
4
+ tables here after the per-language pass, the way it collects Prisma, Drizzle and TypeORM tables.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+
10
+ def find_tables() -> list:
11
+ out: list = []
12
+ for name in ("orm_java", "orm_rust"):
13
+ try:
14
+ mod = __import__(f"codecop.discover.{name}", fromlist=["tables"])
15
+ except ImportError:
16
+ continue
17
+ out.extend(mod.tables())
18
+ return out
19
+
20
+
21
+ def apply_settings(settings: dict | None) -> None:
22
+ """Every limit of the ORM extractors is a `[discover]` setting."""
23
+ for name in ("orm_java", "orm_rust", "orm_jooq", "orm_jdbi", "orm_ex_ecto"):
24
+ try:
25
+ mod = __import__(f"codecop.discover.{name}", fromlist=["apply_settings"])
26
+ except ImportError:
27
+ continue
28
+ if hasattr(mod, "apply_settings"):
29
+ mod.apply_settings(settings)