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,1906 @@
1
+ """ActiveRecord (Ruby on Rails) calls turned into SQL sites, by rule.
2
+
3
+ `ruby.extract` parses every Ruby file once, hands the trees to `Models.collect` (models, their tables, associations,
4
+ scopes, enums, class methods, default scopes, concerns) and then asks `Translator.sites` for the sites of each file.
5
+
6
+ A chain that starts at a model (`Status.where(account: a).order(id: :desc).limit(20)`), at a local variable bound to
7
+ such a chain, or at the implicit receiver inside a model's class method is translated the way ActiveRecord builds
8
+ it: table by Rails convention (`self.table_name`, `table_name_prefix` modules, STI base class), hash conditions with
9
+ association keys (`account:` -> `account_id`), enum symbols as their stored values, `joins`/`eager_load` as joins
10
+ along the associations, `includes`/`preload` as the follow-up statement per association, scopes and single-expression
11
+ class methods inlined one level (their parameters bound to the call's arguments), and the terminal method deciding
12
+ the statement (`count`, `pluck`, `exists?`, `update_all`, `delete_all`, `create`, `insert_all`, `find_each`, ...).
13
+
14
+ Every value only known at run time is a «run-time part» in value position. A method the translator does not know
15
+ (a class method with a body it cannot read) becomes a «run-time part» where the predicate goes, and the site says so
16
+ in its notes with confidence low. A call whose model cannot be told is not translated.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import re
22
+ from dataclasses import dataclass, field
23
+
24
+ from .base import RawSite, trim
25
+
26
+ LIBRARY = "activerecord"
27
+
28
+ # ---- settings (`[discover]` in codecop.toml) -------------------------------------------------------------------------
29
+ DEFAULTS = {
30
+ "ar_max_inline_depth": 3, # scopes / class methods inlined inside one another
31
+ "ar_max_preload_depth": 4, # nested includes followed from one call
32
+ "ar_marker_chars": 80, # longest source expression kept inside one «run-time part»
33
+ "ar_batch_size": 1000, # find_each / in_batches default batch size (ActiveRecord's own default)
34
+ "ar_page_size": 25, # Kaminari `page` default page size
35
+ }
36
+ SETTINGS = dict(DEFAULTS)
37
+
38
+
39
+ def configure(settings: dict | None) -> None:
40
+ SETTINGS.clear()
41
+ SETTINGS.update(DEFAULTS)
42
+ for key in DEFAULTS:
43
+ if settings and settings.get(key) is not None:
44
+ SETTINGS[key] = int(settings[key])
45
+
46
+
47
+ # ---- inflection (Rails' default English rules) --------------------------------------------------------------------
48
+ _PLURAL = [
49
+ (r"$", "s"), (r"s$", "s"), (r"^(ax|test)is$", r"\1es"), (r"(octop|vir)us$", r"\1i"), (r"(octop|vir)i$", r"\1i"),
50
+ (r"(alias|status)$", r"\1es"), (r"(bu)s$", r"\1ses"), (r"(buffal|tomat)o$", r"\1oes"), (r"([ti])um$", r"\1a"),
51
+ (r"([ti])a$", r"\1a"), (r"sis$", "ses"), (r"(?:([^f])fe|([lr])f)$", r"\1\2ves"), (r"(hive)$", r"\1s"),
52
+ (r"([^aeiouy]|qu)y$", r"\1ies"), (r"(x|ch|ss|sh)$", r"\1es"), (r"(matr|vert|ind)(?:ix|ex)$", r"\1ices"),
53
+ (r"^(m|l)ouse$", r"\1ice"), (r"^(m|l)ice$", r"\1ice"), (r"^(ox)$", r"\1en"), (r"^(oxen)$", r"\1"),
54
+ (r"(quiz)$", r"\1zes"),
55
+ ]
56
+ _SINGULAR = [
57
+ (r"s$", ""), (r"(ss)$", r"\1"), (r"(n)ews$", r"\1ews"), (r"([ti])a$", r"\1um"),
58
+ (r"((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$", r"\1sis"), (r"(^analy)(sis|ses)$", r"\1sis"),
59
+ (r"([^f])ves$", r"\1fe"), (r"(hive)s$", r"\1"), (r"(tive)s$", r"\1"), (r"([lr])ves$", r"\1f"),
60
+ (r"([^aeiouy]|qu)ies$", r"\1y"), (r"(s)eries$", r"\1eries"), (r"(m)ovies$", r"\1ovie"), (r"(x|ch|ss|sh)es$", r"\1"),
61
+ (r"^(m|l)ice$", r"\1ouse"), (r"(bus)(es)?$", r"\1"), (r"(o)es$", r"\1"), (r"(shoe)s$", r"\1"),
62
+ (r"(cris|test)(is|es)$", r"\1is"), (r"^(a)x[ie]s$", r"\1xis"), (r"(octop|vir)(us|i)$", r"\1us"),
63
+ (r"(alias|status)(es)?$", r"\1"), (r"^(ox)en", r"\1"), (r"(vert|ind)ices$", r"\1ex"), (r"(matr)ices$", r"\1ix"),
64
+ (r"(quiz)zes$", r"\1"), (r"(database)s$", r"\1"),
65
+ ]
66
+ _IRREGULAR = {"person": "people", "man": "men", "child": "children", "sex": "sexes", "move": "moves", "zombie": "zombies"}
67
+ _UNCOUNTABLE = {"equipment", "information", "rice", "money", "species", "series", "fish", "sheep", "jeans", "police"}
68
+
69
+
70
+ def _inflect(word: str, rules, irregular: dict[str, str]) -> str:
71
+ low = word.lower()
72
+ for unc in _UNCOUNTABLE:
73
+ if low.endswith(unc):
74
+ return word
75
+ for a, b in irregular.items():
76
+ if low == a or low.endswith("_" + a):
77
+ return word[: len(word) - len(a)] + b
78
+ for rx, rep in reversed(rules):
79
+ if re.search(rx, word, re.I):
80
+ return re.sub(rx, rep, word, count=1, flags=re.I)
81
+ return word
82
+
83
+
84
+ def pluralize(word: str) -> str:
85
+ return _inflect(word, _PLURAL, _IRREGULAR)
86
+
87
+
88
+ def singularize(word: str) -> str:
89
+ return _inflect(word, _SINGULAR, {v: k for k, v in _IRREGULAR.items()})
90
+
91
+
92
+ def underscore(name: str) -> str:
93
+ name = name.replace("::", "/")
94
+ name = re.sub(r"([A-Z\d]+)([A-Z][a-z])", r"\1_\2", name)
95
+ name = re.sub(r"([a-z\d])([A-Z])", r"\1_\2", name)
96
+ return name.replace("-", "_").lower()
97
+
98
+
99
+ def classify(name: str) -> str:
100
+ """`account_stats` -> `AccountStat` (association name -> class name)."""
101
+ return "".join(p[:1].upper() + p[1:] for p in singularize(name).split("_"))
102
+
103
+
104
+ # ---- tree helpers -------------------------------------------------------------------------------------------------
105
+
106
+ def txt(node) -> str:
107
+ return node.text.decode("utf-8", "replace") if node is not None else ""
108
+
109
+
110
+ def norm(text: str) -> str:
111
+ return " ".join(text.split())
112
+
113
+
114
+ def mark(text: str) -> str:
115
+ return "«" + trim(norm(text), SETTINGS["ar_marker_chars"]).replace("»", ">").replace("«", "<") + "»"
116
+
117
+
118
+ def symbol_name(node) -> str | None:
119
+ """`:foo`, `"foo"`, `'foo'`, `foo:` -> foo."""
120
+ if node is None:
121
+ return None
122
+ t = node.type
123
+ if t in ("simple_symbol", "hash_key_symbol"):
124
+ return txt(node).lstrip(":").rstrip(":")
125
+ if t == "delimited_symbol":
126
+ s = string_text(node)
127
+ return s
128
+ if t == "string":
129
+ return string_text(node)
130
+ if t == "identifier" and node.parent is not None and node.parent.type == "pair":
131
+ return txt(node)
132
+ return None
133
+
134
+
135
+ def string_text(node) -> str | None:
136
+ """A string with no interpolation, else None."""
137
+ if node is None or node.type not in ("string", "delimited_symbol", "simple_symbol"):
138
+ return None
139
+ if node.type == "simple_symbol":
140
+ return txt(node)[1:]
141
+ parts = []
142
+ for c in node.named_children:
143
+ if c.type == "string_content":
144
+ parts.append(txt(c))
145
+ elif c.type == "escape_sequence":
146
+ parts.append({"\\n": "\n", "\\t": "\t", "\\\"": "\"", "\\'": "'", "\\\\": "\\"}.get(txt(c), txt(c)[1:]))
147
+ else:
148
+ return None
149
+ return "".join(parts)
150
+
151
+
152
+ def interpolated(node, env: dict | None = None) -> str | None:
153
+ """A string or heredoc body as text, interpolations as «expr». None when it is not a string."""
154
+ if node is None:
155
+ return None
156
+ if node.type not in ("string", "heredoc_body", "string_array", "bare_string", "subshell"):
157
+ return None
158
+ out = []
159
+ for c in node.named_children:
160
+ if c.type in ("string_content", "heredoc_content"):
161
+ out.append(txt(c))
162
+ elif c.type == "escape_sequence":
163
+ out.append({"\\n": "\n", "\\t": "\t", "\\\"": "\"", "\\'": "'"}.get(txt(c), txt(c)[1:]))
164
+ elif c.type == "interpolation":
165
+ inner = c.named_children[0] if c.named_children else None
166
+ if inner is not None and env and inner.type == "identifier" and txt(inner) in env:
167
+ inner = env[txt(inner)]
168
+ out.append(mark(txt(inner)))
169
+ elif c.type == "heredoc_end":
170
+ continue
171
+ return "".join(out)
172
+
173
+
174
+ def call_parts(node):
175
+ """(receiver, method name, positional args, pairs, block) of a `call` node."""
176
+ recv = node.child_by_field_name("receiver")
177
+ meth = node.child_by_field_name("method")
178
+ args = node.child_by_field_name("arguments")
179
+ block = node.child_by_field_name("block")
180
+ pos, pairs = [], []
181
+ if args is not None:
182
+ for c in args.named_children:
183
+ if c.type == "pair":
184
+ pairs.append(c)
185
+ elif c.type == "hash":
186
+ pairs.extend(p for p in c.named_children if p.type == "pair")
187
+ if any(p.type == "hash_splat_argument" for p in c.named_children):
188
+ pos.append(c)
189
+ elif c.type == "comment":
190
+ continue
191
+ else:
192
+ pos.append(c)
193
+ return recv, txt(meth), pos, pairs, block
194
+
195
+
196
+ def pair_key(pair) -> str | None:
197
+ k = pair.child_by_field_name("key")
198
+ return symbol_name(k) if k is not None else None
199
+
200
+
201
+ def pair_value(pair):
202
+ return pair.child_by_field_name("value")
203
+
204
+
205
+ def const_text(node) -> str | None:
206
+ if node is None:
207
+ return None
208
+ if node.type == "constant":
209
+ return txt(node)
210
+ if node.type == "scope_resolution":
211
+ return txt(node).lstrip(":").replace(" ", "")
212
+ return None
213
+
214
+
215
+ # ---- models -------------------------------------------------------------------------------------------------------
216
+
217
+ @dataclass
218
+ class Assoc:
219
+ kind: str # belongs_to | has_many | has_one | habtm
220
+ name: str
221
+ class_name: str = ""
222
+ foreign_key: str = ""
223
+ through: str = ""
224
+ source: str = ""
225
+ polymorphic: bool = False
226
+ as_: str = ""
227
+ primary_key: str = ""
228
+
229
+
230
+ @dataclass
231
+ class Model:
232
+ name: str # full constant name, `Fasp::Provider`
233
+ nesting: list[str]
234
+ superclass: str = ""
235
+ file: str = ""
236
+ is_module: bool = False
237
+ table_name: str | None = None
238
+ abstract: bool = False
239
+ inheritance_column: str = "type"
240
+ assocs: dict[str, Assoc] = field(default_factory=dict)
241
+ scopes: dict[str, tuple] = field(default_factory=dict) # name -> (params, body node)
242
+ class_methods: dict[str, tuple] = field(default_factory=dict) # name -> (params, body node)
243
+ enums: dict[str, dict] = field(default_factory=dict) # column -> {name: stored value sql}
244
+ enum_scopes: dict[str, tuple] = field(default_factory=dict) # scope name -> (column, value sql, negated)
245
+ default_scopes: list = field(default_factory=list) # body nodes
246
+ includes: list[str] = field(default_factory=list)
247
+ prefix: str | None = None # module table_name_prefix
248
+ discard_column: str = "" # the discard gem's column, when set
249
+ database: str = "" # `connects_to database: {writing: :x}`: x
250
+
251
+
252
+ def _params(node) -> list[str]:
253
+ if node is None:
254
+ return []
255
+ out = []
256
+ for c in node.named_children:
257
+ if c.type == "identifier":
258
+ out.append(txt(c))
259
+ elif c.type in ("optional_parameter", "keyword_parameter", "splat_parameter", "block_parameter"):
260
+ n = c.child_by_field_name("name")
261
+ out.append(txt(n) if n is not None else "")
262
+ return out
263
+
264
+
265
+ def _last_expr(body):
266
+ """The expression a block / method body returns, when it is a single expression (comments aside)."""
267
+ if body is None:
268
+ return None
269
+ if body.type in ("block", "do_block"):
270
+ body = next((c for c in body.named_children if c.type in ("block_body", "body_statement")), None)
271
+ if body is None:
272
+ return None
273
+ stmts = [c for c in body.named_children if c.type not in ("comment",)]
274
+ if len(stmts) != 1:
275
+ return None
276
+ return stmts[0]
277
+
278
+
279
+ def _lambda_parts(node):
280
+ """(params, body expr) of `-> { }`, `->(a) { }`, `lambda { |a| }`, `proc { }`."""
281
+ if node is None:
282
+ return None
283
+ if node.type == "lambda":
284
+ params = _params(node.child_by_field_name("parameters"))
285
+ body = node.child_by_field_name("body")
286
+ return params, _last_expr(body)
287
+ if node.type == "call" and txt(node.child_by_field_name("method")) in ("lambda", "proc"):
288
+ block = node.child_by_field_name("block")
289
+ if block is None:
290
+ return None
291
+ bp = next((c for c in block.named_children if c.type == "block_parameters"), None)
292
+ return _params(bp), _last_expr(block)
293
+ return None
294
+
295
+
296
+ class Models:
297
+ def __init__(self) -> None:
298
+ self.by_name: dict[str, Model] = {}
299
+ self.schema_tables: dict[str, set[str]] = {} # table -> columns (from schema.rb / migrations)
300
+
301
+ # -- collection
302
+ def collect(self, rel: str, root) -> None:
303
+ self._walk(rel, root, [])
304
+
305
+ def _walk(self, rel: str, node, nesting: list[str]) -> None:
306
+ for c in node.named_children:
307
+ if c.type in ("class", "module"):
308
+ cname = const_text(c.child_by_field_name("name"))
309
+ if not cname:
310
+ continue
311
+ full = "::".join(nesting + [cname]) if nesting else cname
312
+ m = self.by_name.get(full)
313
+ if m is None:
314
+ m = self.by_name[full] = Model(name=full, nesting=list(nesting), file=rel, is_module=c.type == "module")
315
+ if c.type == "class":
316
+ sup = c.child_by_field_name("superclass")
317
+ sc = const_text(sup.named_children[0]) if sup is not None and sup.named_children else None
318
+ if sc:
319
+ m.superclass = sc
320
+ m.is_module = False
321
+ body = c.child_by_field_name("body")
322
+ if body is not None:
323
+ self._body(m, body)
324
+ self._walk(rel, body, nesting + [cname])
325
+ elif c.type in ("body_statement", "begin_block"):
326
+ self._walk(rel, c, nesting)
327
+
328
+ def _body(self, m: Model, body, in_singleton: bool = False) -> None:
329
+ for s in body.named_children:
330
+ t = s.type
331
+ if t == "assignment":
332
+ left, right = s.child_by_field_name("left"), s.child_by_field_name("right")
333
+ if left is not None and left.type == "call" and txt(left.child_by_field_name("receiver")) == "self":
334
+ attr = txt(left.child_by_field_name("method"))
335
+ if attr == "table_name":
336
+ name = string_text(right) if right is not None else None
337
+ if name:
338
+ m.table_name = name
339
+ elif attr == "abstract_class" and txt(right) == "true":
340
+ m.abstract = True
341
+ elif attr == "discard_column":
342
+ name = string_text(right) if right is not None else None
343
+ if name:
344
+ m.discard_column = name
345
+ elif attr == "inheritance_column":
346
+ name = string_text(right) if right is not None else None
347
+ if name:
348
+ m.inheritance_column = name
349
+ elif t == "singleton_method" and txt(s.child_by_field_name("object")) == "self":
350
+ self._def(m, s)
351
+ elif t == "method" and in_singleton:
352
+ self._def(m, s)
353
+ elif t == "singleton_class":
354
+ b = s.child_by_field_name("body")
355
+ if b is not None:
356
+ self._body(m, b, in_singleton=True)
357
+ elif t == "call" and s.child_by_field_name("receiver") is None:
358
+ self._macro(m, s)
359
+ elif t == "identifier" and txt(s) == "primary_abstract_class":
360
+ m.abstract = True
361
+
362
+ def _def(self, m: Model, s) -> None:
363
+ name = txt(s.child_by_field_name("name"))
364
+ params = _params(s.child_by_field_name("parameters"))
365
+ body = s.child_by_field_name("body")
366
+ if name == "table_name_prefix":
367
+ e = _last_expr(body)
368
+ v = string_text(e) if e is not None else None
369
+ if v is not None:
370
+ m.prefix = v
371
+ return
372
+ m.class_methods[name] = (params, _last_expr(body))
373
+
374
+ def _macro(self, m: Model, s) -> None:
375
+ _, meth, pos, pairs, block = call_parts(s)
376
+ if meth in ("has_many", "has_one", "belongs_to", "has_and_belongs_to_many") and pos:
377
+ name = symbol_name(pos[0])
378
+ if not name:
379
+ return
380
+ a = Assoc(kind={"has_and_belongs_to_many": "habtm"}.get(meth, meth), name=name)
381
+ for p in pairs:
382
+ k, v = pair_key(p), pair_value(p)
383
+ sv = string_text(v) if v is not None else None
384
+ if k == "class_name" and sv:
385
+ a.class_name = sv.lstrip(":")
386
+ elif k == "foreign_key" and sv:
387
+ a.foreign_key = sv
388
+ elif k == "through" and sv:
389
+ a.through = sv
390
+ elif k == "source" and sv:
391
+ a.source = sv
392
+ elif k == "polymorphic" and txt(v) == "true":
393
+ a.polymorphic = True
394
+ elif k == "as" and sv:
395
+ a.as_ = sv
396
+ elif k == "primary_key" and sv:
397
+ a.primary_key = sv
398
+ m.assocs[name] = a
399
+ elif meth == "scope" and len(pos) >= 2:
400
+ name = symbol_name(pos[0])
401
+ lp = _lambda_parts(pos[1])
402
+ if name and lp:
403
+ m.scopes[name] = lp
404
+ elif meth == "default_scope":
405
+ lp = _lambda_parts(pos[0]) if pos else None
406
+ if lp is None and block is not None:
407
+ lp = ([], _last_expr(block))
408
+ if lp and lp[1] is not None:
409
+ m.default_scopes.append(lp[1])
410
+ elif meth == "enum":
411
+ self._enum(m, pos, pairs)
412
+ elif meth == "include" and pos:
413
+ for p in pos:
414
+ ct = const_text(p)
415
+ if ct:
416
+ m.includes.append(ct)
417
+ elif meth in ("included", "class_methods") and block is not None:
418
+ inner = next((c for c in block.named_children if c.type in ("block_body", "body_statement")), None)
419
+ if inner is not None:
420
+ self._body(m, inner, in_singleton=meth == "class_methods")
421
+ elif meth == "primary_abstract_class":
422
+ m.abstract = True
423
+ elif meth == "connects_to":
424
+ # connects_to database: { writing: :clickhouse, reading: :clickhouse } (Rails multiple databases)
425
+ for p in pairs:
426
+ if pair_key(p) == "database":
427
+ v = pair_value(p)
428
+ found = re.findall(r"(?:writing|reading)\s*:\s*:?['\"]?(\w+)", txt(v)) if v is not None else []
429
+ if found:
430
+ m.database = found[0]
431
+
432
+ def database_of(self, m: Model, depth: int = 0) -> str:
433
+ """The database name a model (or the abstract class above it) connects to, "" for the primary one."""
434
+ if m.database or depth > 12:
435
+ return m.database
436
+ p = self.parent(m)
437
+ return self.database_of(p, depth + 1) if p is not None else ""
438
+
439
+ def _enum(self, m: Model, pos, pairs) -> None:
440
+ opts = {pair_key(p): pair_value(p) for p in pairs}
441
+ col, values = None, None
442
+ if pos and symbol_name(pos[0]): # enum :status, { a: 0 }, prefix: true
443
+ col = symbol_name(pos[0])
444
+ values = pos[1] if len(pos) > 1 else None
445
+ if values is None:
446
+ # `enum :status, a: 0, b: 1` (the values as keyword pairs)
447
+ vals = {k: v for k, v in opts.items() if k not in ("prefix", "suffix", "_prefix", "_suffix", "default",
448
+ "scopes", "validate", "instance_methods")}
449
+ mapping = {k: self._enum_value(v) for k, v in vals.items()}
450
+ if mapping:
451
+ self._enum_add(m, col, mapping, opts)
452
+ return
453
+ else: # enum status: { a: 0 }
454
+ for k, v in opts.items():
455
+ if k and not k.startswith("_") and k not in ("prefix", "suffix", "default", "scopes") and v is not None \
456
+ and v.type in ("hash", "array"):
457
+ col, values = k, v
458
+ break
459
+ if col is None or values is None:
460
+ return
461
+ mapping: dict[str, str] = {}
462
+ if values.type == "hash":
463
+ for p in values.named_children:
464
+ if p.type == "pair":
465
+ k = pair_key(p)
466
+ if k:
467
+ mapping[k] = self._enum_value(pair_value(p))
468
+ elif values.type == "array":
469
+ for i, c in enumerate(values.named_children):
470
+ k = symbol_name(c)
471
+ if k:
472
+ mapping[k] = str(i)
473
+ elif values.type == "string_array" or values.type == "symbol_array":
474
+ for i, c in enumerate(values.named_children):
475
+ mapping[txt(c)] = str(i)
476
+ if mapping:
477
+ self._enum_add(m, col, mapping, opts)
478
+
479
+ @staticmethod
480
+ def _enum_value(v) -> str:
481
+ if v is None:
482
+ return "NULL"
483
+ if v.type == "integer":
484
+ return txt(v)
485
+ s = string_text(v)
486
+ if s is not None:
487
+ return "'" + s.replace("'", "''") + "'"
488
+ return mark(txt(v))
489
+
490
+ def _enum_add(self, m: Model, col: str, mapping: dict, opts: dict) -> None:
491
+ m.enums[col] = mapping
492
+
493
+ def affix(key: str) -> str:
494
+ v = opts.get(key) if key in opts else opts.get("_" + key)
495
+ if v is None:
496
+ return ""
497
+ if txt(v) == "true":
498
+ return col
499
+ return symbol_name(v) or ""
500
+ pre, suf = affix("prefix"), affix("suffix")
501
+ if "scopes" in opts and txt(opts["scopes"]) == "false":
502
+ return
503
+ for k, stored in mapping.items():
504
+ name = (pre + "_" if pre else "") + k + ("_" + suf if suf else "")
505
+ m.enum_scopes[name] = (col, stored, False)
506
+ m.enum_scopes["not_" + name] = (col, stored, True)
507
+
508
+ # -- lookup
509
+ def lookup(self, name: str, nesting: list[str]) -> Model | None:
510
+ name = name.lstrip(":")
511
+ for i in range(len(nesting), -1, -1):
512
+ full = "::".join(nesting[:i] + [name])
513
+ if full in self.by_name:
514
+ return self.by_name[full]
515
+ return None
516
+
517
+ def model(self, name: str, nesting: list[str]) -> Model | None:
518
+ m = self.lookup(name, nesting)
519
+ return m if m is not None and self.is_model(m) else None
520
+
521
+ def parent(self, m: Model) -> Model | None:
522
+ if not m.superclass:
523
+ return None
524
+ return self.lookup(m.superclass, m.nesting) or self.lookup(m.superclass, m.name.split("::"))
525
+
526
+ def is_model(self, m: Model, depth: int = 0) -> bool:
527
+ if m.is_module or depth > 12:
528
+ return False
529
+ if m.superclass in ("ApplicationRecord", "ActiveRecord::Base", "::ActiveRecord::Base", "::ApplicationRecord"):
530
+ if m.superclass.lstrip(":") == "ApplicationRecord" and self.lookup("ApplicationRecord", []) is not None and \
531
+ not self.is_model(self.by_name["ApplicationRecord"], depth + 1) and m.name != "ApplicationRecord":
532
+ return False
533
+ return True
534
+ p = self.parent(m)
535
+ return p is not None and p is not m and self.is_model(p, depth + 1)
536
+
537
+ def is_abstract(self, m: Model) -> bool:
538
+ return m.abstract or m.name == "ApplicationRecord" or m.superclass.lstrip(":") == "ActiveRecord::Base" and m.name.endswith("Record") and m.abstract
539
+
540
+ def base(self, m: Model, depth: int = 0) -> Model:
541
+ """The class whose table an STI subclass shares."""
542
+ p = self.parent(m)
543
+ if p is None or depth > 12 or not self.is_model(p) or self.is_abstract(p) or m.table_name:
544
+ return m
545
+ return self.base(p, depth + 1)
546
+
547
+ def table(self, m: Model) -> str:
548
+ b = self.base(m)
549
+ if b.table_name:
550
+ return b.table_name
551
+ parts = b.name.split("::")
552
+ short = parts[-1]
553
+ prefix = ""
554
+ if len(parts) > 1:
555
+ outer = self.by_name.get("::".join(parts[:-1]))
556
+ if outer is not None and outer.prefix is not None:
557
+ prefix = outer.prefix
558
+ elif outer is not None and not outer.is_module and self.is_model(outer) and not self.is_abstract(outer):
559
+ prefix = singularize(self.table(outer)) + "_"
560
+ name = prefix + pluralize(underscore(short))
561
+ if self.schema_tables and name not in self.schema_tables:
562
+ alt = pluralize(underscore(b.name.replace("::", "")))
563
+ if alt in self.schema_tables:
564
+ return alt
565
+ return name
566
+
567
+ def sti_type(self, m: Model) -> str | None:
568
+ b = self.base(m)
569
+ return m.name if b is not m else None
570
+
571
+ def chain(self, m: Model, attr: str):
572
+ """Look `attr` up on the model, its included concerns and its superclasses."""
573
+ seen = set()
574
+ stack = [m]
575
+ while stack:
576
+ cur = stack.pop(0)
577
+ if cur is None or cur.name in seen:
578
+ continue
579
+ seen.add(cur.name)
580
+ got = getattr(cur, attr)
581
+ yield cur, got
582
+ for inc in cur.includes:
583
+ stack.append(self.lookup(inc, cur.name.split("::")) or self.lookup(inc, cur.nesting))
584
+ stack.append(self.parent(cur))
585
+
586
+ def find(self, m: Model, attr: str, key: str):
587
+ for owner, got in self.chain(m, attr):
588
+ if key in got:
589
+ return owner, got[key]
590
+ return None, None
591
+
592
+ def discard(self, m: Model) -> str:
593
+ """The discard gem's column of a model that includes Discard::Model ("" otherwise)."""
594
+ found, col = False, ""
595
+ for cur, inc in self.chain(m, "includes"):
596
+ found = found or any(i.lstrip(":") == "Discard::Model" for i in inc)
597
+ col = col or cur.discard_column
598
+ return (col or "discarded_at") if found else ""
599
+
600
+ def enum_of(self, m: Model, col: str) -> dict | None:
601
+ return self.find(m, "enums", col)[1]
602
+
603
+ def assoc(self, m: Model, name: str) -> Assoc | None:
604
+ return self.find(m, "assocs", name)[1]
605
+
606
+ def assoc_model(self, m: Model, a: Assoc) -> Model | None:
607
+ cname = a.class_name or classify(a.name)
608
+ return self.model(cname, m.name.split("::")) or self.model(cname, m.nesting)
609
+
610
+ def default_scopes(self, m: Model) -> list:
611
+ out = []
612
+ for _, got in self.chain(m, "default_scopes"):
613
+ out.extend(got)
614
+ return out
615
+
616
+ def columns(self, table: str) -> set[str] | None:
617
+ return self.schema_tables.get(table)
618
+
619
+
620
+ # ---- query state ----------------------------------------------------------------------------------------------------
621
+
622
+ @dataclass
623
+ class Q:
624
+ model: Model
625
+ table: str
626
+ wheres: list[str] = field(default_factory=list)
627
+ joins: list[str] = field(default_factory=list)
628
+ joined: dict[str, str] = field(default_factory=dict) # association path -> alias
629
+ order: list[str] = field(default_factory=list)
630
+ limit: str | None = None
631
+ offset: str | None = None
632
+ select: list[str] | None = None
633
+ distinct: bool = False
634
+ group: list[str] = field(default_factory=list)
635
+ having: list[str] = field(default_factory=list)
636
+ lock: bool = False
637
+ preloads: list[list[str]] = field(default_factory=list)
638
+ eager: list[str] = field(default_factory=list)
639
+ unscoped: bool = False
640
+ from_: str | None = None
641
+ notes: list[str] = field(default_factory=list)
642
+ confidence: str = "high"
643
+ none: bool = False
644
+ batch: bool = False
645
+
646
+ def copy(self) -> "Q":
647
+ q = Q(self.model, self.table)
648
+ for k in self.__dataclass_fields__:
649
+ v = getattr(self, k)
650
+ setattr(q, k, list(v) if isinstance(v, list) else dict(v) if isinstance(v, dict) else v)
651
+ return q
652
+
653
+ def lower(self, level: str) -> None:
654
+ order = ("low", "medium", "high")
655
+ if order.index(level) < order.index(self.confidence):
656
+ self.confidence = level
657
+
658
+
659
+ class Ctx:
660
+ """Where a chain is translated: the file, the enclosing class (for implicit receivers), the parameter bindings
661
+ of an inlined scope, the depth of inlining."""
662
+
663
+ def __init__(self, tr: "Translator", rel: str, nesting: list[str], env: dict | None = None, depth: int = 0):
664
+ self.tr, self.rel, self.nesting, self.env, self.depth = tr, rel, nesting, env or {}, depth
665
+
666
+
667
+ QUERY_METHODS = {"where", "rewhere", "not", "or", "and", "joins", "left_joins", "left_outer_joins", "includes", "preload",
668
+ "eager_load", "references", "order", "reorder", "in_order_of", "limit", "offset", "select", "reselect",
669
+ "distinct", "uniq", "group", "having", "lock", "all", "unscoped", "unscope", "readonly", "strict_loading",
670
+ "extending", "merge", "from", "none", "page", "per", "except", "only", "annotate", "optimizer_hints",
671
+ "with", "excluding", "without", "invert_where", "regroup", "create_with", "distinct_on", "load_async",
672
+ "cache", "uncached", "includes_values", "joins_values", "rewhere", "where_values_hash"}
673
+ TERMINALS = {"find", "find!", "find_by", "find_by!", "find_sole_by", "sole", "first", "first!", "last", "last!", "take", "take!",
674
+ "second", "third", "count", "size", "length", "sum", "maximum", "minimum", "average", "calculate", "pluck", "pick",
675
+ "ids", "exists?", "any?", "many?", "none?", "empty?", "present?", "blank?", "one?", "to_a", "to_ary", "load", "records",
676
+ "each", "map", "collect", "flat_map", "each_with_object", "each_with_index", "index_by", "index_with", "group_by",
677
+ "filter_map", "sort_by", "reject", "partition", "inject", "reduce", "sum_by", "each_slice", "to_h", "detect",
678
+ "find_each", "find_in_batches", "in_batches",
679
+ "update_all", "delete_all", "destroy_all", "delete_by", "destroy_by", "update_counters", "touch_all",
680
+ "create", "create!", "new", "build", "insert", "insert!", "insert_all", "insert_all!", "upsert", "upsert_all",
681
+ "find_or_create_by", "find_or_create_by!", "find_or_initialize_by", "create_or_find_by", "create_or_find_by!",
682
+ "first_or_create", "first_or_create!", "first_or_initialize", "update", "update!", "delete", "destroy", "destroy!",
683
+ "increment_counter", "decrement_counter", "find_by_sql", "count_by_sql", "pluck_each"}
684
+ # Ruby methods (Array / Enumerable / Object) after a relation: the relation is loaded there
685
+ RUBY_LOADS = {"reverse", "include?", "nil?", "sort", "compact", "to_set", "sample", "shuffle", "lazy", "zip", "min_by", "max_by",
686
+ "tally", "as_json", "to_json", "each_slice", "uniq", "select!", "filter", "find_index", "pluck_in_batches",
687
+ "presence", "then", "tap", "first", "last", "to_sql", "explain", "inspect"}
688
+ NOT_QUERIES = {"transaction", "connection", "new", "name", "table_name", "arel_table", "reflect_on_association", "human_attribute_name",
689
+ "model_name", "columns", "column_names", "primary_key", "sanitize_sql", "sanitize_sql_array", "sanitize_sql_like",
690
+ "with_advisory_lock", "lease_connection", "with_connection", "class", "to_s", "respond_to?", "instance_method",
691
+ "reflect_on_all_associations", "attribute_names", "type_for_attribute", "enum_for", "ancestors", "const_get",
692
+ "send", "public_send", "method", "build", "upsert_all_", "insert_all_", "connected_to", "while_preventing_writes",
693
+ "table_exists?", "reset_column_information", "uncached", "suppress", "no_touching", "inspect", "descendants",
694
+ "defined_enums", "statuses", "translate", "t", "i18n_scope", "unscoped_"}
695
+
696
+
697
+ class Untranslatable(Exception):
698
+ pass
699
+
700
+
701
+ class Translator:
702
+ def __init__(self, models: Models, engine: str = "", resolver=None) -> None:
703
+ self.models = models
704
+ self.engine = engine
705
+ # the file-level lookups (heredoc bodies, local variables, constants): ruby.FileScope
706
+ self.tr = resolver
707
+
708
+ # -- quoting
709
+ def q(self, name: str) -> str:
710
+ if name.startswith("«") or name == "*":
711
+ return name
712
+ if self.engine == "mysql":
713
+ return "`" + name + "`"
714
+ return '"' + name + '"'
715
+
716
+ def col(self, table: str, col: str) -> str:
717
+ if "." in col and not col.startswith("«"):
718
+ t, c = col.split(".", 1)
719
+ return self.q(t) + "." + (c if c == "*" else self.q(c))
720
+ return self.q(table) + "." + self.q(col)
721
+
722
+ # -- values
723
+ def value(self, node, ctx: Ctx, enum: dict | None = None) -> str:
724
+ if node is None:
725
+ return "NULL"
726
+ if node.type == "identifier" and txt(node) in ctx.env and ctx.env[txt(node)] is not None:
727
+ return self.value(ctx.env[txt(node)], Ctx(self, ctx.rel, ctx.nesting, None, ctx.depth), enum)
728
+ t = node.type
729
+ if t == "parenthesized_statements" and len(node.named_children) == 1:
730
+ return self.value(node.named_children[0], ctx, enum)
731
+ if t in ("simple_symbol", "string", "delimited_symbol"):
732
+ s = string_text(node)
733
+ if s is not None:
734
+ if enum and s in enum:
735
+ return enum[s]
736
+ return "'" + s.replace("'", "''") + "'"
737
+ return mark(txt(node))
738
+ if t in ("integer", "float"):
739
+ return txt(node).replace("_", "")
740
+ if t in ("true", "false"):
741
+ return t.upper()
742
+ if t == "nil":
743
+ return "NULL"
744
+ if t == "unary" and txt(node).startswith("-") and node.named_children and node.named_children[0].type in ("integer", "float"):
745
+ return txt(node).replace("_", "")
746
+ return mark(txt(node))
747
+
748
+ def predicate(self, table: str, col: str, vnode, ctx: Ctx, model: Model | None, negate: bool = False) -> str:
749
+ enum = self.models.enum_of(model, col) if model is not None else None
750
+ c = self.col(table, col)
751
+ if vnode is not None and vnode.type == "identifier" and txt(vnode) in ctx.env and ctx.env[txt(vnode)] is not None:
752
+ return self.predicate(table, col, ctx.env[txt(vnode)], Ctx(self, ctx.rel, ctx.nesting, None, ctx.depth), model, negate)
753
+ if vnode is None or vnode.type == "nil":
754
+ return f"{c} IS {'NOT ' if negate else ''}NULL"
755
+ if vnode.type == "array":
756
+ items = [x for x in vnode.named_children if x.type != "comment"]
757
+ if any(x.type == "splat_argument" for x in items):
758
+ return f"{c} {'NOT ' if negate else ''}IN ({mark(txt(vnode))})"
759
+ has_nil = any(x.type == "nil" for x in items)
760
+ vals = [self.value(x, ctx, enum) for x in items if x.type != "nil"]
761
+ if not vals:
762
+ p = f"{c} IS NULL" if has_nil else "1=0"
763
+ elif len(vals) == 1:
764
+ p = f"{c} = {vals[0]}"
765
+ else:
766
+ p = f"{c} IN ({', '.join(vals)})"
767
+ if has_nil and vals:
768
+ p = f"({p} OR {c} IS NULL)"
769
+ return f"NOT ({p})" if negate else p
770
+ if vnode.type == "range":
771
+ kids = [k for k in vnode.children]
772
+ op = next((txt(k) for k in kids if txt(k) in ("..", "...")), "..")
773
+ named = vnode.named_children
774
+ begin = vnode.child_by_field_name("begin")
775
+ end = vnode.child_by_field_name("end")
776
+ if begin is None and end is None and len(named) == 2:
777
+ begin, end = named
778
+ if begin is None and end is None and len(named) == 1:
779
+ if kids and txt(kids[0]) in ("..", "..."):
780
+ end = named[0]
781
+ else:
782
+ begin = named[0]
783
+ parts = []
784
+ if begin is not None and end is not None and op == "..":
785
+ p = f"{c} BETWEEN {self.value(begin, ctx)} AND {self.value(end, ctx)}"
786
+ else:
787
+ if begin is not None:
788
+ parts.append(f"{c} >= {self.value(begin, ctx)}")
789
+ if end is not None:
790
+ parts.append(f"{c} {'<' if op == '...' else '<='} {self.value(end, ctx)}")
791
+ p = " AND ".join(parts) or "1=1"
792
+ return f"NOT ({p})" if negate else p
793
+ sub = self.subquery(vnode, ctx)
794
+ if sub is not None:
795
+ return f"{c} {'NOT ' if negate else ''}IN ({sub})"
796
+ v = self.value(vnode, ctx, enum)
797
+ if v.startswith("«") and (re.search(r"(?:ids|_ids|s)»$", v) or re.search(
798
+ r"\.(?:map|filter_map|flat_map|pluck|ids|split|to_a|uniq|compact|keys|values|select|reject|collect)\b[^»]*»$", v)):
799
+ return f"{c} {'NOT ' if negate else ''}IN ({v})"
800
+ return f"{c} {'!=' if negate else '='} {v}"
801
+
802
+ def subquery(self, node, ctx: Ctx) -> str | None:
803
+ """`Account.where(...).select(:id)` used as a value: the subquery ActiveRecord nests."""
804
+ if node is None or node.type != "call":
805
+ return None
806
+ steps = self.tr_steps(node)
807
+ if steps is None:
808
+ return None
809
+ root, chain = steps
810
+ m = self.root_model(root, ctx)
811
+ if m is None:
812
+ return None
813
+ if any(s[1] in TERMINALS - {"ids"} for s in chain):
814
+ return None
815
+ q = self.start(m)
816
+ try:
817
+ self.apply(q, chain, ctx)
818
+ except Untranslatable:
819
+ return None
820
+ if q.select is None:
821
+ q.select = [self.col(q.table, "id")]
822
+ return self.render_select(q)
823
+
824
+ # -- conditions
825
+ def hash_conditions(self, q: Q, model: Model, table: str, pairs, ctx: Ctx, negate: bool = False) -> list[str]:
826
+ preds = []
827
+ for p in pairs:
828
+ if p.type == "hash_splat_argument":
829
+ preds.append(mark(txt(p)))
830
+ q.lower("medium")
831
+ continue
832
+ key = pair_key(p)
833
+ v = pair_value(p)
834
+ if key is None:
835
+ k = p.child_by_field_name("key")
836
+ preds.append(f"{mark(txt(k))} = {self.value(v, ctx)}")
837
+ q.lower("low")
838
+ q.notes.append("a condition's column is chosen at run time")
839
+ continue
840
+ if v is not None and v.type == "hash":
841
+ a = self.models.assoc(model, key)
842
+ sub_model = self.models.assoc_model(model, a) if a is not None and not a.polymorphic else None
843
+ sub_table = self.models.table(sub_model) if sub_model is not None else key
844
+ alias = q.joined.get(key, sub_table)
845
+ inner = [x for x in v.named_children if x.type == "pair"]
846
+ preds.extend(self.hash_conditions(q, sub_model or model, alias, inner, ctx, negate=False))
847
+ if key not in q.joined and sub_table != q.table:
848
+ q.eager.append(key)
849
+ continue
850
+ if "." in key:
851
+ t, c = key.split(".", 1)
852
+ preds.append(self.predicate(t, c, v, ctx, None))
853
+ continue
854
+ a = self.models.assoc(model, key)
855
+ if a is not None and a.kind == "belongs_to":
856
+ fk = a.foreign_key or key + "_id"
857
+ if a.polymorphic:
858
+ preds.append(f"{self.col(table, key + '_type')} = {mark(txt(v) + '.class')}")
859
+ preds.append(self.predicate(table, fk, v, ctx, None))
860
+ continue
861
+ preds.append(self.predicate(table, key, v, ctx, model))
862
+ if negate and preds:
863
+ return [f"NOT ({' AND '.join(preds)})"] if len(preds) > 1 else [f"NOT ({preds[0]})" if not preds[0].startswith("NOT (") else preds[0][5:-1]]
864
+ return preds
865
+
866
+ def fragment(self, pos, pairs, ctx: Ctx, q: Q) -> str | None:
867
+ """`where("a = ? AND b = :b", x, b: y)`, `where(["a = ?", x])`: the SQL fragment with its binds as values."""
868
+ if not pos:
869
+ return None
870
+ first = pos[0]
871
+ rest = pos[1:]
872
+ if first.type == "array" and first.named_children:
873
+ items = [x for x in first.named_children if x.type != "comment"]
874
+ first, rest = items[0], items[1:]
875
+ pairs = list(pairs) + [x for r in rest if r.type == "hash" for x in r.named_children if x.type == "pair"]
876
+ pairs += [x for x in rest if x.type == "pair"]
877
+ rest = [r for r in rest if r.type not in ("hash", "pair")]
878
+ text = self.string_of(first, ctx)
879
+ if text is None:
880
+ return None
881
+ binds = list(rest)
882
+ named = {pair_key(p): pair_value(p) for p in pairs}
883
+
884
+ def qmark(_m):
885
+ if binds:
886
+ return self.value(binds.pop(0), ctx)
887
+ q.lower("medium")
888
+ return "«?»"
889
+ out = re.sub(r"\?", qmark, text)
890
+ if named:
891
+ def named_bind(m):
892
+ k = m.group(1)
893
+ return self.value(named[k], ctx) if k in named else m.group(0)
894
+ out = re.sub(r"(?<!:):(\w+)", named_bind, out)
895
+ return norm(out)
896
+
897
+ def string_of(self, node, ctx: Ctx, depth: int = 0) -> str | None:
898
+ """A string argument's text: literal, interpolated (parts as «expr»), heredoc, `Arel.sql(...)`, a constant or a
899
+ local variable assigned one string."""
900
+ if node is None or depth > 4:
901
+ return None
902
+ if node.type == "string":
903
+ return interpolated(node)
904
+ if node.type == "heredoc_beginning":
905
+ body = self.tr.heredoc_body(node)
906
+ return interpolated(body) if body is not None else None
907
+ if node.type == "call":
908
+ recv, meth, pos, _, _ = call_parts(node)
909
+ if txt(recv) == "Arel" and meth == "sql" and pos:
910
+ return self.string_of(pos[0], ctx, depth + 1)
911
+ if meth in ("squish", "strip", "freeze", "dup", "chomp", "squish!") and recv is not None:
912
+ s = self.string_of(recv, ctx, depth + 1)
913
+ return norm(s) if s is not None else None
914
+ if meth in ("sanitize_sql_array", "sanitize_sql", "sanitize_sql_for_conditions") and pos:
915
+ # sanitize_sql_array([<<~SQL, a, b]): the statement with its `?` / `:name` binds as values
916
+ first = pos[0].named_children[0] if pos[0].type == "array" and pos[0].named_children else pos[0]
917
+ return self.string_of(first, ctx, depth + 1)
918
+ if node.type == "identifier":
919
+ bound = self.tr.local_value(node)
920
+ if bound is not None:
921
+ return self.string_of(bound, ctx, depth + 1)
922
+ if node.type in ("constant", "scope_resolution"):
923
+ bound = self.tr.constant_value(const_text(node), ctx.nesting)
924
+ if bound is not None:
925
+ return self.string_of(bound, ctx, depth + 1)
926
+ return None
927
+
928
+ # -- chain decomposition
929
+ @staticmethod
930
+ def tr_steps(node):
931
+ """(root node, [(node, method, pos, pairs, block)]) of a call chain, innermost first."""
932
+ steps = []
933
+ n = node
934
+ while n is not None and n.type == "call":
935
+ recv, meth, pos, pairs, block = call_parts(n)
936
+ steps.append((n, meth, pos, pairs, block))
937
+ n = recv
938
+ steps.reverse()
939
+ return n, steps
940
+
941
+ def root_model(self, root, ctx: Ctx) -> Model | None:
942
+ ct = const_text(root)
943
+ if ct is None:
944
+ return None
945
+ return self.models.model(ct, ctx.nesting)
946
+
947
+ def start(self, m: Model, unscoped: bool = False) -> Q:
948
+ q = Q(m, self.models.table(m))
949
+ typ = self.models.sti_type(m)
950
+ if typ:
951
+ b = self.models.base(m)
952
+ col = b.inheritance_column
953
+ cols = self.models.columns(q.table)
954
+ if cols is None or col in cols:
955
+ subs = [x.name for x in self.models.by_name.values() if not x.is_module and x is not m
956
+ and self._descends(x, m)]
957
+ names = [m.name] + sorted(subs)
958
+ vals = ", ".join("'" + n + "'" for n in names)
959
+ q.wheres.append(f"{self.col(q.table, col)} = {vals}" if len(names) == 1 else f"{self.col(q.table, col)} IN ({vals})")
960
+ return q
961
+
962
+ def _descends(self, x: Model, m: Model, depth: int = 0) -> bool:
963
+ p = self.models.parent(x)
964
+ if p is None or depth > 12:
965
+ return False
966
+ return p is m or self._descends(p, m, depth + 1)
967
+
968
+ def apply_default(self, q: Q, ctx: Ctx) -> None:
969
+ if q.unscoped or ctx.depth > SETTINGS["ar_max_inline_depth"]:
970
+ return
971
+ for body in self.models.default_scopes(q.model):
972
+ self.inline(q, body, [], [], ctx)
973
+
974
+ # -- applying query methods
975
+ def apply(self, q: Q, steps, ctx: Ctx) -> str | None:
976
+ """Apply the query methods of `steps` to q; returns the terminal method (or None when the chain ends as a
977
+ relation). Raises Untranslatable when the chain reaches a method that ends ActiveRecord's part."""
978
+ pending_not = False
979
+ for i, (node, meth, pos, pairs, block) in enumerate(steps):
980
+ if meth == "where" and not pos and not pairs:
981
+ pending_not = True if i + 1 < len(steps) and steps[i + 1][1] in ("not", "missing", "associated") else pending_not
982
+ continue
983
+ if meth == "not":
984
+ self.where(q, pos, pairs, ctx, negate=True)
985
+ pending_not = False
986
+ continue
987
+ if meth in ("missing", "associated") and pending_not is not None:
988
+ for p in pos:
989
+ name = symbol_name(p)
990
+ a = self.models.assoc(q.model, name) if name else None
991
+ if a is None:
992
+ continue
993
+ alias, tm = self.join(q, q.model, q.table, name, left=True)
994
+ if alias:
995
+ q.wheres.append(f"{self.col(alias, 'id')} IS {'' if meth == 'missing' else 'NOT '}NULL")
996
+ continue
997
+ if meth in ("where", "rewhere", "and"):
998
+ self.where(q, pos, pairs, ctx)
999
+ elif meth == "or":
1000
+ q.wheres = [f"({' AND '.join(q.wheres) or '1=1'}) OR {mark(txt(pos[0]) if pos else 'or')}"] if q.wheres else q.wheres
1001
+ q.lower("low")
1002
+ q.notes.append("`.or` relation is read as a run-time part")
1003
+ elif meth in ("joins", "left_joins", "left_outer_joins", "eager_load"):
1004
+ self.joins(q, pos, pairs, ctx, left=meth != "joins")
1005
+ elif meth in ("includes", "preload"):
1006
+ for path in self.assoc_paths(pos, pairs):
1007
+ q.preloads.append(path)
1008
+ elif meth == "references":
1009
+ q.eager.extend(n for n in (symbol_name(p) for p in pos) if n)
1010
+ elif meth in ("order", "reorder", "in_order_of"):
1011
+ if meth == "reorder":
1012
+ q.order = []
1013
+ self.order(q, pos, pairs, ctx)
1014
+ elif meth == "limit":
1015
+ q.limit = self.value(pos[0], ctx) if pos else None
1016
+ elif meth == "offset":
1017
+ q.offset = self.value(pos[0], ctx) if pos else None
1018
+ elif meth == "page":
1019
+ size = q.limit or str(SETTINGS["ar_page_size"])
1020
+ q.limit = size
1021
+ q.offset = mark(f"({txt(pos[0]) if pos else 'page'} - 1) * {size}")
1022
+ elif meth == "per":
1023
+ q.limit = self.value(pos[0], ctx) if pos else q.limit
1024
+ elif meth in ("select", "reselect") and block is None:
1025
+ cols = self.columns(q, pos, ctx)
1026
+ if cols:
1027
+ q.select = cols if meth == "reselect" or q.select is None else q.select + cols
1028
+ elif meth in ("distinct", "uniq"):
1029
+ q.distinct = True
1030
+ elif meth in ("group", "regroup"):
1031
+ q.group = [] if meth == "regroup" else q.group
1032
+ q.group.extend(self.columns(q, pos, ctx))
1033
+ elif meth == "having":
1034
+ f = self.fragment(pos, pairs, ctx, q)
1035
+ if f:
1036
+ q.having.append(f)
1037
+ elif meth == "lock":
1038
+ q.lock = True
1039
+ elif meth == "unscoped":
1040
+ q.unscoped = True
1041
+ q.wheres = [w for w in q.wheres if "_default_" not in w]
1042
+ elif meth == "none":
1043
+ q.none = True
1044
+ elif meth == "from":
1045
+ s = self.string_of(pos[0], ctx) if pos else None
1046
+ q.from_ = s if s is not None else (self.subquery(pos[0], ctx) if pos else None)
1047
+ if q.from_ is None:
1048
+ q.from_ = mark(txt(pos[0]) if pos else "from")
1049
+ elif not s:
1050
+ q.from_ = f"({q.from_}) {self.q(q.table)}"
1051
+ elif meth == "merge":
1052
+ self.merge(q, pos, ctx)
1053
+ elif meth in ("all", "readonly", "strict_loading", "extending", "annotate", "optimizer_hints", "load_async",
1054
+ "cache", "includes_values", "create_with", "unscope", "except", "only", "with", "distinct_on",
1055
+ "excluding", "without", "invert_where", "uncached"):
1056
+ if meth in ("excluding", "without") and pos:
1057
+ q.wheres.append(f"{self.col(q.table, 'id')} NOT IN ({', '.join(mark(txt(p) + '.id') for p in pos)})")
1058
+ continue
1059
+ elif meth in TERMINALS:
1060
+ return meth
1061
+ else:
1062
+ if not self.named_scope(q, meth, pos, pairs, ctx):
1063
+ raise Untranslatable(meth)
1064
+ return None
1065
+
1066
+ def where(self, q: Q, pos, pairs, ctx: Ctx, negate: bool = False) -> None:
1067
+ preds = []
1068
+ if pairs:
1069
+ preds.extend(self.hash_conditions(q, q.model, q.table, pairs, ctx, negate))
1070
+ if pos:
1071
+ first = pos[0]
1072
+ if first.type == "hash":
1073
+ inner = [x for x in first.named_children if x.type in ("pair", "hash_splat_argument")]
1074
+ preds.extend(self.hash_conditions(q, q.model, q.table, inner, ctx, negate))
1075
+ else:
1076
+ f = self.fragment(pos, pairs if not preds else [], ctx, q)
1077
+ if f is not None:
1078
+ preds.append(f"NOT ({f})" if negate else f"({f})")
1079
+ elif not pairs:
1080
+ sub = self.arel(first, q, ctx) if first.type in ("call", "element_reference") else None
1081
+ if sub is None and first.type == "call":
1082
+ sub = self.relation_conditions(first, ctx)
1083
+ if sub:
1084
+ preds.append(f"NOT ({sub})" if negate else sub)
1085
+ else:
1086
+ preds.append(mark(txt(first)))
1087
+ q.lower("medium")
1088
+ q.notes.append("a condition is built at run time")
1089
+ q.wheres.extend(preds)
1090
+
1091
+ def relation_conditions(self, node, ctx: Ctx) -> str | None:
1092
+ root, steps = self.tr_steps(node)
1093
+ m = self.root_model(root, ctx)
1094
+ if m is None:
1095
+ return None
1096
+ sub = self.start(m)
1097
+ try:
1098
+ self.apply(sub, steps, ctx)
1099
+ except Untranslatable:
1100
+ return None
1101
+ return " AND ".join(sub.wheres) if sub.wheres else None
1102
+
1103
+ def merge(self, q: Q, pos, ctx: Ctx) -> None:
1104
+ if not pos:
1105
+ return
1106
+ node = pos[0]
1107
+ if node.type == "call" or const_text(node):
1108
+ root, steps = self.tr_steps(node) if node.type == "call" else (node, [])
1109
+ m = self.root_model(root, ctx)
1110
+ if m is not None:
1111
+ sub = self.start(m)
1112
+ sub.joined = dict(q.joined)
1113
+ try:
1114
+ self.apply(sub, steps, ctx)
1115
+ q.wheres.extend(sub.wheres)
1116
+ q.order.extend(sub.order)
1117
+ for j in sub.joins:
1118
+ if j not in q.joins:
1119
+ q.joins.append(j)
1120
+ return
1121
+ except Untranslatable:
1122
+ pass
1123
+ q.wheres.append(mark("merge(" + txt(node) + ")"))
1124
+ q.lower("low")
1125
+ q.notes.append("`.merge` of a relation built at run time")
1126
+
1127
+ def named_scope(self, q: Q, meth: str, pos, pairs, ctx: Ctx) -> bool:
1128
+ """A scope, an enum scope or a single-expression class method of the model, inlined."""
1129
+ if meth.endswith(("=", "!")) and meth not in ("find_by!",):
1130
+ return False
1131
+ owner, es = self.models.find(q.model, "enum_scopes", meth)
1132
+ if es is not None:
1133
+ col, stored, negated = es
1134
+ q.wheres.append(f"{self.col(q.table, col)} {'!=' if negated else '='} {stored}")
1135
+ return True
1136
+ discard = self.models.discard(q.model)
1137
+ if discard and meth in ("kept", "undiscarded", "discarded", "with_discarded"):
1138
+ cond = f"{self.col(q.table, discard)} IS NULL"
1139
+ q.wheres = [w for w in q.wheres if w not in (cond, cond.replace("IS NULL", "IS NOT NULL"))]
1140
+ if meth != "with_discarded":
1141
+ q.wheres.append(cond if meth != "discarded" else cond.replace("IS NULL", "IS NOT NULL"))
1142
+ return True
1143
+ owner, sc = self.models.find(q.model, "scopes", meth)
1144
+ if sc is None:
1145
+ owner, sc = self.models.find(q.model, "class_methods", meth)
1146
+ if sc is not None and (sc[1] is None or not self._chainish(sc[1])):
1147
+ sc = None
1148
+ q.wheres.append(mark(f"{q.model.name.split('::')[-1]}.{meth}"))
1149
+ q.lower("low")
1150
+ q.notes.append(f"class method `{meth}` is not a single query expression: its conditions are a run-time part")
1151
+ return True
1152
+ if sc is None:
1153
+ if meth.startswith(("find_by_", "find_all_by_")): # dynamic finders
1154
+ cols = meth.split("_by_", 1)[1].rstrip("!").split("_and_")
1155
+ for c, v in zip(cols, pos):
1156
+ q.wheres.append(self.predicate(q.table, c, v, ctx, q.model))
1157
+ q.limit = "1" if meth.startswith("find_by_") else q.limit
1158
+ return True
1159
+ return False
1160
+ params, body = sc
1161
+ if body is None or ctx.depth >= SETTINGS["ar_max_inline_depth"]:
1162
+ q.wheres.append(mark(f"{meth}"))
1163
+ q.lower("low")
1164
+ q.notes.append(f"scope `{meth}` is not read (not a single expression)")
1165
+ return True
1166
+ self.inline(q, body, params, list(pos) + ([None] if False else []), ctx, owner=owner)
1167
+ return True
1168
+
1169
+ @staticmethod
1170
+ def _chainish(node) -> bool:
1171
+ n = node
1172
+ while n is not None and n.type == "call":
1173
+ n = n.child_by_field_name("receiver")
1174
+ return n is None or n.type in ("self", "constant", "scope_resolution")
1175
+
1176
+ def inline(self, q: Q, body, params: list[str], args, ctx: Ctx, owner: Model | None = None) -> None:
1177
+ env = {p: (args[i] if i < len(args) else None) for i, p in enumerate(params) if p}
1178
+ sub_ctx = Ctx(self, ctx.rel, (owner or q.model).name.split("::"), {**ctx.env, **env}, ctx.depth + 1)
1179
+ if body.type == "call" or body.type in ("identifier",):
1180
+ root, steps = self.tr_steps(body) if body.type == "call" else (None, [(body, txt(body), [], [], None)])
1181
+ if root is not None and root.type == "identifier" and txt(root) not in sub_ctx.env:
1182
+ # `where.not(...)`, `published.where(...)`: a bare method name is a call on the implicit receiver
1183
+ steps = [(root, txt(root), [], [], None)] + list(steps)
1184
+ root = None
1185
+ if root is not None and root.type not in ("self",):
1186
+ m = self.root_model(root, sub_ctx)
1187
+ if m is None:
1188
+ raise Untranslatable("scope body")
1189
+ if m is not q.model:
1190
+ # `scope :x, -> { Other.where(...) }` returns another model's relation: not inlined
1191
+ raise Untranslatable("scope of another model")
1192
+ term = self.apply(q, steps, sub_ctx)
1193
+ if term is not None:
1194
+ raise Untranslatable(term)
1195
+ return
1196
+ if body.type in ("if_modifier", "unless_modifier", "conditional", "if", "unless"):
1197
+ q.wheres.append(mark(txt(body)))
1198
+ q.lower("low")
1199
+ q.notes.append("a scope chooses its conditions at run time")
1200
+ return
1201
+ raise Untranslatable("scope body")
1202
+
1203
+ # -- Arel
1204
+ ARELOPS = {"eq": "=", "not_eq": "!=", "gt": ">", "gteq": ">=", "lt": "<", "lteq": "<="}
1205
+
1206
+ def arel(self, node, q: Q, ctx: Ctx, depth: int = 0) -> str | None:
1207
+ """An Arel expression (`arel_table[:c].eq(v)`, `.matches`, `.in`, `.lower`, `.desc`, `.or`, `Arel.sql`, `Arel.star`)
1208
+ as SQL; None when the node is not one."""
1209
+ if node is None or depth > 12:
1210
+ return None
1211
+ if node.type == "parenthesized_statements" and len(node.named_children) == 1:
1212
+ return self.arel(node.named_children[0], q, ctx, depth + 1)
1213
+ if node.type == "element_reference":
1214
+ obj = node.child_by_field_name("object")
1215
+ idx = [c for c in node.named_children if c is not obj and c.id != (obj.id if obj is not None else -1)]
1216
+ name = symbol_name(idx[0]) if idx else None
1217
+ if obj is None or name is None:
1218
+ return None
1219
+ ot = txt(obj)
1220
+ if ot == "arel_table":
1221
+ return self.col(q.table, name)
1222
+ m = re.fullmatch(r"([\w:]+)\.arel_table", ot)
1223
+ if m:
1224
+ mm = self.models.model(m.group(1), ctx.nesting)
1225
+ return self.col(self.models.table(mm) if mm else underscore(m.group(1)), name)
1226
+ return None
1227
+ if node.type != "call":
1228
+ return None
1229
+ recv, meth, pos, pairs, _ = call_parts(node)
1230
+ rt = txt(recv) if recv is not None else ""
1231
+ if rt == "Arel":
1232
+ if meth == "star":
1233
+ return "*"
1234
+ if meth == "sql" and pos:
1235
+ s = self.string_of(pos[0], ctx)
1236
+ return norm(s) if s is not None else None
1237
+ return None
1238
+ if recv is None:
1239
+ return None
1240
+ base = self.arel(recv, q, ctx, depth + 1)
1241
+ if base is None:
1242
+ return None
1243
+
1244
+ def val(n):
1245
+ a = self.arel(n, q, ctx, depth + 1) if n is not None and n.type in ("call", "element_reference") else None
1246
+ return a if a is not None else self.value(n, ctx)
1247
+ if meth in self.ARELOPS and pos:
1248
+ if pos[0].type == "nil":
1249
+ return f"{base} IS {'NOT ' if meth == 'not_eq' else ''}NULL"
1250
+ return f"{base} {self.ARELOPS[meth]} {val(pos[0])}"
1251
+ if meth in ("in", "not_in") and pos:
1252
+ p0 = pos[0]
1253
+ sub = self.subquery(p0, ctx) if p0.type == "call" else None
1254
+ inner = sub if sub is not None else (", ".join(self.value(x, ctx) for x in p0.named_children) if p0.type == "array"
1255
+ else self.value(p0, ctx))
1256
+ return f"{base} {'NOT ' if meth == 'not_in' else ''}IN ({inner})"
1257
+ if meth in ("matches", "does_not_match") and pos:
1258
+ sensitive = len(pos) > 2 and txt(pos[2]) == "true"
1259
+ op = "LIKE" if sensitive or self.engine not in ("postgres", "") else "ILIKE"
1260
+ return f"{base} {'NOT ' if meth == 'does_not_match' else ''}{op} {self.value(pos[0], ctx)}"
1261
+ if meth in ("lower", "upper"):
1262
+ return f"{meth.upper()}({base})"
1263
+ if meth in ("asc", "desc"):
1264
+ return f"{base} {meth.upper()}"
1265
+ if meth in ("count", "sum", "maximum", "minimum", "average"):
1266
+ fn = {"count": "COUNT", "sum": "SUM", "maximum": "MAX", "minimum": "MIN", "average": "AVG"}[meth]
1267
+ return f"{fn}({'DISTINCT ' if pos and txt(pos[0]) == 'true' else ''}{base})"
1268
+ if meth in ("or", "and") and pos:
1269
+ other = self.arel(pos[0], q, ctx, depth + 1)
1270
+ return None if other is None else f"({base} {meth.upper()} {other})"
1271
+ if meth == "not" and not pos:
1272
+ return f"NOT ({base})"
1273
+ if meth == "nulls_last":
1274
+ return f"{base} NULLS LAST"
1275
+ if meth == "nulls_first":
1276
+ return f"{base} NULLS FIRST"
1277
+ return None
1278
+
1279
+ # -- joins
1280
+ def assoc_paths(self, pos, pairs, prefix: list[str] | None = None) -> list[list[str]]:
1281
+ prefix = prefix or []
1282
+ out = []
1283
+ for p in pos:
1284
+ name = symbol_name(p)
1285
+ if name:
1286
+ out.append(prefix + [name])
1287
+ elif p.type == "array":
1288
+ out.extend(self.assoc_paths([x for x in p.named_children if x.type != "pair"],
1289
+ [x for x in p.named_children if x.type == "pair"], prefix))
1290
+ elif p.type == "hash":
1291
+ out.extend(self.assoc_paths([], [x for x in p.named_children if x.type == "pair"], prefix))
1292
+ for pr in pairs:
1293
+ k = pair_key(pr)
1294
+ if not k:
1295
+ continue
1296
+ out.append(prefix + [k])
1297
+ v = pair_value(pr)
1298
+ if v is not None:
1299
+ out.extend(self.assoc_paths([v] if v.type != "hash" else [], [x for x in v.named_children if x.type == "pair"]
1300
+ if v.type == "hash" else [], prefix + [k]))
1301
+ return out
1302
+
1303
+ def joins(self, q: Q, pos, pairs, ctx: Ctx, left: bool) -> None:
1304
+ for p in pos:
1305
+ s = self.string_of(p, ctx)
1306
+ if s is not None:
1307
+ q.joins.append(norm(s))
1308
+ continue
1309
+ paths = self.assoc_paths([p for p in pos if symbol_name(p) or p.type in ("array", "hash")], pairs)
1310
+ for path in paths:
1311
+ m, t = q.model, q.table
1312
+ key = ""
1313
+ for name in path:
1314
+ key = key + "." + name if key else name
1315
+ if key in q.joined:
1316
+ a = self.models.assoc(m, name)
1317
+ m = self.models.assoc_model(m, a) if a else m
1318
+ t = q.joined[key]
1319
+ continue
1320
+ alias, tm = self.join(q, m, t, name, left, key=key)
1321
+ if alias is None:
1322
+ break
1323
+ m, t = tm, alias
1324
+
1325
+ def join(self, q: Q, m: Model, table: str, name: str, left: bool, key: str | None = None):
1326
+ a = self.models.assoc(m, name)
1327
+ if a is None:
1328
+ q.joins.append(mark(f"joins({name})"))
1329
+ q.lower("low")
1330
+ q.notes.append(f"association `{name}` is not declared on {m.name}")
1331
+ return None, None
1332
+ kw = "LEFT OUTER JOIN" if left else "INNER JOIN"
1333
+ if a.through:
1334
+ th = self.models.assoc(m, a.through)
1335
+ if th is None:
1336
+ return None, None
1337
+ alias1, tm1 = self.join(q, m, table, a.through, left, key=(key or name) + "@through")
1338
+ if alias1 is None:
1339
+ return None, None
1340
+ src = a.source or name
1341
+ tm1a = self.models.assoc(tm1, src) or self.models.assoc(tm1, singularize(src)) or self.models.assoc(tm1, pluralize(src))
1342
+ if tm1a is None:
1343
+ return None, None
1344
+ return self.join(q, tm1, alias1, tm1a.name, left, key=key or name)
1345
+ if a.polymorphic:
1346
+ q.joins.append(mark(f"joins({name})"))
1347
+ q.lower("low")
1348
+ q.notes.append(f"polymorphic association `{name}`: its table is known at run time")
1349
+ return None, None
1350
+ target = self.models.assoc_model(m, a)
1351
+ if target is None:
1352
+ return None, None
1353
+ tt = self.models.table(target)
1354
+ alias = tt
1355
+ used = {q.table} | set(q.joined.values())
1356
+ if alias in used:
1357
+ alias = f"{name}_{tt}"
1358
+ on_as = f" AS {self.q(alias)}" if alias != tt else ""
1359
+ if a.kind == "belongs_to":
1360
+ fk = a.foreign_key or name + "_id"
1361
+ on = f"{self.col(alias, a.primary_key or 'id')} = {self.col(table, fk)}"
1362
+ elif a.kind == "habtm":
1363
+ q.joins.append(mark(f"joins({name})"))
1364
+ q.lower("low")
1365
+ return None, None
1366
+ else:
1367
+ if a.as_:
1368
+ fk = a.foreign_key or a.as_ + "_id"
1369
+ on = f"{self.col(alias, fk)} = {self.col(table, 'id')} AND {self.col(alias, a.as_ + '_type')} = '{self.models.base(m).name}'"
1370
+ else:
1371
+ fk = a.foreign_key or underscore(self.models.base(m).name.split("::")[-1]) + "_id"
1372
+ on = f"{self.col(alias, fk)} = {self.col(table, a.primary_key or 'id')}"
1373
+ typ = self.models.sti_type(target)
1374
+ if typ:
1375
+ on += f" AND {self.col(alias, self.models.base(target).inheritance_column)} = '{typ}'"
1376
+ q.joins.append(f"{kw} {self.q(tt)}{on_as} ON {on}")
1377
+ q.joined[key or name] = alias
1378
+ return alias, target
1379
+
1380
+ # -- order / columns
1381
+ def order(self, q: Q, pos, pairs, ctx: Ctx) -> None:
1382
+ for p in pos:
1383
+ name = symbol_name(p) if p.type in ("simple_symbol", "delimited_symbol") else None
1384
+ if name:
1385
+ q.order.append(f"{self.col(q.table, name)} ASC")
1386
+ continue
1387
+ s = self.string_of(p, ctx)
1388
+ if s is not None:
1389
+ q.order.append(norm(s))
1390
+ continue
1391
+ if p.type in ("call", "element_reference"):
1392
+ a = self.arel(p, q, ctx) # `arel_table[:id].desc`
1393
+ if a is not None:
1394
+ q.order.append(a)
1395
+ continue
1396
+ q.order.append(mark(txt(p)))
1397
+ q.lower("medium")
1398
+ for pr in pairs:
1399
+ k, v = pair_key(pr), pair_value(pr)
1400
+ if not k:
1401
+ continue
1402
+ d = (symbol_name(v) or "asc") if v is not None else "asc"
1403
+ if v is not None and v.type == "hash":
1404
+ for inner in v.named_children:
1405
+ if inner.type == "pair":
1406
+ ik, iv = pair_key(inner), pair_value(inner)
1407
+ tbl = q.joined.get(k, k)
1408
+ q.order.append(f"{self.col(tbl, ik)} {(symbol_name(iv) or 'asc').upper()}")
1409
+ continue
1410
+ if d.lower() not in ("asc", "desc"):
1411
+ q.order.append(f"{self.col(q.table, k)} {mark(txt(v))}")
1412
+ continue
1413
+ q.order.append(f"{self.col(q.table, k)} {d.upper()}")
1414
+
1415
+ def columns(self, q: Q, pos, ctx: Ctx) -> list[str]:
1416
+ out = []
1417
+ for p in pos:
1418
+ name = symbol_name(p) if p.type in ("simple_symbol", "delimited_symbol") else None
1419
+ if name:
1420
+ out.append(self.col(q.table, name))
1421
+ continue
1422
+ s = self.string_of(p, ctx)
1423
+ if s is not None:
1424
+ out.append(norm(s))
1425
+ continue
1426
+ if p.type == "array":
1427
+ out.extend(self.columns(q, list(p.named_children), ctx))
1428
+ continue
1429
+ if p.type in ("call", "element_reference"):
1430
+ a = self.arel(p, q, ctx)
1431
+ if a is not None:
1432
+ out.append(a)
1433
+ continue
1434
+ if p.type == "splat_argument" or p.type == "identifier":
1435
+ out.append(mark(txt(p)))
1436
+ q.lower("medium")
1437
+ continue
1438
+ out.append(mark(txt(p)))
1439
+ return out
1440
+
1441
+ # -- rendering
1442
+ def from_clause(self, q: Q) -> str:
1443
+ if q.from_:
1444
+ return "FROM " + q.from_
1445
+ return "FROM " + self.q(q.table)
1446
+
1447
+ def where_clause(self, q: Q) -> str:
1448
+ return (" WHERE " + " AND ".join(q.wheres)) if q.wheres else ""
1449
+
1450
+ def body(self, q: Q, order: bool = True, limit: bool = True) -> str:
1451
+ s = self.from_clause(q)
1452
+ if q.joins:
1453
+ s += " " + " ".join(q.joins)
1454
+ s += self.where_clause(q)
1455
+ if q.group:
1456
+ s += " GROUP BY " + ", ".join(q.group)
1457
+ if q.having:
1458
+ s += " HAVING " + " AND ".join(q.having)
1459
+ if order and q.order:
1460
+ s += " ORDER BY " + ", ".join(q.order)
1461
+ if limit and q.limit is not None:
1462
+ s += " LIMIT " + q.limit
1463
+ if limit and q.offset is not None:
1464
+ s += " OFFSET " + q.offset
1465
+ if q.lock:
1466
+ s += " FOR UPDATE"
1467
+ return s
1468
+
1469
+ def render_select(self, q: Q, cols: list[str] | None = None) -> str:
1470
+ cols = cols or q.select or [self.q(q.table) + ".*"]
1471
+ return "SELECT " + ("DISTINCT " if q.distinct else "") + ", ".join(cols) + " " + self.body(q)
1472
+
1473
+ def eager_joins(self, q: Q) -> None:
1474
+ """includes(...) whose table a condition names: ActiveRecord loads it with a LEFT OUTER JOIN."""
1475
+ if not q.eager:
1476
+ return
1477
+ keep = []
1478
+ for path in q.preloads:
1479
+ if path and path[0] in q.eager:
1480
+ m, t, key = q.model, q.table, ""
1481
+ for name in path:
1482
+ key = key + "." + name if key else name
1483
+ if key in q.joined:
1484
+ a = self.models.assoc(m, name)
1485
+ m = self.models.assoc_model(m, a) if a else m
1486
+ t = q.joined[key]
1487
+ continue
1488
+ alias, tm = self.join(q, m, t, name, left=True, key=key)
1489
+ if alias is None:
1490
+ break
1491
+ m, t = tm, alias
1492
+ else:
1493
+ keep.append(path)
1494
+ q.preloads = keep
1495
+
1496
+ def preload_statements(self, q: Q) -> list[tuple[str, str, str]]:
1497
+ """One statement per association level that includes/preload loads after the main one."""
1498
+ out = []
1499
+ seen = set()
1500
+ for path in q.preloads:
1501
+ m = q.model
1502
+ for depth, name in enumerate(path):
1503
+ if depth >= SETTINGS["ar_max_preload_depth"]:
1504
+ break
1505
+ a = self.models.assoc(m, name)
1506
+ if a is None or a.polymorphic or a.kind == "habtm":
1507
+ break
1508
+ key = ".".join(path[: depth + 1])
1509
+ if a.through:
1510
+ break
1511
+ target = self.models.assoc_model(m, a)
1512
+ if target is None:
1513
+ break
1514
+ tt = self.models.table(target)
1515
+ if a.kind == "belongs_to":
1516
+ cond = f"{self.col(tt, a.primary_key or 'id')} IN («{name}_ids»)"
1517
+ elif a.as_:
1518
+ cond = f"{self.col(tt, a.as_ + '_type')} = '{self.models.base(m).name}' AND {self.col(tt, a.foreign_key or a.as_ + '_id')} IN («owner_ids»)"
1519
+ else:
1520
+ fk = a.foreign_key or underscore(self.models.base(m).name.split("::")[-1]) + "_id"
1521
+ cond = f"{self.col(tt, fk)} IN («owner_ids»)"
1522
+ sub = self.start(target)
1523
+ sub.wheres.append(cond)
1524
+ for body in self.models.default_scopes(target):
1525
+ try:
1526
+ self.inline(sub, body, [], [], Ctx(self, "", target.name.split("::")))
1527
+ except Untranslatable:
1528
+ pass
1529
+ if key not in seen:
1530
+ seen.add(key)
1531
+ out.append((self.render_select(sub), "select", f"preload of `{key}` ({tt})"))
1532
+ m = target
1533
+ return out
1534
+
1535
+ def timestamps(self, table: str) -> list[str]:
1536
+ cols = self.models.columns(table)
1537
+ if cols is None:
1538
+ return []
1539
+ return [c for c in ("created_at", "updated_at") if c in cols]
1540
+
1541
+ def assignments(self, q: Q, model: Model, pairs, ctx: Ctx) -> list[tuple[str, str]]:
1542
+ out = []
1543
+ for p in pairs:
1544
+ if p.type == "hash_splat_argument":
1545
+ out.append((mark(txt(p)), mark(txt(p))))
1546
+ continue
1547
+ k = pair_key(p)
1548
+ v = pair_value(p)
1549
+ if k is None:
1550
+ continue
1551
+ a = self.models.assoc(model, k)
1552
+ if a is not None and a.kind == "belongs_to":
1553
+ fk = a.foreign_key or k + "_id"
1554
+ if a.polymorphic:
1555
+ out.append((k + "_type", mark(txt(v) + ".class")))
1556
+ out.append((fk, mark(txt(v) + ".id") if v is not None and v.type not in ("nil",) else "NULL"))
1557
+ continue
1558
+ out.append((k, self.value(v, ctx, self.models.enum_of(model, k))))
1559
+ return out
1560
+
1561
+ def hash_pairs(self, pos, pairs):
1562
+ if pairs:
1563
+ return pairs, False
1564
+ if pos and pos[0].type == "hash":
1565
+ return [x for x in pos[0].named_children if x.type in ("pair", "hash_splat_argument")], False
1566
+ return [], bool(pos)
1567
+
1568
+ def insert(self, q: Q, pos, pairs, ctx: Ctx) -> tuple[str, bool]:
1569
+ hp, unknown = self.hash_pairs(pos, pairs)
1570
+ cols = self.assignments(q, q.model, hp, ctx)
1571
+ typ = self.models.sti_type(q.model)
1572
+ if typ:
1573
+ cols.insert(0, (self.models.base(q.model).inheritance_column, f"'{typ}'"))
1574
+ # attributes the chain's hash conditions set (`Status.where(account: a).create(...)`)
1575
+ names = [c for c, _ in cols]
1576
+ ts = [c for c in self.timestamps(q.table) if c not in names]
1577
+ if unknown or not cols:
1578
+ q.lower("medium")
1579
+ q.notes.append("the attributes are set at run time")
1580
+ body = f"INSERT INTO {self.q(q.table)} ({mark('attribute_names')}) VALUES ({mark(txt(pos[0]) if pos else 'attributes')})"
1581
+ else:
1582
+ body = (f"INSERT INTO {self.q(q.table)} (" + ", ".join(self.q(c) for c, _ in cols) + "".join(", " + self.q(c) for c in ts)
1583
+ + ") VALUES (" + ", ".join(v for _, v in cols) + "".join(", «now»" for _ in ts) + ")")
1584
+ if self.engine in ("postgres", ""):
1585
+ body += f" RETURNING {self.q('id')}"
1586
+ return body, unknown
1587
+
1588
+ def insert_all(self, q: Q, meth: str, pos, pairs, ctx: Ctx) -> str:
1589
+ rows = pos[0] if pos else None
1590
+ cols: list[str] = []
1591
+ if rows is not None and rows.type == "array":
1592
+ first = next((x for x in rows.named_children if x.type == "hash"), None)
1593
+ if first is not None:
1594
+ cols = [c for c, _ in self.assignments(q, q.model, [x for x in first.named_children if x.type == "pair"], ctx)]
1595
+ opts = {pair_key(p): pair_value(p) for p in pairs}
1596
+ if cols:
1597
+ ts = [c for c in self.timestamps(q.table) if c not in cols]
1598
+ cols = cols + ts
1599
+ head = f"INSERT INTO {self.q(q.table)} (" + ", ".join(self.q(c) for c in cols) + ") VALUES (" + ", ".join("«row»" for _ in cols) + ")"
1600
+ else:
1601
+ q.lower("medium")
1602
+ q.notes.append("the inserted columns are known at run time")
1603
+ head = f"INSERT INTO {self.q(q.table)} ({mark('columns')}) VALUES ({mark(txt(rows) if rows is not None else 'rows')})"
1604
+ if meth.startswith("upsert"):
1605
+ ub = opts.get("unique_by")
1606
+ keys = [symbol_name(x) for x in (ub.named_children if ub is not None and ub.type == "array" else [ub])] if ub is not None else ["id"]
1607
+ keys = [k for k in keys if k] or ["id"]
1608
+ upd = [c for c in cols if c not in keys and c != "created_at"] if cols else []
1609
+ if upd:
1610
+ head += f" ON CONFLICT ({', '.join(self.q(k) for k in keys)}) DO UPDATE SET " + ", ".join(
1611
+ f"{self.q(c)} = excluded.{self.q(c)}" for c in upd)
1612
+ else:
1613
+ head += f" ON CONFLICT ({', '.join(self.q(k) for k in keys)}) DO NOTHING"
1614
+ elif not meth.endswith("!"):
1615
+ head += " ON CONFLICT DO NOTHING"
1616
+ if self.engine in ("postgres", ""):
1617
+ head += f" RETURNING {self.q('id')}"
1618
+ return head
1619
+
1620
+ def update(self, q: Q, sets: list[tuple[str, str]] | None, raw: str | None) -> str:
1621
+ if raw is not None:
1622
+ set_sql = raw
1623
+ else:
1624
+ set_sql = ", ".join(f"{self.q(c) if not c.startswith('«') else c} = {v}" for c, v in (sets or []))
1625
+ if q.joins or q.limit is not None or q.order and q.limit is not None:
1626
+ inner = self.render_select(q, [self.col(q.table, "id")])
1627
+ return f"UPDATE {self.q(q.table)} SET {set_sql} WHERE {self.col(q.table, 'id')} IN ({inner})"
1628
+ return f"UPDATE {self.q(q.table)} SET {set_sql}{self.where_clause(q)}"
1629
+
1630
+ def delete(self, q: Q) -> str:
1631
+ if q.joins or q.limit is not None:
1632
+ inner = self.render_select(q, [self.col(q.table, "id")])
1633
+ return f"DELETE FROM {self.q(q.table)} WHERE {self.col(q.table, 'id')} IN ({inner})"
1634
+ return f"DELETE FROM {self.q(q.table)}{self.where_clause(q)}"
1635
+
1636
+ def terminal(self, q: Q, meth: str, pos, pairs, block, ctx: Ctx, rest) -> list[tuple[str, str, str]]:
1637
+ """(sql, operation, note) for the statement(s) the terminal method sends."""
1638
+ t = q.table
1639
+ out: list[tuple[str, str, str]] = []
1640
+ idc = self.col(t, "id")
1641
+ if meth in ("find", "find!"):
1642
+ if len(pos) == 1 and pos[0].type != "array" and not (pos[0].type == "splat_argument"):
1643
+ q.wheres.append(f"{idc} = {self.value(pos[0], ctx)}")
1644
+ q.limit = "1"
1645
+ elif pos:
1646
+ vals = [self.value(p, ctx) for p in (pos[0].named_children if pos[0].type == "array" else pos)]
1647
+ q.wheres.append(f"{idc} IN ({', '.join(vals)})")
1648
+ elif block is not None:
1649
+ pass
1650
+ out.append((self.render_select(q), "select", ""))
1651
+ elif meth in ("find_by", "find_by!", "find_sole_by"):
1652
+ self.where(q, pos, pairs, ctx)
1653
+ q.limit = "1" if meth != "find_sole_by" else "2"
1654
+ out.append((self.render_select(q), "select", ""))
1655
+ elif meth in ("first", "first!", "last", "last!", "take", "take!", "sole", "second", "third"):
1656
+ n = self.value(pos[0], ctx) if pos else "1"
1657
+ if meth.startswith("first") and not q.order:
1658
+ q.order = [f"{idc} ASC"]
1659
+ if meth.startswith("last"):
1660
+ q.order = [self._reverse(o) for o in q.order] if q.order else [f"{idc} DESC"]
1661
+ q.limit = {"sole": "2"}.get(meth, n)
1662
+ if meth in ("second", "third"):
1663
+ q.order = q.order or [f"{idc} ASC"]
1664
+ q.offset = {"second": "1", "third": "2"}[meth]
1665
+ out.append((self.render_select(q), "select", ""))
1666
+ elif meth in ("count", "size", "sum", "maximum", "minimum", "average", "calculate"):
1667
+ fn = {"count": "COUNT", "size": "COUNT", "sum": "SUM", "maximum": "MAX", "minimum": "MIN", "average": "AVG"}.get(meth)
1668
+ args = pos
1669
+ if meth == "calculate" and pos:
1670
+ fn = {"count": "COUNT", "sum": "SUM", "maximum": "MAX", "minimum": "MIN", "average": "AVG"}.get(symbol_name(pos[0]) or "", "COUNT")
1671
+ args = pos[1:]
1672
+ if block is not None:
1673
+ out.append((self.render_select(q), "select", "the block counts in Ruby: every row is loaded"))
1674
+ else:
1675
+ if args:
1676
+ name = symbol_name(args[0]) if args[0].type in ("simple_symbol",) else None
1677
+ s = self.string_of(args[0], ctx) if name is None else None
1678
+ arg = self.col(t, name) if name else (norm(s) if s else mark(txt(args[0])))
1679
+ else:
1680
+ arg = "*" if not q.select or len(q.select) != 1 else q.select[0]
1681
+ if q.distinct and arg != "*":
1682
+ arg = "DISTINCT " + arg
1683
+ elif q.distinct and arg == "*":
1684
+ arg = "DISTINCT " + idc
1685
+ cols = [f"{fn}({arg})"]
1686
+ if q.group:
1687
+ cols = [f"{fn}({arg}) AS {fn.lower()}_{('id' if arg == '*' else 'value')}"] + q.group
1688
+ order_keep = bool(q.group)
1689
+ qq = q.copy()
1690
+ qq.distinct = False
1691
+ if not order_keep:
1692
+ qq.order = []
1693
+ if qq.limit is not None and not q.group:
1694
+ inner = self.render_select(q, [q.select[0]] if q.select else ["1 AS one"])
1695
+ out.append((f"SELECT {fn}({'*' if fn == 'COUNT' else 'subquery_for_count.*'}) FROM ({inner}) subquery_for_count", "select", ""))
1696
+ else:
1697
+ out.append(("SELECT " + ", ".join(cols) + " " + self.body(qq), "select", ""))
1698
+ elif meth in ("pluck", "pick", "ids"):
1699
+ cols = [idc] if meth == "ids" else self.columns(q, pos, ctx)
1700
+ if meth == "pick":
1701
+ q.limit = "1"
1702
+ out.append((self.render_select(q, cols or [idc]), "select", ""))
1703
+ elif meth in ("exists?", "any?", "many?", "none?", "empty?", "present?", "blank?", "one?"):
1704
+ if meth == "exists?" and pos:
1705
+ if pos[0].type == "hash" or pairs:
1706
+ self.where(q, pos, pairs, ctx)
1707
+ else:
1708
+ q.wheres.append(f"{idc} = {self.value(pos[0], ctx)}")
1709
+ elif meth == "exists?" and pairs:
1710
+ self.where(q, [], pairs, ctx)
1711
+ if block is not None:
1712
+ out.append((self.render_select(q), "select", "the block tests rows in Ruby: every row is loaded"))
1713
+ elif meth in ("many?", "one?"):
1714
+ qq = q.copy()
1715
+ qq.order = []
1716
+ out.append(("SELECT COUNT(*) " + self.body(qq), "select", ""))
1717
+ else:
1718
+ qq = q.copy()
1719
+ qq.order = []
1720
+ qq.limit = "1"
1721
+ qq.offset = None
1722
+ out.append(("SELECT 1 AS one " + self.body(qq), "select", ""))
1723
+ elif meth in ("find_each", "find_in_batches", "in_batches", "pluck_each"):
1724
+ opts = {pair_key(p): pair_value(p) for p in pairs}
1725
+ size = opts.get("batch_size") or opts.get("of")
1726
+ q.order = [f"{idc} ASC"] if not (opts.get("order") is not None and symbol_name(opts["order"]) == "desc") else [f"{idc} DESC"]
1727
+ q.limit = self.value(size, ctx) if size is not None else str(SETTINGS["ar_batch_size"])
1728
+ if opts.get("start") is not None:
1729
+ q.wheres.append(f"{idc} >= {self.value(opts['start'], ctx)}")
1730
+ if opts.get("finish") is not None:
1731
+ q.wheres.append(f"{idc} <= {self.value(opts['finish'], ctx)}")
1732
+ nxt = rest[0][1] if rest else ""
1733
+ if meth == "in_batches" and nxt in ("delete_all", "update_all", "destroy_all", "each_record", "pluck", "touch_all"):
1734
+ ids_q = q.copy()
1735
+ out.append((self.render_select(ids_q, [idc]), "select", "batch of ids (later batches add id > «last id»)"))
1736
+ bq = q.copy()
1737
+ bq.order, bq.limit = [], None
1738
+ bq.wheres = bq.wheres + [f"{idc} IN («batch_ids»)"]
1739
+ _, rm, rpos, rpairs, _ = rest[0]
1740
+ if rm == "delete_all":
1741
+ out.append((self.delete(bq), "delete", "per batch"))
1742
+ elif rm == "update_all":
1743
+ sets, raw = self.set_args(bq, rpos, rpairs, ctx)
1744
+ out.append((self.update(bq, sets, raw), "update", "per batch"))
1745
+ elif rm == "destroy_all":
1746
+ out.append((self.render_select(bq), "select", "per batch, then one DELETE per row"))
1747
+ out.append((f"DELETE FROM {self.q(t)} WHERE {idc} = «record.id»", "delete", "one per row"))
1748
+ return out
1749
+ out.append((self.render_select(q), "select", "first batch; later batches add id > «last id»"))
1750
+ elif meth in ("update_all", "touch_all"):
1751
+ if meth == "touch_all":
1752
+ sets, raw = [("updated_at", "«now»")], None
1753
+ else:
1754
+ sets, raw = self.set_args(q, pos, pairs, ctx)
1755
+ out.append((self.update(q, sets, raw), "update", ""))
1756
+ elif meth in ("delete_all", "delete_by"):
1757
+ if meth == "delete_by":
1758
+ self.where(q, pos, pairs, ctx)
1759
+ out.append((self.delete(q), "delete", ""))
1760
+ elif meth in ("destroy_all", "destroy_by"):
1761
+ if meth == "destroy_by":
1762
+ self.where(q, pos, pairs, ctx)
1763
+ out.append((self.render_select(q), "select", "destroy loads the rows, then deletes each (callbacks)"))
1764
+ out.append((f"DELETE FROM {self.q(t)} WHERE {idc} = «record.id»", "delete", "one per row"))
1765
+ elif meth in ("create", "create!", "insert", "insert!", "first_or_create", "first_or_create!"):
1766
+ # `where(a: x).create(...)` sets the conditions' attributes too
1767
+ extra = self.where_attrs(q)
1768
+ if meth.startswith("first_or"):
1769
+ qq = q.copy()
1770
+ qq.order, qq.limit = qq.order or [f"{idc} ASC"], "1"
1771
+ out.append((self.render_select(qq), "select", ""))
1772
+ body, _ = self.insert(q, pos, list(pairs) + [], ctx)
1773
+ if extra and not pos:
1774
+ body = self._add_insert_cols(body, extra)
1775
+ out.append((body, "insert", ""))
1776
+ elif meth in ("insert_all", "insert_all!", "upsert_all", "upsert"):
1777
+ if meth == "upsert":
1778
+ hp, _ = self.hash_pairs(pos, [])
1779
+ cols = [c for c, _ in self.assignments(q, q.model, hp, ctx)]
1780
+ opts = {pair_key(p): pair_value(p) for p in pairs}
1781
+ ub = opts.get("unique_by")
1782
+ keys = [symbol_name(ub)] if ub is not None and symbol_name(ub) else ["id"]
1783
+ if cols:
1784
+ cols = cols + [c for c in self.timestamps(t) if c not in cols]
1785
+ body = f"INSERT INTO {self.q(t)} (" + ", ".join(self.q(c) for c in cols) + ") VALUES (" + ", ".join("«row»" for _ in cols) + ")"
1786
+ upd = [c for c in cols if c not in keys and c != "created_at"]
1787
+ body += f" ON CONFLICT ({', '.join(self.q(k) for k in keys)}) " + (
1788
+ "DO UPDATE SET " + ", ".join(f"{self.q(c)} = excluded.{self.q(c)}" for c in upd) if upd else "DO NOTHING")
1789
+ else:
1790
+ body = self.insert_all(q, "upsert_all", pos, pairs, ctx)
1791
+ out.append((body, "upsert", ""))
1792
+ else:
1793
+ out.append((self.insert_all(q, meth, pos, pairs, ctx), "upsert" if meth.startswith("upsert") else "insert", ""))
1794
+ elif meth in ("find_or_create_by", "find_or_create_by!", "find_or_initialize_by", "create_or_find_by", "create_or_find_by!"):
1795
+ sel = q.copy()
1796
+ self.where(sel, pos, pairs, ctx)
1797
+ sel.limit = "1"
1798
+ if meth.startswith("create_or_find"):
1799
+ body, _ = self.insert(q, pos, pairs, ctx)
1800
+ out.append((body, "insert", "first; on a unique violation the row is read"))
1801
+ out.append((self.render_select(sel), "select", ""))
1802
+ else:
1803
+ out.append((self.render_select(sel), "select", ""))
1804
+ if not meth.endswith("initialize_by"):
1805
+ body, _ = self.insert(q, pos, pairs, ctx)
1806
+ out.append((body, "insert", "when no row matches"))
1807
+ elif meth in ("update", "update!") and q.model is not None and not q.wheres and len(pos) >= 1 and not pairs and pos[0].type != "hash":
1808
+ # Model.update(id, attrs)
1809
+ attrs = pos[1] if len(pos) > 1 else None
1810
+ hp = [x for x in attrs.named_children if x.type == "pair"] if attrs is not None and attrs.type == "hash" else []
1811
+ sets = self.assignments(q, q.model, hp, ctx) + [(c, "«now»") for c in self.timestamps(t) if c == "updated_at"]
1812
+ sel = q.copy()
1813
+ sel.wheres.append(f"{idc} = {self.value(pos[0], ctx)}")
1814
+ sel.limit = "1"
1815
+ out.append((self.render_select(sel), "select", ""))
1816
+ if sets:
1817
+ out.append((f"UPDATE {self.q(t)} SET " + ", ".join(f"{self.q(c)} = {v}" for c, v in sets) + f" WHERE {idc} = {self.value(pos[0], ctx)}", "update", ""))
1818
+ elif meth in ("update", "update!") and (pairs or (pos and pos[0].type == "hash")):
1819
+ # relation.update(attrs): loads the rows, updates each (callbacks)
1820
+ hp, _ = self.hash_pairs(pos, pairs)
1821
+ sets = self.assignments(q, q.model, hp, ctx) + [(c, "«now»") for c in self.timestamps(t) if c == "updated_at"]
1822
+ out.append((self.render_select(q), "select", "update on a relation loads each row"))
1823
+ out.append((f"UPDATE {self.q(t)} SET " + ", ".join(f"{self.q(c)} = {v}" for c, v in sets) + f" WHERE {idc} = «record.id»", "update", "one per row"))
1824
+ elif meth in ("delete", "destroy", "destroy!") and pos:
1825
+ vals = [self.value(p, ctx) for p in pos]
1826
+ cond = f"{idc} = {vals[0]}" if len(vals) == 1 and not vals[0].endswith("s»") else f"{idc} IN ({', '.join(vals)})"
1827
+ if meth == "delete":
1828
+ out.append((f"DELETE FROM {self.q(t)} WHERE {cond}", "delete", ""))
1829
+ else:
1830
+ sel = q.copy()
1831
+ sel.wheres.append(cond)
1832
+ out.append((self.render_select(sel), "select", ""))
1833
+ out.append((f"DELETE FROM {self.q(t)} WHERE {idc} = «record.id»", "delete", "one per row"))
1834
+ elif meth in ("increment_counter", "decrement_counter", "update_counters") and pos:
1835
+ if meth == "update_counters":
1836
+ sets = [(pair_key(p), f"COALESCE({self.q(pair_key(p))}, 0) + {self.value(pair_value(p), ctx)}")
1837
+ for p in pairs if pair_key(p) and pair_key(p) not in ("touch",)]
1838
+ idv = self.value(pos[0], ctx)
1839
+ else:
1840
+ col = symbol_name(pos[0]) or mark(txt(pos[0]))
1841
+ sign = "+" if meth.startswith("inc") else "-"
1842
+ sets = [(col, f"COALESCE({self.q(col)}, 0) {sign} 1")]
1843
+ idv = self.value(pos[1], ctx) if len(pos) > 1 else "«id»"
1844
+ if sets:
1845
+ out.append((f"UPDATE {self.q(t)} SET " + ", ".join(f"{self.q(c)} = {v}" for c, v in sets) + f" WHERE {idc} = {idv}", "update", ""))
1846
+ elif meth in ("new", "build"):
1847
+ return []
1848
+ elif meth in ("find_by_sql", "count_by_sql"):
1849
+ s = self.fragment(pos, pairs, ctx, q) if pos else None
1850
+ if s is None:
1851
+ raise Untranslatable("SQL handed in")
1852
+ out.append((s, "raw", ""))
1853
+ else:
1854
+ # enumerable over the relation: the relation is loaded
1855
+ if block is not None and meth in ("select", "find", "detect"):
1856
+ pass
1857
+ out.append((self.render_select(q), "select", ""))
1858
+ return out
1859
+
1860
+ def _add_insert_cols(self, body: str, extra: list[tuple[str, str]]) -> str:
1861
+ m = re.match(r"INSERT INTO (\S+) \((.*?)\) VALUES \((.*?)\)(.*)$", body)
1862
+ if not m or "«attribute_names»" in body:
1863
+ return body
1864
+ cols = m.group(2) + "".join(", " + self.q(c) for c, _ in extra)
1865
+ vals = m.group(3) + "".join(", " + v for _, v in extra)
1866
+ return f"INSERT INTO {m.group(1)} ({cols}) VALUES ({vals}){m.group(4)}"
1867
+
1868
+ def where_attrs(self, q: Q) -> list[tuple[str, str]]:
1869
+ out = []
1870
+ for w in q.wheres:
1871
+ m = re.fullmatch(r'"[^"]+"\."(\w+)" = (.+)', w)
1872
+ if m and " AND " not in m.group(2):
1873
+ out.append((m.group(1), m.group(2)))
1874
+ return out
1875
+
1876
+ def set_args(self, q: Q, pos, pairs, ctx: Ctx):
1877
+ if pairs or (pos and pos[0].type == "hash"):
1878
+ hp, _ = self.hash_pairs(pos, pairs)
1879
+ return self.assignments(q, q.model, hp, ctx), None
1880
+ if pos:
1881
+ f = self.fragment(pos, pairs, ctx, q)
1882
+ if f is not None:
1883
+ return None, f
1884
+ q.lower("medium")
1885
+ q.notes.append("the assignments are built at run time")
1886
+ return None, f"{mark(txt(pos[0]))}"
1887
+ return [], None
1888
+
1889
+ @staticmethod
1890
+ def _reverse(o: str) -> str:
1891
+ if o.endswith(" ASC"):
1892
+ return o[:-4] + " DESC"
1893
+ if o.endswith(" DESC"):
1894
+ return o[:-5] + " ASC"
1895
+ return o + " DESC"
1896
+
1897
+
1898
+ def make_site(rel: str, node, sink: str, symbol: str, sql: str, *, table: str, operation: str, confidence: str,
1899
+ notes: list[str], in_loop: bool, engine: str, is_test: bool, mechanism: str) -> RawSite:
1900
+ orm = {"library": LIBRARY, "model_or_table": table, "operation": operation, "confidence": confidence,
1901
+ "mechanism": mechanism}
1902
+ if notes:
1903
+ orm["notes"] = "; ".join(dict.fromkeys(n for n in notes if n))
1904
+ return RawSite(file=rel, line=node.start_point[0] + 1, end_line=node.end_point[0] + 1, language="ruby", kind="call",
1905
+ sink=trim(re.sub(r"\s+", "", sink), 80), symbol=symbol, sql=sql, resolution="orm",
1906
+ expr=trim(norm(txt(node))), in_loop=in_loop, engine_hint=engine, is_test=is_test, known_sink=True, orm=orm)