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,702 @@
1
+ """Stage 1, discover: a deterministic inventory of every database call in a repo.
2
+
3
+ No LLM and no database. Output is inventory.json, which every later stage reads.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import fnmatch
9
+ import gc
10
+ import importlib
11
+ import os
12
+ import re
13
+ import subprocess
14
+ import time
15
+ from collections import Counter
16
+ from dataclasses import asdict, replace
17
+ from datetime import datetime, timezone
18
+ from pathlib import Path
19
+
20
+ from .. import __version__, formerly
21
+ from ..sqlinfo import analyze as analyze_sql
22
+ from ..sqlinfo import (NON_SQL, NOT_CLICKHOUSE, analyze, fingerprint, guess_engine, has_template_tokens,
23
+ resolve_template_tokens, write_targets)
24
+ from . import dialect, orm_stats, origins
25
+ from . import schema as schema_mod
26
+ from . import schema_ent
27
+ from .base import BARE_DDL, READ, RawSite, is_test_path, load_rules, path_engine, read_text, receiver_engine
28
+
29
+ SCHEMA_VERSION = 1
30
+ LANG_BY_EXT = {".py": "python", ".rs": "rust", ".go": "go", ".java": "java"}
31
+ LANG_BY_EXT.update(dict.fromkeys((".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"), "typescript"))
32
+ # Languages read only for their database libraries (ActiveRecord, Ecto, the JVM libraries in Kotlin). Each module
33
+ # may also offer `tables()`: the tables its library's own model or migration definitions declare.
34
+ LANG_BY_EXT.update({".rb": "ruby", ".ex": "elixir", ".exs": "elixir", ".kt": "kotlin"})
35
+ LIBRARY_LANGUAGES = ("ruby", "elixir", "kotlin", "xml")
36
+ MODULE_BY_LANG = {"xml": "xml_mapper"} # `xml` would shadow nothing, but reads as the standard library
37
+ TEXT_EXTS = {".py", ".rs", ".go", ".java", ".sql", ".yml", ".yaml", ".md", ".toml", ".json", ".sh", ".tf", ".env", ".txt", ".kt", ".ts", ".js",
38
+ # templates that hold SQL (Go text/template, Jinja) and files that name the project's database driver
39
+ ".tmpl", ".tpl", ".gotmpl", ".j2", ".jinja", ".jinja2", ".mod", ".gradle", ".kts", ".cfg", ".properties", ".conf", ".ini"}
40
+ TEXT_NAMES = ("Dockerfile", "Jenkinsfile", "docker-compose")
41
+ MANIFEST_NAMES = {"pom.xml", "Pipfile", "persistence.xml", "hibernate.cfg.xml"}
42
+ # The engines a project default may name. Anything else in codecop.toml is a typo, not a dialect.
43
+ ENGINES = ("postgres", "clickhouse", "mysql", "sqlite", "mssql", "oracle")
44
+ # Statement-level evidence for an engine: the only kind a file's other statements may be judged by.
45
+ DIRECT_BASES = ("sql", "hint", "receiver", "table", "handle", "package")
46
+ SKIP_DIRS = {".git", "node_modules", "target", ".venv", "venv", "__pycache__", "dist", "build", ".codecop", formerly.OLD_OUT_DIR, ".tox", ".mypy_cache",
47
+ "site-packages", "vendor", ".trail", ".next", ".idea"}
48
+ TEXT_EXTS |= {".tsx", ".jsx", ".mjs", ".cjs", ".mts", ".cts", ".rb", ".ex", ".exs"}
49
+
50
+
51
+ def list_files(root: Path) -> list[str]:
52
+ """Tracked files when the repo uses git (so ignored build output is skipped), else a filtered walk."""
53
+ if (root / ".git").exists():
54
+ try:
55
+ out = subprocess.run(["git", "-C", str(root), "ls-files", "-z"], capture_output=True, check=True).stdout
56
+ files = [f for f in out.decode("utf-8", "replace").split("\0") if f]
57
+ return [f for f in files if not any(part in SKIP_DIRS for part in f.split("/"))]
58
+ except (OSError, subprocess.CalledProcessError):
59
+ pass
60
+ found = []
61
+ for dirpath, dirnames, filenames in os.walk(root):
62
+ dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
63
+ for name in filenames:
64
+ found.append(os.path.relpath(os.path.join(dirpath, name), root))
65
+ return found
66
+
67
+
68
+ def git_info(root: Path) -> dict:
69
+ def run(*args: str) -> str:
70
+ try:
71
+ return subprocess.run(["git", "-C", str(root), *args], capture_output=True, text=True, check=True).stdout.strip()
72
+ except (OSError, subprocess.CalledProcessError):
73
+ return ""
74
+ return {"commit": run("rev-parse", "HEAD"), "branch": run("rev-parse", "--abbrev-ref", "HEAD")}
75
+
76
+
77
+ def _split_statements(text: str) -> list[tuple[int, str]]:
78
+ """Split a .sql file on semicolons outside quotes. Returns (line, statement)."""
79
+ out, start, quote, i, n = [], 0, "", 0, len(text)
80
+ while i < n:
81
+ c = text[i]
82
+ if quote:
83
+ if c == quote:
84
+ quote = ""
85
+ elif c in "'\"`":
86
+ quote = c
87
+ elif c == "-" and text.startswith("--", i):
88
+ i = text.find("\n", i)
89
+ if i < 0:
90
+ break
91
+ continue
92
+ elif c == ";":
93
+ out.append((start, text[start:i]))
94
+ start = i + 1
95
+ i += 1
96
+ out.append((start, text[start:]))
97
+ result = []
98
+ for offset, stmt in out:
99
+ body = stmt.strip()
100
+ if body:
101
+ lead = len(stmt) - len(stmt.lstrip())
102
+ result.append((text.count("\n", 0, offset + lead) + 1, body))
103
+ return result
104
+
105
+
106
+ def _sql_file_sites(rel: str, text: str) -> list[RawSite]:
107
+ sites = []
108
+ for line, stmt in _split_statements(text):
109
+ sites.append(RawSite(
110
+ file=rel, line=line, end_line=line + stmt.count("\n"), language="sql", kind="sql_file", sink="", symbol="",
111
+ sql=stmt, resolution="file", expr="", is_test=is_test_path(rel), known_sink=False,
112
+ ))
113
+ return sites
114
+
115
+
116
+ def _outside_evidence(r: RawSite, engine: str, basis: str) -> tuple[str, str]:
117
+ """Engine evidence from around the statement, applied after the statement's own analysis so that the SQL
118
+ fingerprint (and with it the call-site id) does not move: the receiver of the call
119
+ (`s.chConn.Select`), then a directory that names an engine (`sqlplugin/sqlite/`).
120
+
121
+ The receiver overrides the sink rule and the file's imports, which are per file, and overrides a guess from
122
+ the SQL text only when everything that guess rested on is syntax the receiver's engine shares."""
123
+ if engine in NON_SQL:
124
+ return engine, basis
125
+ named = receiver_engine(r.sink) if r.kind == "call" and r.sink else ""
126
+ if named and named != engine:
127
+ if basis != "sql" or r.sql is None or guess_engine(r.sql, named, by_receiver=True)[0] == named:
128
+ return named, "receiver"
129
+ if not engine:
130
+ by_path = path_engine(r.file)
131
+ if by_path:
132
+ return by_path, "path"
133
+ return engine, basis
134
+
135
+
136
+ def apply_settings(settings: dict | None) -> None:
137
+ """Limits are settings: `[discover]` keys in codecop.toml override the defaults for this run."""
138
+ from . import go as go_mod
139
+ from . import python as python_mod
140
+
141
+ settings = settings or {}
142
+ orm_stats.apply_settings(settings) # orm_in_tests: the one setting for ORM translation of test code
143
+ if "orm_in_tests" in settings or "orm_tests" in settings: # every translator reads the same answer
144
+ settings = {**settings, "orm_in_tests": orm_stats.IN_TESTS, "orm_tests": orm_stats.IN_TESTS}
145
+ from . import orm_ts
146
+ orm_ts.configure(settings) # the orm_* limits of TypeScript ORM and builder translation
147
+ go_mod.MAX_VARIANTS = int(settings.get("max_variants", go_mod.DEFAULT_MAX_VARIANTS))
148
+ python_mod.MAX_VARIANTS = int(settings.get("max_variants", python_mod.DEFAULT_MAX_VARIANTS))
149
+ go_mod.MAX_FIELD_VALUES = int(settings.get("max_field_values", go_mod.DEFAULT_MAX_FIELD_VALUES))
150
+ schema_mod.MAX_TABLE_CHARS = int(settings.get("max_table_chars", schema_mod.DEFAULT_MAX_TABLE_CHARS))
151
+ schema_mod.MAX_TABLE_TAIL_CHARS = int(settings.get("max_table_tail_chars", schema_mod.DEFAULT_MAX_TABLE_TAIL_CHARS))
152
+ go_mod.MAX_DEPTH = int(settings.get("go_resolve_depth", go_mod.DEFAULT_MAX_DEPTH))
153
+ from . import engine_go
154
+ engine_go.DEPTH = int(settings.get("go_handle_depth", engine_go.DEFAULT_DEPTH))
155
+ go_mod.MAX_CONST_CHARS = int(settings.get("max_const_chars", go_mod.DEFAULT_MAX_CONST_CHARS))
156
+ python_mod.MAX_DEPTH = int(settings.get("python_resolve_depth", python_mod.DEFAULT_MAX_DEPTH))
157
+ dialect.MIN_MIGRATION_STATEMENTS = int(settings.get("min_migration_statements", 5))
158
+ dialect.MIGRATION_SHARE = float(settings.get("migration_share", 0.95))
159
+ dialect.EMBEDDED_STORE_SHARE = float(settings.get("embedded_store_share", 0.2))
160
+ from . import orm_go_run
161
+ orm_go_run.apply_settings(settings)
162
+ from . import orm_tables
163
+ orm_tables.apply_settings(settings)
164
+ from . import orm_py
165
+ orm_py.apply_settings(settings)
166
+
167
+
168
+ def discover(root: Path, include: list[str] | None = None, exclude: list[str] | None = None,
169
+ wrappers: list[dict] | None = None, progress=None, on_event=None, *,
170
+ max_file_bytes: int | None = None, default_engine: str | None = None, settings: dict | None = None,
171
+ kinds: list[str] | None = None, kind_settings: dict | None = None) -> dict:
172
+ """`progress(text)` is for the terminal; `on_event(name, label, counts)` reports the same steps as numbers.
173
+
174
+ `max_file_bytes`: files larger than this are not read, and are listed in the inventory. `default_engine`:
175
+ the engine of statements nothing else decides (basis `default`); without it one is inferred when the
176
+ project's drivers and configuration name a single engine (basis `inferred`). `settings`: the other
177
+ `[discover]` limits from codecop.toml."""
178
+ def tell(name: str, label: str, **counts) -> None:
179
+ if on_event:
180
+ on_event(name, label, counts)
181
+
182
+ if default_engine and default_engine not in ENGINES:
183
+ raise ValueError(f"default engine must be one of {', '.join(ENGINES)}, not {default_engine!r}")
184
+ started = time.monotonic()
185
+ root = root.resolve()
186
+ READ.begin(max_file_bytes)
187
+ apply_settings(settings)
188
+ files = list_files(root)
189
+ if include:
190
+ files = [f for f in files if any(f == p or f.startswith(p.rstrip("/") + "/") or fnmatch.fnmatch(f, p) for p in include)]
191
+ if exclude:
192
+ files = [f for f in files if not any(f.startswith(p.rstrip("/") + "/") or fnmatch.fnmatch(f, p) for p in exclude)]
193
+
194
+ by_lang: dict[str, list[str]] = {}
195
+ for f in files:
196
+ lang = LANG_BY_EXT.get(os.path.splitext(f)[1])
197
+ if lang:
198
+ by_lang.setdefault(lang, []).append(f)
199
+ # MyBatis mapper XML: offered only in a JVM repository, and only mapper files are read (xml_mapper.extract). Not
200
+ # source files of a language: kept out of by_lang, so the call graph, the other kinds and the file counts never see them.
201
+ mapper_xml = [f for f in files if f.endswith(".xml")] if ("java" in by_lang or "kotlin" in by_lang) else []
202
+
203
+ raw: list[RawSite] = []
204
+ skipped_languages = []
205
+ files_total, files_done = sum(len(v) for v in by_lang.values()), 0
206
+ per_language: dict[str, dict] = {}
207
+ extras: dict = {}
208
+ orm_libraries: dict[str, dict] = {}
209
+ orm_details: dict = {}
210
+ ghosts_early: dict[int, RawSite] = {}
211
+ tell("files", f"{files_total:,} source files", files_scanned=0, files_total=files_total, sites=0)
212
+ for lang, lang_files in sorted(by_lang.items()) + ([("xml", mapper_xml)] if mapper_xml else []):
213
+ files_done += len(lang_files) if lang in by_lang else 0
214
+ try:
215
+ module = importlib.import_module(f"codecop.discover.{MODULE_BY_LANG.get(lang, lang)}")
216
+ except ModuleNotFoundError:
217
+ skipped_languages.append(lang)
218
+ continue
219
+ if progress:
220
+ progress(f"{lang}: {len(lang_files)} files")
221
+ before = len(raw)
222
+ raw.extend(module.extract(root, lang_files, load_rules(lang, wrappers)))
223
+ for old, new in getattr(module, "replaced_sites", list)(): # sites the language's own translator stood in for
224
+ ghosts_early[id(old)] = new
225
+ more = dict(getattr(module, "summary_extras", dict)()) # counts an extractor reports beside its sites
226
+ untranslated = None
227
+ if lang == "go":
228
+ from . import orm_go_run
229
+ untranslated = orm_go_run.LAST.get("untranslated")
230
+ for lib, row in orm_stats.unify(lang, more, untranslated).items(): # ORM coverage: one shape for every translator
231
+ orm_libraries[f"{lib}:{lang}" if lib in orm_libraries else lib] = row
232
+ orm_details.update(more.pop("_orm_details", None) or {})
233
+ orm_stats.merge_extras(extras, more)
234
+ gc.collect() # an extractor's parsed files point at each other: let go of now, not when the next stage has grown
235
+ per_language[lang] = {"files": len(lang_files), "sites": len(raw) - before}
236
+ tell("files", f"{lang}: {len(lang_files):,} files", language=lang, files_scanned=files_done, files_total=files_total,
237
+ sites=len(raw), by_language=dict(per_language))
238
+
239
+ # one call, one site (a translator and a raw-string extractor may both see it), and the test-code rule
240
+ # A site that lost keeps its place in the list as a ghost: it is given the id it always had, which its
241
+ # replacement then carries as `previous_ids`, and it is not emitted (`ghosts`: id(site) -> replacement).
242
+ ghosts: dict[int, RawSite] = {}
243
+ raw, orm_dropped = orm_stats.one_site_per_call(raw, ghosts)
244
+ ghosts.update(ghosts_early)
245
+ extras.update(orm_stats.finish(orm_libraries, orm_details, orm_dropped))
246
+
247
+ # Schema, version evidence and .sql files come from a raw text pass over every text file.
248
+ if progress:
249
+ progress("schema and versions")
250
+ tell("phase", "Schema and versions", phase="schema", files_total=len(files))
251
+ tables, versions, renames = [], [], []
252
+ index_defs: list[dict] = [] # CREATE INDEX statements, applied to the merged tables
253
+ sql_functions: list[dict] = [] # CREATE FUNCTION ... LANGUAGE sql in .sql files (schema.find_sql_functions)
254
+ added_columns: list[dict] = [] # ALTER TABLE ... ADD COLUMN, applied in migration order
255
+ texts: list[tuple[str, str]] = []
256
+ name_consts: dict[str, set[str]] = {}
257
+ evidence = dialect.Evidence()
258
+ files_read = 0
259
+ for f in files:
260
+ ext = os.path.splitext(f)[1]
261
+ base = os.path.basename(f)
262
+ if ext not in TEXT_EXTS and not base.startswith(TEXT_NAMES) and base not in MANIFEST_NAMES:
263
+ continue
264
+ text = read_text(root / f)
265
+ if text is None:
266
+ continue
267
+ files_read += 1
268
+ if ext in LANG_BY_EXT:
269
+ for name, value in schema_mod.find_name_constants(text).items():
270
+ name_consts.setdefault(name, set()).add(value)
271
+ if "CREATE" in text or "create table" in text:
272
+ texts.append((f, text))
273
+ index_defs.extend(schema_mod.find_indexes(f, text))
274
+ if ext == ".sql" and not is_test_path(f):
275
+ sql_functions.extend(schema_mod.find_sql_functions(f, text))
276
+ if "RENAME" in text or "rename" in text:
277
+ renames.extend(schema_mod.find_renames(f, text))
278
+ if "ALTER" in text or "alter table" in text:
279
+ added_columns.extend(schema_mod.find_added_columns(f, text))
280
+ if ext == ".go" and schema_ent.is_ent_schema(f, text):
281
+ tables.extend(schema_ent.find_tables(f, text)) # ent's generated schema: the tables ent creates at start-up
282
+ if ext in (".yml", ".yaml", ".md", ".toml", ".sh", ".tf", ".env", "") or base.startswith(("Dockerfile", "Jenkinsfile")):
283
+ versions.extend(schema_mod.find_versions(f, text))
284
+ if ext not in (".md", ".txt", ".json", ".env") or dialect.MANIFEST.search(f):
285
+ evidence.scan(f, text, is_test_path(f))
286
+ if ext == ".sql":
287
+ raw.extend(_sql_file_sites(f, text))
288
+ for f, text in texts:
289
+ tables.extend(schema_mod.find_tables(f, text, name_consts))
290
+ if "python" in per_language:
291
+ from . import orm_py # Django models, SQLAlchemy models and Table(), Alembic migrations
292
+ tables = orm_py.tables() + tables
293
+ if "typescript" in per_language or any(f.endswith(".prisma") for f in files):
294
+ from . import schema_ts # Prisma schema files, Drizzle tables, TypeORM entities
295
+ tables = schema_ts.find_tables(root, files) + tables
296
+ if "go" in per_language:
297
+ from . import orm_go_run # xorm and GORM model structs
298
+ tables = orm_go_run.tables() + tables
299
+ if "java" in per_language or "rust" in per_language:
300
+ from . import orm_tables # JPA entity mappings, Diesel `table!` schemas
301
+ tables = orm_tables.find_tables() + tables
302
+ for lang in LIBRARY_LANGUAGES: # ActiveRecord schema.rb / migrations, Ecto schemas, MyBatis result maps
303
+ if lang in per_language:
304
+ module = importlib.import_module(f"codecop.discover.{MODULE_BY_LANG.get(lang, lang)}")
305
+ tables = list(getattr(module, "tables", list)()) + tables
306
+
307
+ if progress:
308
+ progress(f"analysing {len(raw)} SQL sites")
309
+ tell("phase", "Analysing SQL", phase="analyse", sites=len(raw), tables_defined=len(tables))
310
+ # The words of a DDL statement alone ("ALTER TABLE ", a fragment a name is appended to) are not a statement.
311
+ raw = [r for r in raw if not (r.sql is not None and r.kind != "sql_file" and BARE_DDL.match(r.sql))]
312
+
313
+ # `@@table_name@@`, `{{.Table}}`, `${table}` in SQL: a table name some template fills in. Where the repository
314
+ # says which table (a definition or a constant by that name), the name is used; otherwise the token becomes
315
+ # a run-time part, so the statement still parses and the site still names what it reads.
316
+ known_names = {t.name.split(".")[-1] for t in tables if t.name_basis != "unresolved"}
317
+ for r in renames:
318
+ if r["kind"] == "table":
319
+ known_names.add(r["to"].split(".")[-1])
320
+
321
+ def table_for(candidates: list[str]) -> str | None:
322
+ for c in candidates:
323
+ if c in known_names:
324
+ return c
325
+ for c in candidates:
326
+ values = name_consts.get(c) or name_consts.get(c.upper())
327
+ if values and len(values) == 1:
328
+ return next(iter(values))
329
+ return None
330
+
331
+ # The same text reaches many sites (a query per branch, per caller, per ORM call): each is parsed once.
332
+ analysis_memo: dict[tuple, object] = {}
333
+
334
+ def analyze(sql: str, engine_hint: str = "", in_loop: bool = False):
335
+ key = (sql, engine_hint, in_loop)
336
+ got = analysis_memo.get(key)
337
+ if got is None:
338
+ got = analysis_memo[key] = analyze_sql(sql, engine_hint, in_loop)
339
+ return replace(got, tables=list(got.tables), ctes=list(got.ctes), flags=list(got.flags))
340
+
341
+ analysed = []
342
+ template_tables: dict[int, dict[str, str]] = {}
343
+ for r in raw:
344
+ if r.sql is None:
345
+ analysed.append((r, None))
346
+ continue
347
+ info = analyze(r.sql, r.engine_hint, r.in_loop)
348
+ if (not info.parse_ok or not info.tables) and has_template_tokens(r.sql):
349
+ rewritten, resolved = resolve_template_tokens(r.sql, table_for)
350
+ again = analyze(rewritten, r.engine_hint, r.in_loop)
351
+ # only when it makes the site better: it parses now, or it names its tables now
352
+ if again.tables and ((again.parse_ok and not info.parse_ok) or not info.tables):
353
+ r.sql, info = rewritten, again
354
+ if resolved:
355
+ template_tables[id(r)] = resolved
356
+ info.engine, info.engine_basis = _outside_evidence(r, info.engine, info.engine_basis)
357
+ if info.engine_basis == "hint" and (r.engine_evidence or {}).get("basis"):
358
+ info.engine_basis = r.engine_evidence["basis"] # the handle's type or source, or the package (engine_go)
359
+ if r.resolution == "orm" and r.engine_hint and info.engine_basis != "receiver":
360
+ info.engine, info.engine_basis = r.engine_hint, "hint" # the ORM's schema names the engine; the text is synthesised
361
+ analysed.append((r, info))
362
+ # A query assembled from fragments names a CTE that a sibling fragment defines. Such a name is
363
+ # dropped when a statement in the same directory defines it and no table definition has it.
364
+ defined = {t.name.split(".")[-1] for t in tables}
365
+ dir_ctes: dict[str, set[str]] = {}
366
+ live = [(r, info) for r, info in analysed if id(r) not in ghosts]
367
+ for r, info in live:
368
+ if info is not None and info.ctes:
369
+ dir_ctes.setdefault(r.file.rpartition("/")[0], set()).update(info.ctes)
370
+ for r, info in live:
371
+ local = dir_ctes.get(r.file.rpartition("/")[0]) if info is not None else None
372
+ if local:
373
+ info.tables = [t for t in info.tables if "." in t or t not in local or t in defined]
374
+ referenced = {t.split(".")[-1] for _, info in live if info is not None for t in info.tables}
375
+ app_reads = {t.split(".")[-1] for r, info in live if info is not None and not r.is_test and info.kind in ("select", "insert", "update", "delete")
376
+ for t in info.tables}
377
+ tables = schema_mod.merge_tables(tables, referenced, renames, index_defs, added_columns, app_reads=app_reads)
378
+ # `ENGINE=InnoDB` is a MySQL storage engine, not a ClickHouse table engine
379
+ not_ch = ("innodb", "myisam", "aria", "ndb", "ndbcluster", "tokudb")
380
+ ch_tables = {t.name.split(".")[-1] for t in tables if t.engine and t.engine.lower() not in not_ch}
381
+ plain_tables = {t.name.split(".")[-1] for t in tables if not t.engine or t.engine.lower() in not_ch} - ch_tables
382
+ # for the project-wide inference below, a table that only test code defines says nothing
383
+ app_plain_tables = {t.name.split(".")[-1] for t in tables
384
+ if (not t.engine or t.engine.lower() in not_ch) and not t.test_only} - ch_tables
385
+
386
+ sites = []
387
+ seen_ids: Counter[str] = Counter()
388
+ seen_stable: Counter[str] = Counter()
389
+ earlier_ids: dict[int, list[str]] = {} # id(replacement) -> the ids of the sites it stands in for
390
+ rec_of: dict[int, dict] = {}
391
+ for r, info in analysed:
392
+ rec = asdict(r)
393
+ if rec.get("orm") is None:
394
+ rec.pop("orm", None) # only sites synthesised from an ORM call carry it
395
+ hint = rec.pop("engine_hint")
396
+ site_ev = rec.pop("engine_evidence", None) or {}
397
+ id_from = rec["orm"].pop("id_from", None) if rec.get("orm") else None
398
+ if not rec.get("orm"):
399
+ rec.pop("orm", None)
400
+ if info is None:
401
+ engine, basis = _outside_evidence(r, hint, "hint" if hint else "")
402
+ if basis == "hint" and site_ev.get("basis"):
403
+ basis = site_ev["basis"]
404
+ rec.update(id="", statement="unknown", tables=[], flags=["in_loop"] if r.in_loop else [], engine=engine,
405
+ engine_basis=basis, parse_ok=False, sql_hash="")
406
+ base_id = stable = fingerprint(r.expr, r.file, r.symbol)
407
+ else:
408
+ names = {t.split(".")[-1] for t in info.tables}
409
+ # an ORM site whose library names its engine keeps it: its tables may share a name with a ClickHouse mirror
410
+ if info.engine_basis != "sql" and names and not ((r.resolution == "orm" or r.orm) and r.engine_hint):
411
+ # a table defined for ClickHouse decides, unless the statement is written in syntax ClickHouse
412
+ # does not have (a SQLite mirror of a ClickHouse table upserts with ON CONFLICT)
413
+ if names & ch_tables and not NOT_CLICKHOUSE.search(r.sql):
414
+ info.engine, info.engine_basis = "clickhouse", "table"
415
+ elif names <= plain_tables and info.engine == "clickhouse":
416
+ info.engine, info.engine_basis = "", "table"
417
+ rec.update(statement=info.kind, tables=info.tables, writes=[w for w in write_targets(r.sql) if w in info.tables],
418
+ flags=info.flags, engine=info.engine,
419
+ engine_basis=info.engine_basis, parse_ok=info.parse_ok, sql_hash=info.sql_hash)
420
+ if id(r) in template_tables:
421
+ rec["template_tables"] = template_tables[id(r)]
422
+ base_id = fingerprint(info.sql_hash, r.file, r.symbol)
423
+ stable = fingerprint("text:" + info.text_hash, r.file, r.symbol)
424
+ if id_from: # a site that existed before its text was translated to SQL keeps the ids it had
425
+ was = analyze(id_from[0], id_from[1], r.in_loop)
426
+ base_id = fingerprint(was.sql_hash, r.file, r.symbol)
427
+ stable = fingerprint("text:" + was.text_hash, r.file, r.symbol)
428
+ if site_ev.get("detail") and rec["engine_basis"] in ("handle", "package"):
429
+ rec["engine_detail"] = site_ev["detail"]
430
+ if site_ev.get("unsure") and not rec["engine"]:
431
+ rec["engine_unsure"] = site_ev["unsure"]
432
+ # the engines its file or package opens: a project-wide engine that is not one of them is not applied
433
+ if site_ev.get("engines"):
434
+ rec["engine_candidates"] = site_ev["engines"]
435
+ if site_ev.get("binds"):
436
+ rec["binds"] = site_ev["binds"] # `?` placeholders and no library that rewrites them (Go)
437
+ seen_ids[base_id] += 1
438
+ rec["id"] = base_id if seen_ids[base_id] == 1 else f"{base_id}-{seen_ids[base_id]}"
439
+ # `id` is built on the SQL as written in the engine's dialect, so it moves when the engine label is
440
+ # corrected. `stable_id` is built on the text alone and does not: a comparison of two scans can fall
441
+ # back to it for a site whose `id` is gone.
442
+ seen_stable[stable] += 1
443
+ rec["stable_id"] = stable if seen_stable[stable] == 1 else f"{stable}-{seen_stable[stable]}"
444
+ if id(r) in ghosts:
445
+ winner = ghosts[id(r)]
446
+ while id(winner) in ghosts:
447
+ winner = ghosts[id(winner)]
448
+ earlier_ids.setdefault(id(winner), []).extend(dict.fromkeys((rec["id"], rec["stable_id"])))
449
+ continue
450
+ rec_of[id(r)] = rec
451
+ sites.append(rec)
452
+ for key, ids in earlier_ids.items():
453
+ if key in rec_of:
454
+ # what an earlier version, or the raw-string extractor alone, called this call: a comparison of two
455
+ # scans pairs an old site with the new one whose `previous_ids` holds the old `id` or `stable_id`
456
+ rec_of[key]["previous_ids"] = list(dict.fromkeys(ids))
457
+ if "go" in per_language:
458
+ from . import named_go # sqlc, goyesql: the statement in the .sql file and the Go call that sends it are one site
459
+ sites, named = named_go.link(sites)
460
+ if named:
461
+ extras["named_queries"] = named
462
+ # a .sql file that code embeds (include_str!, go:embed, sqlc) is reported at the code site, not twice
463
+ embedded = {s["sql_hash"] for s in sites if s["kind"] != "sql_file" and s["sql_hash"]}
464
+ sites = [s for s in sites if not (s["kind"] == "sql_file" and s["sql_hash"] in embedded)]
465
+ sites.sort(key=lambda s: (s["file"], s["line"]))
466
+ engine_default = _apply_default_engine(sites, evidence, default_engine, app_plain_tables)
467
+ if progress:
468
+ progress("origins and roles")
469
+ tell("phase", "Tracing entry points", phase="origins", sites=len(sites),
470
+ by_engine=dict(Counter(s["engine"] or "unknown" for s in sites).most_common()))
471
+ # adds role, role_basis, origins, origin_count; its limits are the `[discover.origins]` table (or the same
472
+ # keys directly under `[discover]`)
473
+ origin_settings = {**{k: v for k, v in (settings or {}).items() if not isinstance(v, (dict, list))},
474
+ **((settings or {}).get("origins") or {})}
475
+ # the call sites of the other kinds of finding (kinds/): found by each kind, traced with the query sites (entry points,
476
+ # request path, loops), kept apart under `kinds` (`kinds`: the selected names; None: every kind on by default)
477
+ from ..kinds import pipeline as kinds_pipeline
478
+ kind_raw = kinds_pipeline.raw_sites(root, by_lang, kinds, kind_settings, log=progress)
479
+ proxies = kinds_pipeline.trace_proxies(kind_raw, is_test_path)
480
+ origin_info = origins.annotate(root, by_lang, sites, progress, settings=origin_settings, extra=proxies)
481
+ kinds_pipeline.take_trace(proxies)
482
+
483
+ wrapper_counts = Counter(
484
+ s["sink"].split("(")[0].split(".")[-1] for s in sites
485
+ if s["kind"] == "call" and not s["known_sink"] and s["sink"] and not s["is_test"]
486
+ )
487
+ skipped_files = [{"file": os.path.relpath(path, root), "bytes": size} for path, size in sorted(READ.skipped.items())]
488
+ summary = summarize(sites, tables, time.monotonic() - started, files_total, skipped_languages)
489
+ summary.update(files_tracked=len(files), source_files=files_total, text_files_read=files_read,
490
+ max_file_bytes=READ.max_file_bytes, files_skipped_too_large=len(skipped_files),
491
+ engine_default={k: v for k, v in engine_default.items() if k != "evidence"})
492
+ # coverage (coverage.repository): how each site's SQL comes to exist, and the sites only the library probes find
493
+ from .. import mechanism
494
+ from . import probes as probes_mod
495
+ mechanism.annotate(sites, root)
496
+ _mark_pass_through(sites)
497
+ _mark_search_store(sites, root)
498
+ probed = probes_mod.missed(root, sites) if (settings or {}).get("probes", True) is not False else None
499
+ return {
500
+ **({"probes": probed} if probed is not None else {}),
501
+ "schema_version": SCHEMA_VERSION,
502
+ "tool_version": __version__,
503
+ "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
504
+ "repo": {"name": root.name, "root": str(root), **git_info(root)},
505
+ "summary": {**summary, "origins": origin_info["summary"], **extras},
506
+ "version_evidence": versions,
507
+ "engine_evidence": engine_default["evidence"],
508
+ "skipped_files": skipped_files,
509
+ "suggested_wrappers": [{"name": n, "sites": c} for n, c in wrapper_counts.most_common(15) if c >= 3],
510
+ "tables": [t.to_dict() for t in tables],
511
+ **({"kinds": kinds_pipeline.inventory_section(kind_raw)} if kind_raw else {}),
512
+ # PostgreSQL functions the repository's .sql files define in plain SQL (LANGUAGE sql): the sandbox creates the
513
+ # ones a candidate calls (definitions.complete), the last definition of a name winning
514
+ "sql_functions": schema_mod.last_functions(sql_functions),
515
+ "entry_points": origin_info["entry_points"],
516
+ "areas": origin_info["areas"],
517
+ "call_sites": sites,
518
+ }
519
+
520
+
521
+ def _apply_default_engine(sites: list[dict], evidence: "dialect.Evidence", configured: str | None, plain_tables: set[str]) -> dict:
522
+ """Give an engine to the statements nothing decided, and say on each one that it was not a per-statement guess.
523
+
524
+ In order: the file's other statements (all of those with direct evidence agree), then the project's engine:
525
+ `default` when configured, `inferred` when the project's drivers and configuration name one engine. In a
526
+ project with ClickHouse and one other server engine, a statement whose tables are all defined as plain SQL
527
+ tables belongs to the other engine. `engine_scope` on a site is file | tables | project."""
528
+ schema_dialect = Counter(
529
+ s["engine"] for s in sites
530
+ if not s["is_test"] and s["engine"] and s["engine_basis"] == "sql" and (s["kind"] == "sql_file" or s["statement"] == "ddl"))
531
+ by_file: dict[str, Counter] = {}
532
+ usage: Counter = Counter() # application statements whose engine has direct evidence
533
+ for s in sites:
534
+ if s["engine"] and s["engine"] not in NON_SQL and s["engine_basis"] in DIRECT_BASES and s["resolution"] != "orm":
535
+ # (an ORM call says which engine the ORM talks to, not where the raw strings of its file go)
536
+ by_file.setdefault(s["file"], Counter())[s["engine"]] += 1
537
+ if not s["is_test"]:
538
+ usage[s["engine"]] += 1
539
+ inferred, reason = dialect.infer(evidence, dict(schema_dialect), dict(usage))
540
+ engine = configured or inferred
541
+ basis = "default" if configured else ("inferred" if inferred else "")
542
+ drivers = dialect.stores(evidence, dict(usage))
543
+ other = next(iter(drivers - {"clickhouse"})) if "clickhouse" in drivers and len(drivers) == 2 else ""
544
+ counts: Counter = Counter()
545
+
546
+ def refused(s: dict, engine: str) -> bool:
547
+ """A project-wide engine is not given to a statement whose own evidence speaks against it: one whose handle's
548
+ evidence names engines and not this one (`engine_candidates`: the package opens SQLite and MySQL, or SQLite only
549
+ through the packages it uses), or one written with `?` placeholders for PostgreSQL (Go). A package that opens two
550
+ engines, one of them this one, runs the statement on either: the project's choice stands."""
551
+ if engine == "postgres" and s.get("binds") == "qmark":
552
+ return True
553
+ if s.get("engine_candidates"):
554
+ return engine not in s["engine_candidates"]
555
+ return bool(s.get("engine_unsure"))
556
+ for s in sites:
557
+ if s["engine"] or s["sql"] is None:
558
+ continue
559
+ near = by_file.get(s["file"])
560
+ names = {t.split(".")[-1] for t in s["tables"]}
561
+ if near and len(near) == 1 and sum(near.values()) >= 2 and s["kind"] != "sql_file":
562
+ if s.get("binds") == "qmark" and next(iter(near)) == "postgres":
563
+ continue
564
+ s["engine"], s["engine_basis"], s["engine_scope"] = next(iter(near)), "inferred", "file"
565
+ elif not configured and refused(s, engine or other):
566
+ continue
567
+ elif not configured and other and names and names <= plain_tables:
568
+ s["engine"], s["engine_basis"], s["engine_scope"] = other, "inferred", "tables"
569
+ elif engine:
570
+ s["engine"], s["engine_basis"], s["engine_scope"] = engine, basis, "project"
571
+ else:
572
+ continue
573
+ if not s["is_test"]:
574
+ counts[s["engine_scope"]] += 1
575
+ # No single engine: the project ships drivers for several. A statement with no dialect of its own (every
576
+ # statement an ORM writes, and a raw string no evidence places) is sent to whichever engine is configured,
577
+ # so it is read as the one the project's own settings favour, and says so: basis `project_choice` with the
578
+ # alternatives when there are several, `inferred` (scope `orm`) when ClickHouse is the only other store.
579
+ # With ClickHouse among the stores only an ORM's statements are placed: a raw string may be for either.
580
+ choice: dict = {}
581
+ if not engine:
582
+ choice = dialect.choose(evidence, dict(usage))
583
+ chosen, alternatives = choice["engine"], choice["alternatives"]
584
+ manifest_dirs: dict[str, set[str]] = {}
585
+ for e, by in evidence.found.items():
586
+ for f in by.get("driver") or ():
587
+ manifest_dirs.setdefault(os.path.dirname(f), set()).add(e)
588
+
589
+ def package_drivers(rel: str) -> set[str]:
590
+ """The drivers of the nearest manifest above a file that names any (the whole project's when none does)."""
591
+ best = None
592
+ for d in manifest_dirs:
593
+ if (not d or rel.startswith(d + "/")) and (best is None or len(d) > len(best)):
594
+ best = d
595
+ return manifest_dirs.get(best, set()) if best is not None else set(drivers)
596
+ placed: Counter = Counter()
597
+ for s in sites:
598
+ if s["engine"] or s["sql"] is None or not chosen:
599
+ continue
600
+ library = (s.get("orm") or {}).get("library", "")
601
+ is_orm = s["resolution"] == "orm" or bool(library)
602
+ if "clickhouse" in drivers and (not is_orm or library in dialect.BUILDERS) and \
603
+ "clickhouse" in package_drivers(s["file"]):
604
+ continue # (a package whose own manifest has no ClickHouse driver sends its raw strings elsewhere)
605
+ if s["kind"] == "sql_file": # a .sql file is written for one engine; which one is not the project's choice to make
606
+ continue
607
+ if refused(s, chosen):
608
+ placed["refused"] += 1
609
+ continue
610
+ if alternatives:
611
+ s["engine"], s["engine_basis"], s["engine_scope"] = chosen, "project_choice", "project"
612
+ s["engine_alternatives"] = list(alternatives)
613
+ elif is_orm:
614
+ s["engine"], s["engine_basis"], s["engine_scope"] = chosen, "inferred", "orm"
615
+ else:
616
+ continue
617
+ if not s["is_test"]:
618
+ placed["orm_sites" if is_orm else "raw_sites"] += 1
619
+ choice = {**choice, "basis": ("project_choice" if alternatives else "inferred") if chosen else "",
620
+ "sites": placed["orm_sites"] + placed["raw_sites"], "orm_sites": placed["orm_sites"], "raw_sites": placed["raw_sites"],
621
+ "refused_sites": placed["refused"],
622
+ "how_to_choose": "pass --default-engine, or set default_engine under [discover] in codecop.toml"}
623
+ return {
624
+ "engine": engine, "basis": basis,
625
+ "reason": "set in codecop.toml or --default-engine" if configured else reason,
626
+ "sites": counts.get("project", 0), "sites_from_file": counts.get("file", 0),
627
+ "sites_from_tables": counts.get("tables", 0),
628
+ "choice": choice,
629
+ "evidence": evidence.to_dict(),
630
+ }
631
+
632
+
633
+ SEARCH_CLIENT = re.compile(r"\borg\.opensearch\b|\bco\.elastic\b|\borg\.elasticsearch\b|@elastic/elasticsearch|@opensearch-project|"
634
+ r"^\s*(?:from|import)\s+(?:elasticsearch|opensearchpy)\b|olivere/elastic|elastic/go-elasticsearch|opensearch-go",
635
+ re.M)
636
+
637
+
638
+ # client-side data fetching libraries: `queryClient.query(..)` / `.fetchQuery(..)` is an HTTP request cache, not SQL
639
+ CACHE_CLIENT = re.compile(r"""['"]@tanstack/(?:react|vue|solid|svelte|angular)-query(?:-\w+)?['"]|['"]react-query['"]|['"]@apollo/client['"]""")
640
+
641
+
642
+ def _mark_search_store(sites: list[dict], root: Path) -> None:
643
+ """A call with no SQL text in a file that uses an Elasticsearch / OpenSearch client (`qs.query(..)`,
644
+ `client.search(..)`) sends a search request, not SQL: `other_store = "search"`; one in a file using a client-side
645
+ query cache (`queryClient.query(..)` of TanStack Query) is an HTTP request. Coverage leaves both out of D."""
646
+ seen: dict[str, str] = {}
647
+ for s in sites:
648
+ if s.get("sql") or s.get("resolution") == "orm":
649
+ continue
650
+ f = s.get("file") or ""
651
+ if f not in seen:
652
+ try:
653
+ text = (root / f).read_text(errors="ignore")[:400_000]
654
+ seen[f] = ("search" if SEARCH_CLIENT.search(text) else "http_query_cache" if CACHE_CLIENT.search(text) else "")
655
+ except OSError:
656
+ seen[f] = ""
657
+ if seen[f]:
658
+ s["other_store"] = seen[f]
659
+
660
+
661
+ def _mark_pass_through(sites: list[dict]) -> None:
662
+ """A wrapper's own sink call (`func runQuery(sql) { db.Query(sql) }`, `def execute(self, query): conn.execute(query)`)
663
+ holds no statement: its callers do, and discovery resolved them through it as sites of their own. Such a site gets
664
+ `pass_through` = the number of caller sites with text, so coverage counts the statements once, at the callers."""
665
+ callers: Counter = Counter()
666
+ for s in sites:
667
+ if s.get("is_test") or s.get("resolution") == "parameter" or not s.get("sql"):
668
+ continue
669
+ sink = re.split(r"[.:]", (s.get("sink") or "").split("(")[0].split("<")[0])[-1]
670
+ if sink:
671
+ callers[sink] += 1
672
+ for s in sites:
673
+ if s.get("resolution") != "parameter" or s.get("sql"):
674
+ continue
675
+ name = re.split(r"[.:]", re.sub(r"^\(\*?\w+\)\.", "", s.get("symbol") or ""))[-1]
676
+ if name and callers.get(name):
677
+ s["pass_through"] = callers[name]
678
+
679
+
680
+ def summarize(sites: list[dict], tables: list, seconds: float, n_files: int, skipped: list[str]) -> dict:
681
+ app = [s for s in sites if not s["is_test"]]
682
+
683
+ def count(key: str, rows: list[dict]) -> dict:
684
+ return dict(Counter(s[key] or "unknown" for s in rows).most_common())
685
+
686
+ flags = Counter(f for s in app for f in s["flags"])
687
+ return {
688
+ "files_scanned": n_files, # source files in a language with an extractor: the files searched for SQL
689
+ "seconds": round(seconds, 1),
690
+ "sites": len(sites),
691
+ "sites_in_tests": len(sites) - len(app),
692
+ "by_engine": count("engine", app),
693
+ "by_engine_basis": count("engine_basis", app),
694
+ "by_statement": count("statement", app),
695
+ "by_resolution": count("resolution", app),
696
+ "by_language": count("language", app),
697
+ "by_kind": count("kind", app),
698
+ "flags": dict(flags.most_common()),
699
+ "tables_defined": len(tables),
700
+ "tables_defined_in_tests_only": sum(1 for t in tables if getattr(t, "test_only", False)),
701
+ "languages_without_extractor": skipped,
702
+ }