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,793 @@
1
+ """Ruby: database calls of a Rails application (ActiveRecord) and SQL strings sent through its connection.
2
+
3
+ Read only for the database library (see `discover/__init__.py` LIBRARY_LANGUAGES). Two passes over the parsed files:
4
+ the first collects the models (`orm_rb_activerecord.Models`) and string constants, the second turns every call chain
5
+ that starts at a model, at a local variable bound to one, or at a model's implicit receiver into sites, and every
6
+ `connection.execute/exec_query/select_*` into a SQL string site. `tables()` gives the tables of db/schema.rb, or of
7
+ db/migrate/*.rb when there is no schema.rb (db/structure.sql is read as SQL by discover itself).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import re
14
+ from pathlib import Path
15
+
16
+ from . import orm_stats
17
+ from .base import RawSite, is_test_path, read_text, trim, walk_tree
18
+ from .orm_rb_activerecord import (LIBRARY, NOT_QUERIES, QUERY_METHODS, RUBY_LOADS, TERMINALS, Ctx, Models, Translator,
19
+ Untranslatable, call_parts, const_text, interpolated, make_site, norm, string_text,
20
+ symbol_name, txt)
21
+ from .schema import Table
22
+
23
+ STATS = orm_stats.Stats()
24
+ TABLES: list[Table] = []
25
+ _PARSER = None
26
+
27
+ RUBY_TEST = re.compile(r"(^|/)(spec|test|features)/|_spec\.rb$|_test\.rb$")
28
+ RAW_METHODS = {"execute", "exec_query", "select_all", "select_value", "select_values", "select_rows", "select_one",
29
+ "exec_update", "exec_delete", "exec_insert", "exec_params", "async_exec", "exec"}
30
+ LOOP_METHODS = {"each", "map", "collect", "flat_map", "each_with_index", "each_with_object", "times", "each_slice",
31
+ "find_each", "find_in_batches", "in_batches", "select", "reject", "filter_map", "inject", "reduce", "sum",
32
+ "upto", "downto", "step", "loop", "each_pair", "each_key", "each_value", "each_record", "each_batch",
33
+ "index_with", "index_by", "group_by", "sort_by", "partition", "any?", "all?", "count", "find", "detect",
34
+ "each_cons", "zip", "to_h"}
35
+ STOP = ("method", "singleton_method", "class", "module", "program")
36
+ ADAPTERS = {"postgresql": "postgres", "postgis": "postgres", "mysql2": "mysql", "trilogy": "mysql", "mysql": "mysql",
37
+ "sqlite3": "sqlite", "sqlserver": "mssql"}
38
+
39
+
40
+ def _parser():
41
+ global _PARSER
42
+ if _PARSER is None:
43
+ import tree_sitter_ruby
44
+ from tree_sitter import Language, Parser
45
+ _PARSER = Parser(Language(tree_sitter_ruby.language()))
46
+ return _PARSER
47
+
48
+
49
+ def is_ruby_test(rel: str) -> bool:
50
+ return bool(RUBY_TEST.search(rel)) or is_test_path(rel)
51
+
52
+
53
+ # ---- per file lookups ---------------------------------------------------------------------------------------------
54
+
55
+ class FileScope:
56
+ """Heredoc bodies of a file (tree-sitter puts the body after the line that opens it), local variables of the
57
+ enclosing method, and string constants of the whole repository."""
58
+
59
+ def __init__(self, constants: dict[str, object]) -> None:
60
+ self.constants = constants
61
+ self.heredocs: dict[int, object] = {}
62
+
63
+ def begin(self, root) -> None:
64
+ self.heredocs = {}
65
+ starts, bodies = [], []
66
+ for n in walk_tree(root):
67
+ if n.type == "heredoc_beginning":
68
+ starts.append(n)
69
+ elif n.type == "heredoc_body":
70
+ bodies.append(n)
71
+ for s, b in zip(starts, bodies):
72
+ self.heredocs[s.start_byte] = b
73
+
74
+ def heredoc_body(self, node):
75
+ return self.heredocs.get(node.start_byte)
76
+
77
+ def local_value(self, ident):
78
+ name = txt(ident)
79
+ scope = ident.parent
80
+ while scope is not None and scope.type not in STOP:
81
+ scope = scope.parent
82
+ if scope is None:
83
+ return None
84
+ best = None
85
+ for n in walk_tree(scope, stop=("method", "singleton_method", "class", "module")):
86
+ if n.start_byte >= ident.start_byte:
87
+ break
88
+ if n.type == "assignment":
89
+ left = n.child_by_field_name("left")
90
+ if left is not None and left.type == "identifier" and txt(left) == name:
91
+ best = n.child_by_field_name("right")
92
+ return best
93
+
94
+ def constant_value(self, name: str | None, nesting: list[str]):
95
+ if not name:
96
+ return None
97
+ for i in range(len(nesting), -1, -1):
98
+ full = "::".join(nesting[:i] + [name])
99
+ if full in self.constants:
100
+ return self.constants[full]
101
+ return None
102
+
103
+
104
+ def _nesting(node) -> list[str]:
105
+ out = []
106
+ n = node.parent
107
+ while n is not None:
108
+ if n.type in ("class", "module"):
109
+ c = const_text(n.child_by_field_name("name"))
110
+ if c:
111
+ out.append(c)
112
+ n = n.parent
113
+ return list(reversed(out))
114
+
115
+
116
+ def _symbol(node) -> str:
117
+ n = node.parent
118
+ meth = ""
119
+ while n is not None:
120
+ if not meth and n.type in ("method", "singleton_method"):
121
+ meth = txt(n.child_by_field_name("name"))
122
+ if n.type in ("class", "module"):
123
+ c = const_text(n.child_by_field_name("name")) or ""
124
+ return f"{c.split('::')[-1]}.{meth}" if meth else c.split("::")[-1]
125
+ n = n.parent
126
+ return meth
127
+
128
+
129
+ def _in_loop(node) -> bool:
130
+ n = node.parent
131
+ while n is not None and n.type not in STOP:
132
+ if n.type in ("while", "until", "for", "while_modifier", "until_modifier"):
133
+ return True
134
+ if n.type in ("block", "do_block") and n.parent is not None and n.parent.type == "call":
135
+ if txt(n.parent.child_by_field_name("method")) in LOOP_METHODS:
136
+ return True
137
+ n = n.parent
138
+ return False
139
+
140
+
141
+ def _class_context(node):
142
+ """(class node, in a class-level method) for an implicit receiver."""
143
+ n = node.parent
144
+ singleton = False
145
+ while n is not None:
146
+ if n.type == "singleton_method":
147
+ singleton = True
148
+ elif n.type == "method":
149
+ p = n.parent
150
+ while p is not None and p.type not in ("singleton_class", "class", "module"):
151
+ p = p.parent
152
+ singleton = p is not None and p.type == "singleton_class"
153
+ if not singleton:
154
+ return None, False
155
+ elif n.type == "lambda" or (n.type == "call" and txt(n.child_by_field_name("method")) in ("scope", "default_scope")):
156
+ return None, False
157
+ elif n.type in ("class", "module"):
158
+ return n, singleton
159
+ n = n.parent
160
+ return None, False
161
+
162
+
163
+ CONDITIONAL = ("if", "unless", "if_modifier", "unless_modifier", "case", "conditional", "when", "else", "elsif", "rescue",
164
+ "begin", "while", "until", "rescue_modifier")
165
+
166
+
167
+ def _conditional(node, scope) -> bool:
168
+ n = node.parent
169
+ while n is not None and n is not scope:
170
+ if n.type in CONDITIONAL:
171
+ return True
172
+ if n.type in ("block", "do_block"):
173
+ return True
174
+ n = n.parent
175
+ return False
176
+
177
+
178
+ # ---- extraction ---------------------------------------------------------------------------------------------------
179
+
180
+ def _engine(root: Path) -> str:
181
+ text = read_text(root / "config" / "database.yml")
182
+ if not text:
183
+ return ""
184
+ found = {ADAPTERS.get(a.strip().strip("'\"").lower(), "?") for a in re.findall(r"^\s*adapter:\s*(\S+)", text, re.M)
185
+ if "<%" not in a}
186
+ found.discard("?")
187
+ if len(found) > 1 and "clickhouse" in found and len(found - {"clickhouse"}) == 1:
188
+ return next(iter(found - {"clickhouse"})) # the primary database; ClickHouse models say so (`connects_to`)
189
+ return next(iter(found)) if len(found) == 1 else ""
190
+
191
+
192
+ def _databases(root: Path) -> dict[str, str]:
193
+ """config/database.yml named databases -> engine (`clickhouse:` with `adapter: clickhouse` under an environment)."""
194
+ text = read_text(root / "config" / "database.yml") or ""
195
+ out: dict[str, str] = {}
196
+ keys: list[tuple[int, str]] = []
197
+ for line in text.split("\n"):
198
+ m = re.match(r"^(\s*)([\w-]+):\s*(.*)$", line)
199
+ if not m or line.lstrip().startswith("#"):
200
+ continue
201
+ ind, key, rest = len(m.group(1)), m.group(2), m.group(3).strip()
202
+ keys = [(i, k) for i, k in keys if i < ind]
203
+ if key == "adapter" and keys and "<%" not in rest:
204
+ eng = ADAPTERS.get(rest.strip("'\"").lower())
205
+ if eng:
206
+ out.setdefault(keys[-1][1], eng)
207
+ elif not rest or rest.startswith(("&", "<<")):
208
+ keys.append((ind, key))
209
+ return out
210
+
211
+
212
+ def extract(root: Path, files: list[str], rules) -> list[RawSite]:
213
+ STATS.clear()
214
+ TABLES[:] = []
215
+ parser = _parser()
216
+ engine = _engine(root)
217
+ models = Models()
218
+ constants: dict[str, object] = {}
219
+ trees: list[tuple[str, object, bool]] = []
220
+ for rel in files:
221
+ test = is_ruby_test(rel)
222
+ if test and not orm_stats.IN_TESTS:
223
+ continue
224
+ src = read_text(root / rel)
225
+ if src is None:
226
+ continue
227
+ data = src.encode("utf-8", "replace")
228
+ try:
229
+ tree = parser.parse(data)
230
+ except Exception:
231
+ continue
232
+ trees.append((rel, tree, test))
233
+ models.collect(rel, tree.root_node)
234
+ _constants(tree.root_node, constants)
235
+ schema = _schema(root, files)
236
+ TABLES.extend(schema)
237
+ models.schema_tables = {t.name: {c["name"] for c in t.columns} for t in schema}
238
+ scope = FileScope(constants)
239
+ tr = Translator(models, engine, scope)
240
+ tr.databases = _databases(root)
241
+ out: list[RawSite] = []
242
+ for rel, tree, test in trees:
243
+ scope.begin(tree.root_node)
244
+ try:
245
+ out.extend(_file_sites(rel, tree.root_node, tr, test, engine))
246
+ except Exception:
247
+ if os.environ.get("CODECOP_ORM_DEBUG"):
248
+ raise
249
+ STATS.miss(LIBRARY, "file could not be read", rel, 0, test)
250
+ return out
251
+
252
+
253
+ def _constants(root, out: dict) -> None:
254
+ for n in walk_tree(root, stop=("method", "singleton_method")):
255
+ if n.type == "assignment":
256
+ left = n.child_by_field_name("left")
257
+ if left is not None and left.type == "constant":
258
+ right = n.child_by_field_name("right")
259
+ if right is not None and right.type in ("string", "heredoc_beginning", "call"):
260
+ full = "::".join(_nesting(n) + [txt(left)])
261
+ out[full] = right
262
+
263
+
264
+ def _is_maximal(node) -> bool:
265
+ p = node.parent
266
+ return not (p is not None and p.type == "call" and p.child_by_field_name("receiver") is not None
267
+ and p.child_by_field_name("receiver").id == node.id)
268
+
269
+
270
+ def _file_sites(rel: str, root, tr: Translator, test: bool, engine: str) -> list[RawSite]:
271
+ out: list[RawSite] = []
272
+ for node in walk_tree(root):
273
+ if node.type != "call" or not _is_maximal(node):
274
+ continue
275
+ base, steps = tr.tr_steps(node)
276
+ if not steps:
277
+ continue
278
+ # SQL through the connection: `ActiveRecord::Base.connection.execute(sql)`, `connection.select_all(...)`
279
+ raw_at = next((i for i, s in enumerate(steps) if s[1] in RAW_METHODS and (
280
+ (i > 0 and steps[i - 1][1] in ("connection", "lease_connection")) or (i == 0 and txt(base) in ("connection", "conn")))), None)
281
+ if raw_at is not None:
282
+ out.extend(_raw_site(rel, node, steps[raw_at], tr, test, engine))
283
+ continue
284
+ sites = _chain_sites(rel, node, base, steps, tr, test, engine)
285
+ out.extend(sites)
286
+ return out
287
+
288
+
289
+ def _raw_site(rel, node, step, tr: Translator, test: bool, engine: str) -> list[RawSite]:
290
+ snode, meth, pos, pairs, _ = step
291
+ if not pos:
292
+ return []
293
+ ctx = Ctx(tr, rel, _nesting(snode))
294
+ sql = None
295
+ first = pos[0]
296
+ if first.type == "array":
297
+ from .orm_rb_activerecord import Q
298
+ sql = tr.fragment(pos, pairs, ctx, Q(None, "")) # `execute(["... ?", x])`: binds as values
299
+ else:
300
+ sql = tr.string_of(first, ctx)
301
+ sink = txt(snode.child_by_field_name("receiver")) + "." + meth
302
+ res = "unresolved" if sql is None else ("template" if "«" in sql else "literal")
303
+ if sql is not None:
304
+ sql = norm(sql)
305
+ return [RawSite(file=rel, line=node.start_point[0] + 1, end_line=node.end_point[0] + 1, language="ruby", kind="call",
306
+ sink=trim(re.sub(r"\s+", "", sink), 80), symbol=_symbol(node), sql=sql, resolution=res,
307
+ expr=trim(norm(txt(first))), in_loop=_in_loop(node), engine_hint=engine, is_test=test, known_sink=True)]
308
+
309
+
310
+ def _root_model(base, steps, tr: Translator, nesting: list[str], node):
311
+ """The model a chain starts at, and the steps that are query methods on it. None when it does not start at one."""
312
+ if base is None:
313
+ # implicit receiver inside a model's class-level method
314
+ if steps[0][1] in NOT_QUERIES:
315
+ return None
316
+ cls, singleton = _class_context(node)
317
+ if cls is None or not singleton:
318
+ return None
319
+ m = tr.models.model(const_text(cls.child_by_field_name("name")) or "", _nesting(cls))
320
+ if m is None:
321
+ return None
322
+ first = steps[0][1]
323
+ known = first in QUERY_METHODS or first in TERMINALS or tr.models.find(m, "scopes", first)[1] is not None \
324
+ or tr.models.find(m, "enum_scopes", first)[1] is not None
325
+ if not known or first in ("new", "update", "delete", "destroy", "build"):
326
+ return None
327
+ return m, steps
328
+ if base.type == "self":
329
+ cls, singleton = _class_context(node)
330
+ if cls is None or not singleton:
331
+ return None
332
+ m = tr.models.model(const_text(cls.child_by_field_name("name")) or "", _nesting(cls))
333
+ return (m, steps) if m is not None else None
334
+ ct = const_text(base)
335
+ if ct is None:
336
+ return None
337
+ m = tr.models.model(ct, nesting)
338
+ if m is None:
339
+ return None
340
+ first = steps[0][1]
341
+ if first in NOT_QUERIES or first.endswith("="):
342
+ return None
343
+ if not _known(tr, m, first):
344
+ # a class method that is not one query expression (its own queries are sites in the model), or a method the
345
+ # library adds: not a call this translator reads
346
+ return None
347
+ return m, steps
348
+
349
+
350
+ def _known(tr: Translator, m, meth: str) -> bool:
351
+ if meth in QUERY_METHODS or meth in TERMINALS or meth.startswith(("find_by_", "async_")):
352
+ return True
353
+ if tr.models.find(m, "scopes", meth)[1] is not None or tr.models.find(m, "enum_scopes", meth)[1] is not None:
354
+ return True
355
+ if tr.models.discard(m) and meth in ("kept", "discarded", "undiscarded", "with_discarded"):
356
+ return True
357
+ cm = tr.models.find(m, "class_methods", meth)[1]
358
+ return cm is not None and cm[1] is not None and tr._chainish(cm[1])
359
+
360
+
361
+ def _var_bases(ident, tr: Translator, nesting: list[str]):
362
+ """The relations a local variable may hold at `ident`: [(model, steps, conditional extensions)]."""
363
+ name = txt(ident)
364
+ scope = ident.parent
365
+ while scope is not None and scope.type not in STOP:
366
+ scope = scope.parent
367
+ if scope is None or scope.type in ("class", "module", "program"):
368
+ return []
369
+ assigns = []
370
+ for n in walk_tree(scope, stop=("method", "singleton_method", "class", "module")):
371
+ if n.start_byte >= ident.start_byte:
372
+ break
373
+ if n.type in ("assignment", "operator_assignment"):
374
+ left = n.child_by_field_name("left")
375
+ if left is not None and left.type in ("identifier", "instance_variable") and txt(left) == name:
376
+ right = n.child_by_field_name("right")
377
+ if right is not None and ident.start_byte > n.end_byte:
378
+ assigns.append((n, right))
379
+ if not assigns:
380
+ return []
381
+ bases, exts = [], []
382
+ for n, right in assigns:
383
+ r = right
384
+ while r is not None and r.type == "parenthesized_statements" and r.named_children:
385
+ r = r.named_children[-1]
386
+ if r is None or r.type != "call":
387
+ if r is not None and r.type in ("constant", "scope_resolution"):
388
+ m = tr.models.model(const_text(r), nesting)
389
+ if m is not None:
390
+ bases.append((n, m, []))
391
+ exts = []
392
+ continue
393
+ bases.append((n, None, None))
394
+ exts = []
395
+ continue
396
+ base, steps = tr.tr_steps(r)
397
+ if base is not None and base.type in ("identifier", "instance_variable") and txt(base) == name:
398
+ exts.append((n, steps, _conditional(n, scope)))
399
+ continue
400
+ got = _root_model(base, steps, tr, nesting, r) if base is None or base.type != "identifier" else None
401
+ if got is None and base is not None and base.type == "identifier":
402
+ inner = _var_bases(base, tr, nesting)
403
+ if inner and inner[0][3] == "relation":
404
+ got = inner[0][0], inner[0][1] + steps
405
+ cond = _conditional(n, scope)
406
+ if not cond:
407
+ bases, exts = [], []
408
+ bases.append((n, got[0] if got else None, got[1] if got else None))
409
+ real = [(m, s) for _, m, s in bases if m is not None]
410
+ if not real or len(real) != len(bases):
411
+ return []
412
+ sure = [(st, False) for _, st, c in exts if not c]
413
+ maybe = [st for _, st, c in exts if c]
414
+ out = []
415
+ for m, s in real:
416
+ kind = _kind(s)
417
+ if kind == "record" and not exts:
418
+ out.append((m, list(s), [], "record"))
419
+ elif kind == "relation":
420
+ common = list(s) + [x for st, _ in sure for x in st]
421
+ out.append((m, common, maybe, "relation"))
422
+ return out
423
+
424
+
425
+ FINDERS = {"find", "find!", "find_by", "find_by!", "first", "first!", "last", "last!", "take", "take!", "sole", "find_sole_by",
426
+ "create", "create!", "find_or_create_by", "find_or_create_by!", "find_or_initialize_by", "create_or_find_by",
427
+ "create_or_find_by!", "first_or_create", "first_or_create!", "new"}
428
+
429
+
430
+ def _kind(steps) -> str:
431
+ """What a chain gives back: a relation (no terminal), one record (ends at a single-row finder), or something else."""
432
+ for i, s in enumerate(steps):
433
+ if s[1] in TERMINALS or s[1] in RUBY_LOADS:
434
+ if s[1] in FINDERS and i == len(steps) - 1 and not (s[1] in ("find", "find!") and len(s[2]) == 1 and s[2][0].type == "array"):
435
+ return "record"
436
+ return "other"
437
+ return "relation"
438
+
439
+
440
+ def _chain_sites(rel, node, base, steps, tr: Translator, test: bool, engine: str) -> list[RawSite]:
441
+ nesting = _nesting(node)
442
+ variants: list[tuple] = [] # (model, steps, note)
443
+ if base is not None and base.type in ("identifier", "instance_variable"):
444
+ if steps[0][1] not in QUERY_METHODS and steps[0][1] not in TERMINALS:
445
+ # `account.statuses` and other methods of plain objects: unless a scope/enum scope of the bound model
446
+ pass
447
+ bound = _var_bases(base, tr, nesting)
448
+ if not bound and base.type == "identifier":
449
+ got = _root_model(None, [(base, txt(base), [], [], None)] + list(steps), tr, nesting, node)
450
+ if got is not None:
451
+ bound = [(got[0], [], [], "relation")]
452
+ steps = got[1]
453
+ if not bound:
454
+ return []
455
+ if bound[0][3] == "record":
456
+ return _record_sites(rel, node, base, bound[0][0], steps, tr, test, engine, nesting)
457
+ from .arms import max_variants
458
+ cap = max(1, max_variants())
459
+ for m, common, maybe, _kind_ in bound:
460
+ variants.append((m, common + steps, ""))
461
+ for ext in maybe:
462
+ if len(variants) >= cap:
463
+ break
464
+ variants.append((m, common + ext + steps, "variant: a conditional refinement applied"))
465
+ if not variants:
466
+ return []
467
+ else:
468
+ got = _root_model(base, steps, tr, nesting, node)
469
+ if got is None:
470
+ return []
471
+ variants.append((got[0], got[1], ""))
472
+ # a relation assigned to a local that a later chain extends is reported there, not here (a record a finder
473
+ # loaded is sent here: `org = Organization.find_by(..)` then `org&.enabled?` is not a second query)
474
+ if _kind(got[1]) == "relation" and _assigned_and_reused(node):
475
+ return []
476
+ # a relation passed as an argument (a subquery value, `merge(...)`) is part of the outer call
477
+ terminal_seen = any(s[1] in TERMINALS for s in variants[0][1])
478
+ if not terminal_seen and node.parent is not None and node.parent.type in ("argument_list", "pair", "array", "hash"):
479
+ return []
480
+ sink_head = (const_text(base) or txt(base) if base is not None else "self")
481
+ sink = f"{sink_head}.{steps[-1][1]}"
482
+ symbol = _symbol(node)
483
+ in_loop = _in_loop(node)
484
+ out: list[RawSite] = []
485
+ STATS.seen(LIBRARY, test)
486
+ first_err = None
487
+ for m, chain, note in variants:
488
+ try:
489
+ stmts, q = _translate(tr, m, chain, rel, nesting)
490
+ except Untranslatable as e:
491
+ first_err = first_err or str(e)
492
+ continue
493
+ for sql, op, extra in stmts:
494
+ notes = list(q.notes) + ([note] if note else []) + ([extra] if extra else [])
495
+ mech = "orm_raw_fragment" if op == "raw" else ("orm_api_in_loop" if in_loop else "orm_api")
496
+ out.append(make_site(rel, node, sink, symbol, norm(sql), table=q.table, operation=op if op != "raw" else "select",
497
+ confidence=q.confidence, notes=notes, in_loop=in_loop, engine=_model_engine(tr, m, engine),
498
+ is_test=test, mechanism=mech))
499
+ if out:
500
+ STATS.hit(LIBRARY, len(out), test)
501
+ else:
502
+ reason = f"method `{first_err}` is not translated" if first_err and re.fullmatch(r"[\w?!]+", first_err) else (first_err or "no statement")
503
+ STATS.miss(LIBRARY, reason, rel, node.start_point[0] + 1, test)
504
+ return out
505
+
506
+
507
+ def _model_engine(tr: Translator, m, default: str) -> str:
508
+ """The engine of the database a model connects to (`connects_to database: {writing: :clickhouse}`)."""
509
+ db = tr.models.database_of(m) if m is not None else ""
510
+ if not db:
511
+ return default
512
+ return (getattr(tr, "databases", {}) or {}).get(db) or ("clickhouse" if "clickhouse" in db.lower() else default)
513
+
514
+
515
+ def _assigned_and_reused(node) -> bool:
516
+ p = node.parent
517
+ if p is None or p.type not in ("assignment", "operator_assignment"):
518
+ return False
519
+ left = p.child_by_field_name("left")
520
+ if left is None or left.type not in ("identifier", "instance_variable"):
521
+ return False
522
+ name = txt(left)
523
+ scope = p.parent
524
+ while scope is not None and scope.type not in STOP:
525
+ scope = scope.parent
526
+ if scope is None or scope.type in ("class", "module", "program"):
527
+ return False
528
+ for n in walk_tree(scope, stop=("method", "singleton_method", "class", "module")):
529
+ if n.start_byte <= p.end_byte:
530
+ continue
531
+ if n.type == "call" and _is_maximal(n):
532
+ b = n
533
+ while b is not None and b.type == "call":
534
+ b = b.child_by_field_name("receiver")
535
+ if b is not None and b.type == left.type and txt(b) == name:
536
+ # extended by a query method or ended by a terminal: that chain is the site
537
+ return True
538
+ return False
539
+
540
+
541
+ def _record_sites(rel, node, base, m, steps, tr: Translator, test: bool, engine: str, nesting) -> list[RawSite]:
542
+ """A chain on a variable holding one record of model m: an association of the record (`account.statuses.where`)
543
+ or an instance write (`status.update(...)`, `.destroy`)."""
544
+ first = steps[0][1]
545
+ ctx = Ctx(tr, rel, nesting)
546
+ var = txt(base)
547
+ stmts, q, target = [], None, None
548
+ a = tr.models.assoc(m, first)
549
+ if a is not None and not a.polymorphic and not a.through and a.kind != "habtm" and not steps[0][2]:
550
+ target = tr.models.assoc_model(m, a)
551
+ if target is None:
552
+ return []
553
+ if a.kind == "belongs_to":
554
+ cond_col, cond_val = (a.primary_key or "id"), f"«{var}.{a.foreign_key or a.name + '_id'}»"
555
+ elif a.as_:
556
+ cond_col, cond_val = (a.foreign_key or a.as_ + "_id"), f"«{var}.id»"
557
+ else:
558
+ cond_col = a.foreign_key or underscore_name(tr.models.base(m).name.split("::")[-1]) + "_id"
559
+ cond_val = f"«{var}.id»"
560
+ try:
561
+ stmts, q = _translate(tr, target, list(steps[1:]), rel, nesting,
562
+ pre=[f"{tr.col(tr.models.table(target), cond_col)} = {cond_val}"]
563
+ + ([f"{tr.col(tr.models.table(target), a.as_ + '_type')} = '{tr.models.base(m).name}'"] if a.as_ else []),
564
+ single=a.kind in ("belongs_to", "has_one"))
565
+ except Untranslatable:
566
+ return []
567
+ elif first in ("update", "update!", "update_columns", "update_column", "update_attribute", "destroy", "destroy!", "delete",
568
+ "touch", "increment!", "decrement!"):
569
+ q = tr.start(m)
570
+ stmts = [(sql.replace("«record.id»", f"«{var}.id»"), op, n) for sql, op, n in _instance_followup(tr, q, steps[0], ctx)]
571
+ if not stmts or q is None:
572
+ return []
573
+ STATS.seen(LIBRARY, test)
574
+ STATS.hit(LIBRARY, len(stmts), test)
575
+ in_loop = _in_loop(node)
576
+ return [make_site(rel, node, f"{var}.{steps[-1][1]}", _symbol(node), norm(sql), table=q.table, operation=op,
577
+ confidence=q.confidence if q.confidence != "high" else "medium",
578
+ notes=list(q.notes) + [n, f"`{var}` holds one {m.name} record"], in_loop=in_loop,
579
+ engine=_model_engine(tr, target if target is not None else m, engine),
580
+ is_test=test, mechanism="orm_api_in_loop" if in_loop else "orm_api") for sql, op, n in stmts]
581
+
582
+
583
+ def underscore_name(name: str) -> str:
584
+ from .orm_rb_activerecord import underscore
585
+ return underscore(name)
586
+
587
+
588
+ def _translate(tr: Translator, m, chain, rel: str, nesting: list[str], pre: list[str] | None = None, single: bool = False):
589
+ ctx = Ctx(tr, rel, nesting)
590
+ q = tr.start(m)
591
+ q.wheres.extend(pre or [])
592
+ if single and (not chain or chain[0][1] in RUBY_LOADS):
593
+ q.limit = "1" # a belongs_to / has_one reader loads one row
594
+ if not any(s[1] == "unscoped" for s in chain):
595
+ for body in tr.models.default_scopes(m):
596
+ try:
597
+ tr.inline(q, body, [], [], Ctx(tr, rel, m.name.split("::"), None, 1))
598
+ except Untranslatable:
599
+ q.lower("medium")
600
+ q.notes.append("default_scope not read")
601
+ # the query methods, up to the terminal (`async_count` is `count` sent later; Ruby methods load the relation)
602
+ chain = [(n, m[6:] if m.startswith("async_") and m[6:] in TERMINALS else m, p, pr, b) for n, m, p, pr, b in chain]
603
+ idx = len(chain)
604
+ for i, s in enumerate(chain):
605
+ if (s[1] in TERMINALS and not (s[1] == "select" and s[4] is None)) or s[1] in RUBY_LOADS:
606
+ idx = i
607
+ break
608
+ term = tr.apply(q, chain[:idx], ctx) if idx else None
609
+ if q.none:
610
+ return [], q
611
+ if idx < len(chain):
612
+ node, meth, pos, pairs, block = chain[idx]
613
+ tr.eager_joins(q)
614
+ stmts = tr.terminal(q, meth, pos, pairs, block, ctx, chain[idx + 1:])
615
+ if meth in ("find", "find!", "find_by", "find_by!", "first", "first!", "last", "last!", "take", "take!", "to_a",
616
+ "each", "map", "find_each", "find_in_batches", "load", "records", "each_with_object", "index_by",
617
+ "group_by", "flat_map", "filter_map", "sort_by") or meth not in TERMINALS:
618
+ stmts = stmts + tr.preload_statements(q)
619
+ # an instance call after a finder: `Model.find(id).update(attrs)`, `.destroy`
620
+ if meth in ("find", "find!", "find_by", "find_by!", "first", "first!", "last", "take") and idx + 1 < len(chain):
621
+ stmts = stmts + _instance_followup(tr, q, chain[idx + 1], ctx)
622
+ return stmts, q
623
+ _ = term
624
+ tr.eager_joins(q)
625
+ return [(tr.render_select(q), "select", "relation: sent where it is enumerated")] + tr.preload_statements(q), q
626
+
627
+
628
+ def _instance_followup(tr: Translator, q, step, ctx) -> list[tuple[str, str, str]]:
629
+ node, meth, pos, pairs, block = step
630
+ t = q.table
631
+ idc = tr.col(t, "id")
632
+ if meth in ("update", "update!", "update_columns", "update_attribute", "update_column"):
633
+ if meth in ("update_attribute", "update_column") and len(pos) >= 2:
634
+ name = symbol_name(pos[0])
635
+ sets = [(name, tr.value(pos[1], ctx))] if name else []
636
+ else:
637
+ hp, _ = tr.hash_pairs(pos, pairs)
638
+ sets = tr.assignments(q, q.model, hp, ctx)
639
+ if meth not in ("update_columns", "update_column"):
640
+ sets += [(c, "«now»") for c in tr.timestamps(t) if c == "updated_at" and all(c != s for s, _ in sets)]
641
+ if sets:
642
+ return [(f"UPDATE {tr.q(t)} SET " + ", ".join(f"{tr.q(c)} = {v}" for c, v in sets) + f" WHERE {idc} = «record.id»", "update", "")]
643
+ if meth in ("destroy", "destroy!", "delete"):
644
+ return [(f"DELETE FROM {tr.q(t)} WHERE {idc} = «record.id»", "delete", "")]
645
+ if meth in ("touch",):
646
+ return [(f"UPDATE {tr.q(t)} SET {tr.q('updated_at')} = «now» WHERE {idc} = «record.id»", "update", "")]
647
+ if meth in ("increment!", "decrement!") and pos:
648
+ col = symbol_name(pos[0])
649
+ if col:
650
+ sign = "+" if meth.startswith("inc") else "-"
651
+ return [(f"UPDATE {tr.q(t)} SET {tr.q(col)} = COALESCE({tr.q(col)}, 0) {sign} 1 WHERE {idc} = «record.id»", "update", "")]
652
+ return []
653
+
654
+
655
+ # ---- schema -------------------------------------------------------------------------------------------------------
656
+ PG_TYPES = {"string": "character varying", "text": "text", "integer": "integer", "bigint": "bigint", "boolean": "boolean",
657
+ "datetime": "timestamp", "timestamp": "timestamp", "timestamptz": "timestamp with time zone", "date": "date",
658
+ "time": "time", "decimal": "numeric", "numeric": "numeric", "float": "double precision", "json": "json",
659
+ "jsonb": "jsonb", "uuid": "uuid", "inet": "inet", "cidr": "cidr", "binary": "bytea", "citext": "citext",
660
+ "hstore": "hstore", "interval": "interval", "smallint": "smallint", "virtual": "text", "enum": "text",
661
+ "tsvector": "tsvector", "ltree": "ltree", "bigserial": "bigint", "serial": "integer", "macaddr": "macaddr",
662
+ "money": "money", "xml": "xml", "point": "point", "daterange": "daterange", "tsrange": "tsrange",
663
+ "int4range": "int4range", "blob": "bytea"}
664
+ _CREATE = re.compile(r"^\s*create_table\s*\(?\s*[\"':]([\w.]+)[\"']?(.*?)(?:do\s*\|(\w+)\||\{\s*\|(\w+)\|)", re.M)
665
+ _COLDEF = re.compile(r"^\s*(\w+)\.(\w+)\s+\(?\s*([^\n#]*)", re.M)
666
+
667
+
668
+ def _type(kind: str, rest: str) -> str:
669
+ t = PG_TYPES.get(kind, kind)
670
+ if re.search(r"\barray:\s*true", rest):
671
+ t += "[]"
672
+ return t
673
+
674
+
675
+ def _parse_defs(rel: str, text: str, tables: dict[str, Table], order: list[str]) -> None:
676
+ lines = text.split("\n")
677
+ i = 0
678
+ while i < len(lines):
679
+ line = lines[i]
680
+ m = _CREATE.match(line)
681
+ if m:
682
+ name, opts, var = m.group(1), m.group(2), m.group(3) or m.group(4)
683
+ t = Table(name=name, defined_at=[f"{rel}:{i + 1}"], name_basis="sql")
684
+ idm = re.search(r"\bid:\s*(false|:(\w+))", opts)
685
+ if not idm:
686
+ t.columns.append({"name": "id", "type": "bigint"})
687
+ elif idm.group(2):
688
+ t.columns.append({"name": "id", "type": _type(idm.group(2), "")})
689
+ pk = re.search(r"primary_key:\s*[\"':](\w+)", opts)
690
+ if pk and idm and idm.group(1) == "false":
691
+ pass
692
+ depth = 1
693
+ j = i + 1
694
+ while j < len(lines) and depth > 0:
695
+ ln = lines[j]
696
+ s = ln.strip()
697
+ if re.match(r"^end\b", s) or s == "}":
698
+ depth -= 1
699
+ if depth == 0:
700
+ break
701
+ elif re.search(r"\bdo\b(\s*\|.*\|)?\s*$", s):
702
+ depth += 1
703
+ cm = re.match(rf"^\s*{re.escape(var)}\.(\w+)\s*\(?\s*(.*)$", ln) if var else None
704
+ if cm:
705
+ kind, rest = cm.group(1), cm.group(2)
706
+ if kind == "index":
707
+ cols = re.findall(r"[\"'](\w+)[\"']", rest.split("name:")[0])
708
+ nm = re.search(r"name:\s*[\"']([^\"']+)", rest)
709
+ t.indexes.append({"name": nm.group(1) if nm else f"index_{name}_on_{'_and_'.join(cols)}",
710
+ "columns": cols, "unique": bool(re.search(r"unique:\s*true", rest))})
711
+ elif kind == "timestamps":
712
+ for c in ("created_at", "updated_at"):
713
+ t.columns.append({"name": c, "type": "timestamp"})
714
+ elif kind in ("references", "belongs_to"):
715
+ nm = re.match(r"[\"':](\w+)", rest)
716
+ if nm:
717
+ t.columns.append({"name": nm.group(1) + "_id", "type": "bigint"})
718
+ if re.search(r"polymorphic:\s*true", rest):
719
+ t.columns.append({"name": nm.group(1) + "_type", "type": "character varying"})
720
+ elif kind not in ("check_constraint", "foreign_key", "exclusion_constraint", "unique_constraint"):
721
+ for cn in re.findall(r"[\"':](\w+)[\"']?", rest.split(",")[0]) if kind != "column" else []:
722
+ t.columns.append({"name": cn, "type": _type(kind, rest)})
723
+ if kind == "column":
724
+ cm2 = re.match(r"[\"':](\w+)[\"']?\s*,\s*:?[\"']?(\w+)", rest)
725
+ if cm2:
726
+ t.columns.append({"name": cm2.group(1), "type": _type(cm2.group(2), rest)})
727
+ j += 1
728
+ if name not in tables:
729
+ order.append(name)
730
+ tables[name] = t
731
+ i = j + 1
732
+ continue
733
+ am = re.match(r"^\s*add_index\s*\(?\s*[\"':](\w+)[\"']?\s*,\s*(\[[^\]]*\]|[\"':]\w+[\"']?)(.*)$", line)
734
+ if am and am.group(1) in tables:
735
+ cols = re.findall(r"[\"':](\w+)", am.group(2))
736
+ nm = re.search(r"name:\s*[\"']([^\"']+)", am.group(3))
737
+ tables[am.group(1)].indexes.append({"name": nm.group(1) if nm else f"index_{am.group(1)}_on_{'_and_'.join(cols)}",
738
+ "columns": cols, "unique": bool(re.search(r"unique:\s*true", am.group(3)))})
739
+ ac = re.match(r"^\s*add_column\s*\(?\s*[\"':](\w+)[\"']?\s*,\s*[\"':](\w+)[\"']?\s*,\s*[\"':](\w+)[\"']?(.*)$", line)
740
+ if ac and ac.group(1) in tables:
741
+ cols = tables[ac.group(1)].columns
742
+ if all(c["name"] != ac.group(2) for c in cols):
743
+ cols.append({"name": ac.group(2), "type": _type(ac.group(3), ac.group(4))})
744
+ ar = re.match(r"^\s*add_reference\s*\(?\s*[\"':](\w+)[\"']?\s*,\s*[\"':](\w+)", line)
745
+ if ar and ar.group(1) in tables:
746
+ tables[ar.group(1)].columns.append({"name": ar.group(2) + "_id", "type": "bigint"})
747
+ rc = re.match(r"^\s*remove_column\s*\(?\s*[\"':](\w+)[\"']?\s*,\s*[\"':](\w+)", line)
748
+ if rc and rc.group(1) in tables:
749
+ tables[rc.group(1)].columns = [c for c in tables[rc.group(1)].columns if c["name"] != rc.group(2)]
750
+ rn = re.match(r"^\s*rename_column\s*\(?\s*[\"':](\w+)[\"']?\s*,\s*[\"':](\w+)[\"']?\s*,\s*[\"':](\w+)", line)
751
+ if rn and rn.group(1) in tables:
752
+ for c in tables[rn.group(1)].columns:
753
+ if c["name"] == rn.group(2):
754
+ c["name"] = rn.group(3)
755
+ rt = re.match(r"^\s*rename_table\s*\(?\s*[\"':](\w+)[\"']?\s*,\s*[\"':](\w+)", line)
756
+ if rt and rt.group(1) in tables:
757
+ t = tables.pop(rt.group(1))
758
+ t.renamed_from.append(t.name)
759
+ t.name = rt.group(2)
760
+ tables[t.name] = t
761
+ order.append(t.name)
762
+ dt = re.match(r"^\s*drop_table\s*\(?\s*[\"':](\w+)", line)
763
+ if dt and dt.group(1) in tables:
764
+ tables.pop(dt.group(1))
765
+ i += 1
766
+
767
+
768
+ def _schema(root: Path, files: list[str]) -> list[Table]:
769
+ tables: dict[str, Table] = {}
770
+ order: list[str] = []
771
+ schema_files = [f for f in files if re.search(r"(^|/)db/(\w+_)?schema\.rb$", f) and not is_ruby_test(f)]
772
+ if schema_files:
773
+ for f in sorted(schema_files):
774
+ text = read_text(root / f)
775
+ if text:
776
+ _parse_defs(f, text, tables, order)
777
+ else:
778
+ migs = sorted((f for f in files if re.search(r"(^|/)db/(\w+_)?migrate/[^/]+\.rb$", f)), key=os.path.basename)
779
+ for f in migs:
780
+ text = read_text(root / f)
781
+ if text:
782
+ _parse_defs(f, text, tables, order)
783
+ return [tables[n] for n in dict.fromkeys(order) if n in tables]
784
+
785
+
786
+ def tables() -> list:
787
+ out = list(TABLES)
788
+ TABLES.clear()
789
+ return out
790
+
791
+
792
+ def summary_extras() -> dict:
793
+ return STATS.summary()