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,320 @@
1
+ """Which database a Go call sends its statement to, from where its handle comes from.
2
+
3
+ `db.QueryContext(ctx, q)` names no engine. What does is the handle `db`: its type (`*sqlstore.DB`, declared in a package
4
+ that opens `github.com/mattn/go-sqlite3` and nothing else), the struct field it is read from, the method that returns
5
+ it (`s.store.DB()` of a store package that opens SQLite), the `sql.Open("sqlite3", ...)` it was assigned from, or,
6
+ for a `*sql.DB` parameter, what every caller in the repository passes for it. A package whose files open one engine
7
+ and nothing else speaks for the calls in it whose handle says nothing.
8
+
9
+ Evidence that names two engines decides nothing: the call keeps no engine, and the project's default is not applied
10
+ to it either (`unsure`). Nothing here runs the Go type checker (orm_go_types.Types reads declarations)."""
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from collections import defaultdict
16
+
17
+ from tree_sitter import Node
18
+
19
+ from .base import receiver_engine
20
+ from .go import FUNC_DECL, GoFile, _strip_parens, _txt, call_args, callee_name, param_names
21
+
22
+ # database/sql driver names, as `sql.Open` takes them
23
+ DRIVER_NAMES = {"sqlite3": "sqlite", "sqlite": "sqlite", "libsql": "sqlite", "postgres": "postgres", "pgx": "postgres",
24
+ "pgx/v5": "postgres", "postgresql": "postgres", "cloudsqlpostgres": "postgres", "mysql": "mysql",
25
+ "clickhouse": "clickhouse", "chhttp": "clickhouse", "sqlserver": "mssql", "mssql": "mssql", "oracle": "oracle",
26
+ "godror": "oracle"}
27
+ OPENERS = {"Open", "OpenDB", "Connect", "MustConnect", "MustOpen", "ConnectContext"}
28
+ # Libraries that rewrite `?` into the driver's own placeholders: in their packages `?` says nothing about the engine.
29
+ REBINDERS = ("github.com/jmoiron/sqlx", "gorm.io/gorm", "github.com/jinzhu/gorm", "github.com/uptrace/bun", "xorm.io/xorm",
30
+ "github.com/go-xorm/xorm", "github.com/Masterminds/squirrel", "github.com/doug-martin/goqu", "github.com/huandu/go-sqlbuilder",
31
+ "github.com/volatiletech/sqlboiler")
32
+ # How many callers deep a `*sql.DB` parameter is followed. A setting: `[discover] go_handle_depth`.
33
+ DEFAULT_DEPTH = 3
34
+ DEPTH = DEFAULT_DEPTH
35
+ # A `?` that stands where a value goes: after a comparison, an opening parenthesis, a comma, or a keyword that takes a value.
36
+ QMARK = re.compile(r"(?:[=<>(,+\-*/]|\b(?:IN|LIKE|ILIKE|LIMIT|OFFSET|BETWEEN|AND|THEN|ELSE|WHEN|VALUES|SET|IS|NOT|GLOB))\s*\?(?![?|&])", re.I)
37
+ DOLLAR = re.compile(r"\$\d+")
38
+ # a struct field that holds a database handle
39
+ HANDLE_FIELD = re.compile(r"\*?\b(?:sql|sqlx|pgxpool|pgx|pgconn)\.(?:DB|Tx|Conn|Pool|Stmt)\b")
40
+
41
+
42
+ def qmark_binds(sql: str | None) -> bool:
43
+ """The statement takes its values as `?` placeholders (outside string literals) and has no `$1`: no PostgreSQL
44
+ driver for database/sql (lib/pq, pgx) accepts it."""
45
+ if not sql or "?" not in sql:
46
+ return False
47
+ text = re.sub(r"'(?:[^']|'')*'", "''", sql)
48
+ return bool(QMARK.search(text)) and not DOLLAR.search(text)
49
+
50
+
51
+ class Handles:
52
+ """The engine of a call's handle, per call; built once per run (go.Ctx.handles)."""
53
+
54
+ def __init__(self, ctx):
55
+ self.ctx = ctx
56
+ self._types = None
57
+ self._drivers: dict[str, set[str]] = {}
58
+ self._package: dict[str, tuple[str, str]] = {}
59
+ self._package_sets: dict[str, set[str]] = {}
60
+ self._app_drivers: dict[str, set[str]] = {}
61
+ self._rebinds: dict[str, bool] = {}
62
+ self._callers: dict[str, list[tuple[GoFile, Node]]] | None = None
63
+ self._busy: set = set()
64
+ self._memo: dict = {}
65
+
66
+ @property
67
+ def types(self):
68
+ if self._types is None:
69
+ from .orm_go_types import Types
70
+ self._types = Types(self.ctx)
71
+ return self._types
72
+
73
+ # ---- packages --------------------------------------------------------------------------
74
+ def drivers(self, dir: str) -> set[str]:
75
+ """The engines the package's own files open: driver imports and `sql.Open("<driver>", ...)` names."""
76
+ got = self._drivers.get(dir)
77
+ if got is not None:
78
+ return got
79
+ def opened_by(group) -> set[str]:
80
+ out: set[str] = set()
81
+ for gf in group:
82
+ out |= gf.engines
83
+ for call in gf.calls:
84
+ eng = self.opened(gf, call)
85
+ if eng:
86
+ out.add(eng)
87
+ return out
88
+ files = self.ctx.dir_files.get(dir, ())
89
+ # A test's driver is not the package's when the package's own files open one. When they open none, the
90
+ # tests that open one run the package's statements on it: that engine is the evidence there is (for this
91
+ # package's own calls only: app_drivers is what other packages are judged by).
92
+ app = opened_by([gf for gf in files if not gf.test])
93
+ self._app_drivers[dir] = app
94
+ got = app or opened_by([gf for gf in files if gf.test])
95
+ self._drivers[dir] = got
96
+ return got
97
+
98
+ def app_drivers(self, dir: str) -> set[str]:
99
+ """The engines the package's application files (not its tests) open."""
100
+ self.drivers(dir)
101
+ return self._app_drivers.get(dir, set())
102
+
103
+ def is_handle_type(self, dir: str, name: str) -> bool:
104
+ """A type of that package that holds a database handle: a struct with a field (or an embedded one) of a
105
+ database/sql, sqlx or pgx handle type, or of another such type of the package."""
106
+ hit = self.types.decls.get(dir, {}).get(name)
107
+ if hit is None:
108
+ return False
109
+ gf, spec = hit
110
+ typ = spec.child_by_field_name("type")
111
+ if typ is None or typ.type != "struct_type":
112
+ return False
113
+ text = gf.src[typ.start_byte:typ.end_byte].decode("utf-8", "replace")
114
+ return bool(HANDLE_FIELD.search(text))
115
+
116
+ def opened(self, gf: GoFile, call: Node) -> str:
117
+ """`sql.Open("sqlite3", dsn)`, `sqlx.Connect("postgres", dsn)`: the engine the driver name stands for."""
118
+ name, recv, _ = callee_name(call.child_by_field_name("function"))
119
+ if name not in OPENERS or recv is None or recv.type != "identifier":
120
+ return ""
121
+ path = gf.imports.get(_txt(recv), "")
122
+ if path not in ("database/sql", "github.com/jmoiron/sqlx"):
123
+ return ""
124
+ args = call_args(call)
125
+ if not args or args[0].type not in ("interpreted_string_literal", "raw_string_literal"):
126
+ return ""
127
+ return DRIVER_NAMES.get(_txt(args[0]).strip("\"`").lower(), "")
128
+
129
+ def package(self, dir: str) -> tuple[str, str]:
130
+ """(engine, unsure) for the calls of a package whose handle says nothing.
131
+
132
+ The package's own drivers when they name one engine. A package that opens none speaks through the local
133
+ packages it imports that do (`common/graph` imports `common/sqlstore`, which opens SQLite only). Two engines:
134
+ ("", "the package opens postgres and sqlite")."""
135
+ if dir in self._package:
136
+ return self._package[dir]
137
+ own = {e for e in self.drivers(dir) if e}
138
+ via: set[str] = set()
139
+ if not own:
140
+ # a local package that opens one engine counts only when this package declares a parameter or a field of
141
+ # one of its types (`db *sqlstore.DB`): importing it for anything else says nothing about these calls
142
+ for gf in self.ctx.dir_files.get(dir, ()):
143
+ if gf.test:
144
+ continue
145
+ text = gf.src.decode("utf-8", "replace")
146
+ for alias, path in gf.imports.items():
147
+ target = self.ctx.import_dir(gf.dir, path)
148
+ if target is None or target == dir:
149
+ continue
150
+ engines = {e for e in self.app_drivers(target) if e}
151
+ if not engines:
152
+ continue
153
+ used = {m.group(1) for m in re.finditer(rf"\b\w+\s+\*?{re.escape(alias)}\.([A-Z]\w*)\b", text)}
154
+ if any(self.is_handle_type(target, u) for u in used):
155
+ via |= engines
156
+ found = own or via
157
+ self._package_sets[dir] = found
158
+ if len(found) == 1:
159
+ out = (next(iter(found)), "")
160
+ elif found:
161
+ out = ("", f"the package {'opens' if own else 'imports packages that open'} {' and '.join(sorted(found))}")
162
+ else:
163
+ out = ("", "")
164
+ self._package[dir] = out
165
+ return out
166
+
167
+ def package_engines(self, dir: str) -> set[str]:
168
+ """Every engine the package's evidence names (package())."""
169
+ self.package(dir)
170
+ return set(self._package_sets.get(dir, set()))
171
+
172
+ # ---- values ----------------------------------------------------------------------------
173
+ def type_engine(self, ref) -> tuple[str, str]:
174
+ """(engine, how) of a handle type: a driver's own type, or a type declared in a package that opens one engine."""
175
+ if ref is None:
176
+ return "", ""
177
+ t = self.types
178
+ key = t.named(ref)
179
+ if key is not None:
180
+ got = {e for e in self.drivers(key[0]) if e}
181
+ if len(got) == 1:
182
+ return next(iter(got)), f"type {key[1]} of {key[0]}, which opens {next(iter(got))}"
183
+ return "", ""
184
+ ext = t.external(ref)
185
+ if ext is not None:
186
+ eng = self.ctx.import_engine(ext[0])
187
+ if eng:
188
+ return eng, f"type {ext[1]} of {ext[0]}"
189
+ return "", ""
190
+
191
+ def value(self, gf: GoFile, node: Node | None, at: Node, depth: int = 0) -> tuple[str, str]:
192
+ """(engine, how) of a handle expression; ("", "") when nothing about it names one."""
193
+ node = _strip_parens(node)
194
+ if node is None or depth > DEPTH + 6:
195
+ return "", ""
196
+ key = (gf.rel, node.id, at.id)
197
+ if key in self._memo:
198
+ return self._memo[key]
199
+ if key in self._busy:
200
+ return "", ""
201
+ self._busy.add(key)
202
+ try:
203
+ out = self._value(gf, node, at, depth)
204
+ finally:
205
+ self._busy.discard(key)
206
+ self._memo[key] = out
207
+ return out
208
+
209
+ def _value(self, gf: GoFile, node: Node, at: Node, depth: int) -> tuple[str, str]:
210
+ text = _txt(node)
211
+ named = receiver_engine(text + ".x") if len(text) < 80 else ""
212
+ if named:
213
+ return named, f"the handle is named {text}"
214
+ eng, how = self.type_engine(self.types.type_of(gf, node, at))
215
+ if eng:
216
+ return eng, how
217
+ if node.type == "call_expression":
218
+ opened = self.opened(gf, node)
219
+ if opened:
220
+ return opened, f"opened as {opened}"
221
+ fn = node.child_by_field_name("function")
222
+ _name, recv, _ = callee_name(fn)
223
+ if recv is not None: # `s.store.DB()`: the handle a store's method returns is that store's
224
+ eng, how = self.value(gf, recv, at, depth + 1)
225
+ if eng:
226
+ return eng, how
227
+ hit = self.types.callee(gf, node, at)
228
+ if hit is not None:
229
+ got = {e for e in self.drivers(hit[0].dir) if e}
230
+ if len(got) == 1:
231
+ return next(iter(got)), f"returned by {_name} of {hit[0].dir}, which opens {next(iter(got))}"
232
+ return "", ""
233
+ if node.type == "selector_expression":
234
+ operand = node.child_by_field_name("operand")
235
+ if operand is not None and not (operand.type == "identifier" and _txt(operand) in gf.imports):
236
+ ref = self.types.type_of(gf, operand, at)
237
+ eng, how = self.type_engine(ref)
238
+ if eng:
239
+ return eng, how
240
+ return "", ""
241
+ if node.type == "identifier":
242
+ local = gf._local(text, at)
243
+ if local is None:
244
+ return "", ""
245
+ _top, decl, later = local
246
+ if decl.kind == "decl" and decl.value is not None:
247
+ values = [decl.value] + [e.value for e in later if e.kind == "assign" and e.value is not None]
248
+ found = {self.value(gf, v, decl.node, depth + 1) for v in values}
249
+ engines = {e for e, _h in found if e}
250
+ if len(engines) == 1:
251
+ return next(iter(engines)), next(h for e, h in found if e)
252
+ return "", ""
253
+ if decl.kind == "param" and depth < DEPTH:
254
+ return self.callers(gf, decl.node, text, depth)
255
+ return "", ""
256
+
257
+ # ---- callers ---------------------------------------------------------------------------
258
+ def _calls_by_name(self) -> dict[str, list[tuple[GoFile, Node]]]:
259
+ if self._callers is None:
260
+ self._callers = defaultdict(list)
261
+ for gf in self.ctx.files.values():
262
+ if gf.test:
263
+ continue
264
+ for call in gf.calls:
265
+ name = callee_name(call.child_by_field_name("function"))[0]
266
+ if name:
267
+ self._callers[name].append((gf, call))
268
+ return self._callers
269
+
270
+ def callers(self, gf: GoFile, func: Node, param: str, depth: int) -> tuple[str, str]:
271
+ """What the callers of `func` pass for its parameter `param`: one engine when every caller that says one
272
+ says the same."""
273
+ if func.type not in FUNC_DECL:
274
+ return "", ""
275
+ names = param_names(func)
276
+ if param not in names:
277
+ return "", "" # the method's receiver: its type said what it could
278
+ index = names.index(param)
279
+ nm = func.child_by_field_name("name")
280
+ if nm is None:
281
+ return "", ""
282
+ found: dict[str, str] = {}
283
+ for cgf, call in self._calls_by_name().get(_txt(nm), ()):
284
+ hit = self.types.callee(cgf, call, call)
285
+ if hit is None or hit[1].id != func.id or hit[0].rel != gf.rel:
286
+ continue
287
+ args = call_args(call)
288
+ if index >= len(args):
289
+ continue
290
+ eng, how = self.value(cgf, args[index], call, depth + 1)
291
+ if eng:
292
+ found.setdefault(eng, f"{cgf.rel}:{call.start_point[0] + 1} passes {_txt(args[index])[:40]} ({how})")
293
+ if len(found) == 1:
294
+ eng, how = next(iter(found.items()))
295
+ return eng, f"callers pass it: {how}"
296
+ return "", ""
297
+
298
+ # ---- one call ----------------------------------------------------------------------------
299
+ def site(self, gf: GoFile, call: Node) -> tuple[str, str]:
300
+ """(engine, how) of the handle a database call is made on; ("", "") when it says nothing."""
301
+ _name, recv, _ = callee_name(call.child_by_field_name("function"))
302
+ if recv is None or (recv.type == "identifier" and _txt(recv) in gf.imports and gf._local(_txt(recv), call) is None):
303
+ return "", ""
304
+ return self.value(gf, recv, call)
305
+
306
+ def rebinds(self, gf: GoFile) -> bool:
307
+ """Does this file's package use a library that rewrites `?` placeholders for the driver, itself or through a
308
+ local package it imports (a wrapper of xorm or sqlx: `x base.EngineMigration`)?"""
309
+ if gf.dir in self._rebinds:
310
+ return self._rebinds[gf.dir]
311
+
312
+ def uses(dir: str) -> bool:
313
+ return any(p == r or p.startswith(r + "/") for f in self.ctx.dir_files.get(dir, ())
314
+ for p in [*f.imports.values(), *f.side_imports] for r in REBINDERS)
315
+ found = uses(gf.dir)
316
+ if not found:
317
+ targets = {self.ctx.import_dir(f.dir, p) for f in self.ctx.dir_files.get(gf.dir, ()) for p in f.imports.values()}
318
+ found = any(uses(t) for t in targets if t is not None and t != gf.dir)
319
+ self._rebinds[gf.dir] = found
320
+ return found