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,2138 @@
1
+ """Ecto (Elixir): `Repo.<function>` calls translated to SQL by rule.
2
+
3
+ The repository's own modules are indexed first: aliases, functions, module attributes, `schema "table" do ... end`
4
+ blocks (fields, belongs_to / has_many / has_one / many_to_many, timestamps, embeds) and `use Ecto.Repo, adapter: ...`
5
+ (which engine a repo talks to). Migrations (`create table(:t) do add :c, :type end`, `alter table`) give the tables
6
+ too, so the sandbox can build them.
7
+
8
+ A call such as
9
+
10
+ from(s in Site, join: m in assoc(s, :memberships), where: m.user_id == ^user.id, order_by: [desc: s.inserted_at])
11
+ |> limit(10)
12
+ |> Repo.all()
13
+
14
+ becomes `SELECT s0."id", ... FROM "sites" AS s0 INNER JOIN "site_memberships" AS s1 ON s1."site_id" = s0."id"
15
+ WHERE (s1."user_id" = «user.id») ORDER BY s0."inserted_at" DESC LIMIT 10`. The query may be built in a variable of
16
+ the same function, in a function of the same or another module (followed with its arguments bound), and through
17
+ pipes of the Ecto.Query macros. `^pinned` values are «values»; anything decided at run time in a structural place
18
+ (a source held in a variable that is not a query here, `order_by: ^order`, a function this reader cannot follow
19
+ that takes and returns the query) is a «run-time part» in that place, so the statement says what it does not know.
20
+ `if` / `case` choices of a query give one statement per branch (capped by `[discover] max_variants`).
21
+
22
+ Raw SQL (`Repo.query(sql, params)`) is the string itself. A call whose table cannot be told gets no SQL: it is
23
+ reported as a site with no statement and counted with the reason.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import re
29
+ from pathlib import Path
30
+
31
+ from tree_sitter import Node
32
+
33
+ from .base import RawSite, trim
34
+ from .orm_stats import Stats
35
+ from .schema import Table
36
+
37
+ LIB = "ecto"
38
+ STATS = Stats()
39
+ TABLES: list = []
40
+
41
+ REPO_FUNCS = {"all", "one", "one!", "get", "get!", "get_by", "get_by!", "insert", "insert!", "insert_all", "update", "update!",
42
+ "update_all", "delete", "delete!", "delete_all", "aggregate", "exists?", "stream", "preload", "query", "query!",
43
+ "insert_or_update", "insert_or_update!", "reload", "reload!"}
44
+ QUERY_MACROS = {"where", "or_where", "select", "select_merge", "order_by", "limit", "offset", "group_by", "having",
45
+ "or_having", "distinct", "join", "preload", "lock", "update", "exclude", "first", "last", "windows",
46
+ "hints", "prefix", "intersect", "union", "union_all", "except", "with_cte", "reverse_order", "combinations"}
47
+ JOIN_KW = {"join": "INNER JOIN", "inner_join": "INNER JOIN", "left_join": "LEFT OUTER JOIN", "right_join": "RIGHT OUTER JOIN",
48
+ "full_join": "FULL OUTER JOIN", "cross_join": "CROSS JOIN", "inner_lateral_join": "INNER JOIN LATERAL",
49
+ "left_lateral_join": "LEFT OUTER JOIN LATERAL", "array_join": "ARRAY JOIN", "left_array_join": "LEFT ARRAY JOIN"}
50
+ JOIN_QUAL = {"inner": "INNER JOIN", "left": "LEFT OUTER JOIN", "right": "RIGHT OUTER JOIN", "full": "FULL OUTER JOIN",
51
+ "cross": "CROSS JOIN", "inner_lateral": "INNER JOIN LATERAL", "left_lateral": "LEFT OUTER JOIN LATERAL",
52
+ "array": "ARRAY JOIN", "left_array": "LEFT ARRAY JOIN"}
53
+ BINOP = {"==": "=", "!=": "<>", ">": ">", "<": "<", ">=": ">=", "<=": "<=", "and": "AND", "or": "OR", "&&": "AND",
54
+ "||": "OR", "+": "+", "-": "-", "*": "*", "/": "/"}
55
+ AGG = {"count": "count", "sum": "sum", "avg": "avg", "min": "min", "max": "max", "coalesce": "coalesce",
56
+ "lower": "lower", "upper": "upper", "length": "length"}
57
+ ECTO_TYPES = {"string": "varchar(255)", "text": "text", "integer": "integer", "bigint": "bigint", "id": "bigint",
58
+ "serial": "serial", "bigserial": "bigserial", "boolean": "boolean", "float": "double precision",
59
+ "decimal": "numeric", "binary": "bytea", "binary_id": "uuid", "uuid": "uuid", "date": "date",
60
+ "time": "time", "naive_datetime": "timestamp", "naive_datetime_usec": "timestamp",
61
+ "utc_datetime": "timestamp", "utc_datetime_usec": "timestamp", "timestamptz": "timestamptz",
62
+ "map": "jsonb", "jsonb": "jsonb", "json": "json", "citext": "citext", "inet": "inet", "smallint": "smallint"}
63
+ LOOP_FUNCS = re.compile(r"^(?:Enum|Stream|Task|Flow)\.(?:each|map|flat_map|reduce|reduce_while|filter|map_reduce|"
64
+ r"each_while|async_stream|chunk_every|with_index|zip|into|scan|transform)$")
65
+
66
+ DEFAULT_MAX_VARIANTS = 8
67
+ DEFAULT_FOLLOW_DEPTH = 6 # functions followed from one call to find its query
68
+ SETTINGS = {"max_variants": DEFAULT_MAX_VARIANTS, "ecto_follow_depth": DEFAULT_FOLLOW_DEPTH}
69
+
70
+
71
+ def apply_settings(settings: dict | None) -> None:
72
+ settings = settings or {}
73
+ SETTINGS["max_variants"] = int(settings.get("max_variants", DEFAULT_MAX_VARIANTS))
74
+ SETTINGS["ecto_follow_depth"] = int(settings.get("ecto_follow_depth", DEFAULT_FOLLOW_DEPTH))
75
+
76
+
77
+ # ---------------------------------------------------------------------------------------------- syntax helpers
78
+ def t(n: Node | None) -> str:
79
+ return n.text.decode("utf-8", "replace") if n is not None else ""
80
+
81
+
82
+ def kids(n: Node | None) -> list[Node]:
83
+ return [c for c in n.named_children if c.type != "comment"] if n is not None else []
84
+
85
+
86
+ def strip(n: Node | None) -> Node | None:
87
+ while n is not None and n.type in ("block",) and len(kids(n)) == 1:
88
+ n = kids(n)[0]
89
+ return n
90
+
91
+
92
+ def op(n: Node) -> str:
93
+ o = n.child_by_field_name("operator")
94
+ return t(o) if o is not None else ""
95
+
96
+
97
+ def call_target(n: Node) -> tuple[str, str]:
98
+ """('Mod.Path' or '' for a local call, function name)."""
99
+ tg = n.child_by_field_name("target")
100
+ if tg is None:
101
+ return "", ""
102
+ if tg.type == "identifier":
103
+ return "", t(tg)
104
+ if tg.type == "dot":
105
+ left, right = tg.child_by_field_name("left"), tg.child_by_field_name("right")
106
+ return t(left), t(right)
107
+ return "", ""
108
+
109
+
110
+ def call_args(n: Node) -> tuple[list[Node], dict[str, Node], Node | None]:
111
+ """(positional arguments, keyword arguments in a trailing keyword list, do block)."""
112
+ pos: list[Node] = []
113
+ kw: dict[str, Node] = {}
114
+ do = None
115
+ for c in n.named_children:
116
+ if c.type == "arguments":
117
+ for a in kids(c):
118
+ if a.type == "keywords":
119
+ for k, v in pairs(a):
120
+ kw[k] = v
121
+ else:
122
+ pos.append(a)
123
+ elif c.type == "do_block":
124
+ do = c
125
+ return pos, kw, do
126
+
127
+
128
+ def kw_list(n: Node) -> list[tuple[str, Node]]:
129
+ """The trailing keyword arguments of a call in source order, repeated keys kept (`where:` twice in a `from`)."""
130
+ out: list[tuple[str, Node]] = []
131
+ for c in n.named_children:
132
+ if c.type == "arguments":
133
+ for a in kids(c):
134
+ if a.type == "keywords":
135
+ out.extend(pairs(a))
136
+ return out
137
+
138
+
139
+ def pairs(n: Node | None) -> list[tuple[str, Node]]:
140
+ """`[a: x, b: y]` / `a: x, b: y` as (key, value) in order."""
141
+ out: list[tuple[str, Node]] = []
142
+ if n is None:
143
+ return out
144
+ if n.type == "list":
145
+ for c in kids(n):
146
+ if c.type == "keywords":
147
+ out.extend(pairs(c))
148
+ elif c.type == "tuple" and len(kids(c)) == 2 and kids(c)[0].type == "atom":
149
+ out.append((t(kids(c)[0])[1:], kids(c)[1]))
150
+ return out
151
+ if n.type == "keywords":
152
+ for p in kids(n):
153
+ if p.type == "pair":
154
+ k, v = p.child_by_field_name("key"), p.child_by_field_name("value")
155
+ if k is not None and v is not None:
156
+ out.append((t(k).strip().rstrip(":").strip().strip('"'), v))
157
+ return out
158
+
159
+
160
+ def string_text(n: Node | None) -> tuple[str, bool] | None:
161
+ """(text, has_interpolation) of a string, heredoc or ~s/~S sigil; interpolations as «expr»."""
162
+ if n is None:
163
+ return None
164
+ if n.type == "sigil":
165
+ name = n.child_by_field_name("sigil_name") if hasattr(n, "child_by_field_name") else None
166
+ nm = t(name) if name is not None else ""
167
+ if nm not in ("s", "S", ""):
168
+ return None
169
+ elif n.type not in ("string", "charlist"):
170
+ return None
171
+ out, interp = [], False
172
+ for c in n.named_children:
173
+ if c.type == "quoted_content":
174
+ out.append(t(c))
175
+ elif c.type == "escape_sequence":
176
+ e = t(c)
177
+ out.append({"\\n": "\n", "\\t": "\t", '\\"': '"', "\\\\": "\\"}.get(e, e[1:]))
178
+ elif c.type == "interpolation":
179
+ interp = True
180
+ out.append("«" + trim(t(c)[2:-1], 80).replace("»", ">") + "»")
181
+ return "".join(out), interp
182
+
183
+
184
+ def mark(text: str) -> str:
185
+ return "«" + trim(" ".join(text.split()), 80).replace("»", ">").replace("«", "<") + "»"
186
+
187
+
188
+ def q_ident(name: str) -> str:
189
+ if name.startswith("«"):
190
+ return name
191
+ return '"' + name.replace('"', '""') + '"'
192
+
193
+
194
+ def q_table(name: str) -> str:
195
+ return ".".join(q_ident(p) for p in name.split(".")) if not name.startswith("«") else name
196
+
197
+
198
+ def underscore(name: str) -> str:
199
+ last = name.split(".")[-1]
200
+ return re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "_", last).lower()
201
+
202
+
203
+ # ---------------------------------------------------------------------------------------------- module index
204
+ class Assoc:
205
+ __slots__ = ("kind", "name", "target", "fk", "through", "join_through", "join_keys", "references")
206
+
207
+ def __init__(self, kind, name, target, fk="", through=None, join_through="", join_keys=None, references="id"):
208
+ self.kind, self.name, self.target, self.fk = kind, name, target, fk
209
+ self.through, self.join_through, self.join_keys, self.references = through, join_through, join_keys, references
210
+
211
+
212
+ class Mod:
213
+ def __init__(self, name: str, f, node: Node):
214
+ self.name, self.f, self.node = name, f, node
215
+ self.aliases: dict[str, str] = {}
216
+ self.attrs: dict[str, Node] = {}
217
+ self.fns: dict[str, list[Node]] = {}
218
+ self.table: str | None = None
219
+ self.prefix = ""
220
+ self.fields: dict[str, tuple[str, str]] = {} # field -> (column, ecto type text)
221
+ self.pk: list[str] = ["id"]
222
+ self.assocs: dict[str, Assoc] = {}
223
+ self.casts: dict[str, list[str]] = {} # function name -> fields its cast() takes
224
+ self.clickhouse_schema = False
225
+ self.repo_engine: str | None = None
226
+ self.schema_line = 0
227
+
228
+ def columns(self) -> list[str]:
229
+ return [c for c, _ in self.fields.values()]
230
+
231
+
232
+ class Index:
233
+ def __init__(self):
234
+ self.mods: dict[str, Mod] = {}
235
+ self.by_last: dict[str, list[Mod]] = {}
236
+ self.assoc_by_name: dict[str, list[tuple[Mod, Assoc]]] = {}
237
+
238
+ # -- building
239
+ def add_file(self, f) -> None:
240
+ for n in kids(f.root):
241
+ self._visit(f, n, None)
242
+
243
+ def _visit(self, f, n: Node, parent: Mod | None) -> None:
244
+ if n.type != "call":
245
+ return
246
+ mod_name, fn = call_target(n)
247
+ if mod_name or fn != "defmodule":
248
+ return
249
+ pos, _kw, do = call_args(n)
250
+ if not pos or do is None:
251
+ return
252
+ name = t(pos[0])
253
+ if parent is not None:
254
+ name = name.replace("__MODULE__", parent.name)
255
+ if not name.startswith(parent.name + "."):
256
+ short = name.split(".")[0]
257
+ full = parent.name + "." + name
258
+ parent.aliases.setdefault(short, parent.name + "." + short)
259
+ name = full
260
+ m = Mod(name, f, do)
261
+ if parent is not None:
262
+ m.aliases.update(parent.aliases)
263
+ self.mods[name] = m
264
+ self.by_last.setdefault(name.split(".")[-1], []).append(m)
265
+ for c in kids(do):
266
+ if c.type == "call" and call_target(c) == ("", "defmodule"):
267
+ self._visit(f, c, m)
268
+ self._read_body(m, do)
269
+
270
+ def _read_body(self, m: Mod, do: Node) -> None:
271
+ stack = list(reversed(kids(do)))
272
+ while stack:
273
+ c = stack.pop()
274
+ if c.type == "call":
275
+ mn, fn = call_target(c)
276
+ if mn == "" and fn == "defmodule":
277
+ continue
278
+ if mn == "" and fn == "alias":
279
+ self._alias(m, c)
280
+ continue
281
+ if mn == "" and fn in ("def", "defp"):
282
+ self._def(m, c)
283
+ continue
284
+ if mn == "" and fn == "use":
285
+ pos, kw, _ = call_args(c)
286
+ if pos and t(pos[0]) == "Ecto.Repo":
287
+ m.repo_engine = engine_of_adapter(t(kw.get("adapter")))
288
+ continue
289
+ if mn == "" and fn == "schema":
290
+ self._schema(m, c)
291
+ continue
292
+ if mn == "" and fn in ("if", "unless", "quote", "do", "for"):
293
+ _p, _k, d = call_args(c)
294
+ if d is not None:
295
+ stack.extend(reversed(kids(d)))
296
+ continue
297
+ elif c.type == "unary_operator" and op(c) == "@":
298
+ inner = c.child_by_field_name("operand")
299
+ if inner is not None and inner.type == "call":
300
+ _, an = call_target(inner)
301
+ pos, _k, _d = call_args(inner)
302
+ if pos:
303
+ m.attrs[an] = pos[0]
304
+
305
+ def _alias(self, m: Mod, c: Node) -> None:
306
+ pos, kw, _ = call_args(c)
307
+ if not pos:
308
+ return
309
+ a = pos[0]
310
+ if a.type == "dot" and a.child_by_field_name("right") is not None and a.child_by_field_name("right").type == "tuple":
311
+ base = t(a.child_by_field_name("left")).replace("__MODULE__", m.name)
312
+ for x in kids(a.child_by_field_name("right")):
313
+ full = base + "." + t(x)
314
+ m.aliases[t(x).split(".")[-1]] = full
315
+ return
316
+ full = t(a).replace("__MODULE__", m.name)
317
+ if "as" in kw:
318
+ m.aliases[t(kw["as"])] = full
319
+ else:
320
+ m.aliases[full.split(".")[-1]] = full
321
+
322
+ def _def(self, m: Mod, c: Node) -> None:
323
+ pos, _kw, _ = call_args(c)
324
+ if not pos:
325
+ return
326
+ head = pos[0]
327
+ if head.type == "binary_operator" and op(head) == "when":
328
+ head = head.child_by_field_name("left")
329
+ if head is None:
330
+ return
331
+ name = t(head) if head.type == "identifier" else call_target(head)[1] if head.type == "call" else ""
332
+ if name:
333
+ m.fns.setdefault(name, []).append(c)
334
+ # cast(attrs, [...]) inside a changeset function
335
+ for n in walk(c):
336
+ if n.type == "call" and call_target(n)[1] == "cast":
337
+ p, _k, _d = call_args(n)
338
+ for a in p:
339
+ fields = self.atom_list(m, a)
340
+ if fields:
341
+ m.casts.setdefault(name, [])
342
+ m.casts[name].extend(x for x in fields if x not in m.casts[name])
343
+ break
344
+
345
+ def atom_list(self, m: Mod, a: Node | None, depth: int = 0) -> list[str] | None:
346
+ if a is None or depth > 3:
347
+ return None
348
+ if a.type == "list":
349
+ items = kids(a)
350
+ if items and all(i.type == "atom" for i in items):
351
+ return [t(i)[1:] for i in items]
352
+ return None
353
+ if a.type == "unary_operator" and op(a) == "@":
354
+ inner = a.child_by_field_name("operand")
355
+ name = call_target(inner)[1] if inner is not None and inner.type == "call" else t(inner)
356
+ return self.atom_list(m, m.attrs.get(name), depth + 1)
357
+ if a.type == "binary_operator" and op(a) == "++":
358
+ l1 = self.atom_list(m, a.child_by_field_name("left"), depth + 1)
359
+ l2 = self.atom_list(m, a.child_by_field_name("right"), depth + 1)
360
+ if l1 is not None and l2 is not None:
361
+ return l1 + l2
362
+ if a.type == "sigil":
363
+ sn = a.child_by_field_name("sigil_name")
364
+ if sn is not None and t(sn) == "w":
365
+ body = "".join(t(x) for x in a.named_children if x.type == "quoted_content")
366
+ return body.split()
367
+ return None
368
+
369
+ def _schema(self, m: Mod, c: Node) -> None:
370
+ pos, _kw, do = call_args(c)
371
+ if not pos or do is None:
372
+ return
373
+ st = string_text(pos[0])
374
+ if st is None or st[1]:
375
+ return
376
+ m.table = st[0]
377
+ m.schema_line = c.start_point[0] + 1
378
+ pkattr = m.attrs.get("primary_key")
379
+ if pkattr is not None:
380
+ if t(pkattr) == "false":
381
+ m.pk = []
382
+ elif pkattr.type == "tuple" and kids(pkattr) and kids(pkattr)[0].type == "atom":
383
+ pkname = t(kids(pkattr)[0])[1:]
384
+ m.pk = [pkname]
385
+ m.fields[pkname] = (pkname, t(kids(pkattr)[1]) if len(kids(pkattr)) > 1 else ":id")
386
+ elif "id" not in m.fields:
387
+ m.fields["id"] = ("id", ":id")
388
+ pre = m.attrs.get("schema_prefix")
389
+ if pre is not None and string_text(pre):
390
+ m.prefix = string_text(pre)[0]
391
+ for s in kids(do):
392
+ if s.type == "identifier" and t(s) == "timestamps":
393
+ s_fields = [("inserted_at", ":naive_datetime"), ("updated_at", ":naive_datetime")]
394
+ for f_, ty in s_fields:
395
+ m.fields[f_] = (f_, ty)
396
+ continue
397
+ if s.type != "call":
398
+ continue
399
+ mn, fn = call_target(s)
400
+ if mn:
401
+ continue
402
+ p, kw, _d = call_args(s)
403
+ if fn == "timestamps":
404
+ ins = t(kw.get("inserted_at"))[1:] if "inserted_at" in kw and t(kw["inserted_at"]) != "false" else ("" if "inserted_at" in kw else "inserted_at")
405
+ upd = t(kw.get("updated_at"))[1:] if "updated_at" in kw and t(kw["updated_at"]) != "false" else ("" if "updated_at" in kw else "updated_at")
406
+ ty = t(kw.get("type")) or ":naive_datetime"
407
+ for x in (ins, upd):
408
+ if x:
409
+ m.fields[x] = (x, ty)
410
+ continue
411
+ if not p or p[0].type != "atom":
412
+ continue
413
+ name = t(p[0])[1:]
414
+ if fn == "field":
415
+ if t(kw.get("virtual")) == "true":
416
+ continue
417
+ ty = t(p[1]) if len(p) > 1 else ":string"
418
+ if ty == "Ch" or ty.startswith("Ch,"):
419
+ m.clickhouse_schema = True
420
+ col = t(kw["source"])[1:] if "source" in kw else name
421
+ m.fields[name] = (col, ty)
422
+ elif fn in ("embeds_one", "embeds_many"):
423
+ m.fields[name] = (name, ":map")
424
+ elif fn == "belongs_to" and len(p) > 1:
425
+ fk = t(kw["foreign_key"])[1:] if "foreign_key" in kw else name + "_id"
426
+ if t(kw.get("define_field")) != "false":
427
+ m.fields[fk] = (fk, t(kw.get("type")) or ":id")
428
+ refs = t(kw["references"])[1:] if "references" in kw else "id"
429
+ m.assocs[name] = Assoc("belongs_to", name, self.resolve(m, t(p[1])), fk, references=refs)
430
+ elif fn in ("has_many", "has_one"):
431
+ if "through" in kw:
432
+ thr = [t(x)[1:] for x in kids(kw["through"]) if x.type == "atom"]
433
+ m.assocs[name] = Assoc(fn, name, "", through=thr)
434
+ elif len(p) > 1:
435
+ fk = t(kw["foreign_key"])[1:] if "foreign_key" in kw else underscore(m.name) + "_id"
436
+ m.assocs[name] = Assoc(fn, name, self.resolve(m, t(p[1])), fk)
437
+ elif fn == "many_to_many" and len(p) > 1:
438
+ jt = kw.get("join_through")
439
+ jts = string_text(jt) if jt is not None else None
440
+ jtable = jts[0] if jts and not jts[1] else ("@mod:" + self.resolve(m, t(jt)) if jt is not None else "")
441
+ keys = pairs(kw["join_keys"]) if "join_keys" in kw else None
442
+ m.assocs[name] = Assoc("many_to_many", name, self.resolve(m, t(p[1])), join_through=jtable,
443
+ join_keys=[(k, t(v)[1:]) for k, v in keys] if keys else None)
444
+
445
+ def finish(self) -> None:
446
+ for m in self.mods.values():
447
+ for a in m.assocs.values():
448
+ self.assoc_by_name.setdefault(a.name, []).append((m, a))
449
+
450
+ # -- lookup
451
+ def resolve(self, m: Mod | None, name: str) -> str:
452
+ name = name.strip()
453
+ if m is not None:
454
+ name = name.replace("__MODULE__", m.name)
455
+ first, _, rest = name.partition(".")
456
+ if first in m.aliases:
457
+ return m.aliases[first] + ("." + rest if rest else "")
458
+ parts = m.name.split(".")
459
+ for i in range(len(parts), 0, -1):
460
+ cand = ".".join(parts[:i]) + "." + name
461
+ if cand in self.mods:
462
+ return cand
463
+ if name in self.mods:
464
+ return name
465
+ cands = self.by_last.get(name.split(".")[-1], [])
466
+ if len(cands) == 1 and cands[0].name.endswith(name):
467
+ return cands[0].name
468
+ return name
469
+
470
+ def mod(self, m: Mod | None, name: str) -> Mod | None:
471
+ return self.mods.get(self.resolve(m, name))
472
+
473
+ def table_of(self, mod: Mod) -> str:
474
+ return (mod.prefix + "." if mod.prefix else "") + (mod.table or "")
475
+
476
+
477
+ def walk(n: Node):
478
+ stack = [n]
479
+ while stack:
480
+ x = stack.pop()
481
+ yield x
482
+ stack.extend(reversed(x.children))
483
+
484
+
485
+ def engine_of_adapter(text: str) -> str:
486
+ low = text.lower()
487
+ if "postgres" in low:
488
+ return "postgres"
489
+ if "clickhouse" in low or re.search(r"\bch\b", low):
490
+ return "clickhouse"
491
+ if "myxql" in low or "mysql" in low:
492
+ return "mysql"
493
+ if "sqlite" in low:
494
+ return "sqlite"
495
+ if "tds" in low:
496
+ return "mssql"
497
+ return ""
498
+
499
+
500
+ # ---------------------------------------------------------------------------------------------- queries
501
+ class Unknown(Exception):
502
+ """The call's table cannot be told: no SQL."""
503
+
504
+
505
+ class Q:
506
+ def __init__(self):
507
+ self.srcs: list[dict] = [] # {alias, sql, mod}
508
+ self.joins: list[str] = []
509
+ self.named: dict[str, int] = {}
510
+ self.where: list[tuple[str, str]] = []
511
+ self.select: str | None = None
512
+ self.select_merge: list[str] = []
513
+ self.distinct = ""
514
+ self.order: list[str] = []
515
+ self.group: list[str] = []
516
+ self.having: list[str] = []
517
+ self.limit: str | None = None
518
+ self.offset: str | None = None
519
+ self.lock = ""
520
+ self.update: list[str] = []
521
+ self.preload: list[str] = []
522
+ self.notes: list[str] = []
523
+ self.runtime = 0
524
+ self.followed: list[str] = []
525
+
526
+ def copy(self) -> "Q":
527
+ q = Q()
528
+ for k, v in self.__dict__.items():
529
+ setattr(q, k, list(v) if isinstance(v, list) else dict(v) if isinstance(v, dict) else v)
530
+ q.srcs = [dict(s) for s in self.srcs]
531
+ return q
532
+
533
+ def add_src(self, sql: str, mod: Mod | None) -> int:
534
+ i = len(self.srcs)
535
+ self.srcs.append({"alias": f"s{i}", "sql": sql, "mod": mod})
536
+ return i
537
+
538
+ @property
539
+ def root_mod(self) -> Mod | None:
540
+ return self.srcs[0]["mod"] if self.srcs else None
541
+
542
+
543
+ class Scope:
544
+ __slots__ = ("f", "m", "fn", "env", "depth", "stack")
545
+
546
+ def __init__(self, f, m: Mod | None, fn: Node | None, env: dict | None = None, depth: int = 0, stack=()):
547
+ self.f, self.m, self.fn, self.env, self.depth, self.stack = f, m, fn, env or {}, depth, stack
548
+
549
+
550
+ class Ecto:
551
+ def __init__(self, ix: Index):
552
+ self.ix = ix
553
+
554
+ # ---- sources
555
+ def from_mod(self, mod: Mod) -> Q:
556
+ q = Q()
557
+ q.add_src(q_table(self.ix.table_of(mod)), mod)
558
+ return q
559
+
560
+ def from_table(self, name: str) -> Q:
561
+ q = Q()
562
+ q.add_src(q_table(name), None)
563
+ return q
564
+
565
+ def source(self, node: Node, sc: Scope) -> list[Q]:
566
+ """Queries a source expression stands for (`Site`, `"sites"`, a query in a variable, a function's result)."""
567
+ return self.query(node, sc)
568
+
569
+ # ---- the evaluator: alternatives of a query expression
570
+ def query(self, node: Node | None, sc: Scope, piped: list[Q] | None = None) -> list[Q]:
571
+ node = strip(node)
572
+ if node is None or sc.depth > SETTINGS["ecto_follow_depth"] * 4:
573
+ return []
574
+ typ = node.type
575
+ if typ == "alias":
576
+ mod = self.ix.mod(sc.m, t(node))
577
+ if mod is not None and mod.table:
578
+ return [self.from_mod(mod)]
579
+ return []
580
+ if typ in ("string", "sigil"):
581
+ st = string_text(node)
582
+ if st and st[0] and re.fullmatch(r"[\w.«»]+", st[0]):
583
+ return [self.from_table(st[0])]
584
+ return []
585
+ if typ == "tuple":
586
+ items = kids(node)
587
+ if len(items) == 2:
588
+ st = string_text(items[0])
589
+ mod = self.ix.mod(sc.m, t(items[1])) if items[1].type == "alias" else None
590
+ if st and not st[1]:
591
+ q = Q()
592
+ q.add_src(q_table(st[0]), mod)
593
+ return [q]
594
+ return []
595
+ if typ == "binary_operator" and op(node) == "|>":
596
+ left = self.query(node.child_by_field_name("left"), sc)
597
+ right = node.child_by_field_name("right")
598
+ if not left:
599
+ return []
600
+ if right is not None and right.type == "call":
601
+ return self.call(right, sc, left)
602
+ return []
603
+ if typ == "identifier":
604
+ return self.var(node, sc)
605
+ if typ == "unary_operator" and op(node) == "@" and sc.m is not None:
606
+ inner = node.child_by_field_name("operand")
607
+ name = call_target(inner)[1] if inner is not None and inner.type == "call" else t(inner)
608
+ val = sc.m.attrs.get(name)
609
+ return self.query(val, self.sub(sc)) if val is not None else []
610
+ if typ == "call":
611
+ mn, fn = call_target(node)
612
+ if mn == "" and fn in ("if", "unless", "case", "cond", "with"):
613
+ return self.branches(node, sc)
614
+ return self.call(node, sc, piped)
615
+ return []
616
+
617
+ def sub(self, sc: Scope, **kw) -> Scope:
618
+ return Scope(kw.get("f", sc.f), kw.get("m", sc.m), kw.get("fn", sc.fn), kw.get("env", sc.env), sc.depth + 1,
619
+ kw.get("stack", sc.stack))
620
+
621
+ def branches(self, node: Node, sc: Scope) -> list[Q]:
622
+ """`if` / `case` / `cond` choosing a query: one alternative per branch that gives one."""
623
+ out: list[Q] = []
624
+ mn, fn = call_target(node)
625
+ pos, kw, do = call_args(node)
626
+ bodies: list[Node] = []
627
+ if do is not None:
628
+ for c in kids(do):
629
+ if c.type == "stab_clause":
630
+ b = c.child_by_field_name("right")
631
+ if b is not None:
632
+ bodies.append(b)
633
+ elif c.type == "else_block":
634
+ bodies.extend(kids(c)[-1:] if not any(x.type == "stab_clause" for x in kids(c)) else
635
+ [x.child_by_field_name("right") for x in kids(c) if x.type == "stab_clause" and x.child_by_field_name("right") is not None])
636
+ if fn in ("if", "unless"):
637
+ body = [c for c in kids(do) if c.type not in ("else_block", "stab_clause")]
638
+ if body:
639
+ bodies.insert(0, body[-1])
640
+ if not any(c.type == "else_block" for c in kids(do)):
641
+ bodies.append(None) # no else: nil, not a query
642
+ for k in ("do", "else"):
643
+ if k in kw:
644
+ bodies.append(kw[k])
645
+ for b in bodies:
646
+ if b is None:
647
+ continue
648
+ last = kids(b)[-1] if b.type in ("body", "block") and kids(b) else b
649
+ for q in self.query(last, self.sub(sc)):
650
+ out.append(q)
651
+ if len(out) > 1:
652
+ for q in out:
653
+ q.notes.append(f"one of {len(out)} branches of `{fn}`")
654
+ return out[: SETTINGS["max_variants"]]
655
+
656
+ def var(self, node: Node, sc: Scope) -> list[Q]:
657
+ name = t(node)
658
+ found = self.assignment(node, name, sc)
659
+ if found is not None:
660
+ return self.query(found, self.sub(sc))
661
+ if name in sc.env:
662
+ v = sc.env[name]
663
+ if isinstance(v, list):
664
+ return [q.copy() for q in v]
665
+ if isinstance(v, tuple):
666
+ node2, sc2 = v
667
+ return self.query(node2, sc2)
668
+ return []
669
+
670
+ def assignment(self, use: Node, name: str, sc: Scope) -> Node | None:
671
+ """The right side of the last `name = ...` before `use`, at the use's block level or an enclosing one."""
672
+ n = use
673
+ while n is not None and n is not sc.fn:
674
+ p = n.parent
675
+ if p is None:
676
+ break
677
+ if p.type in ("do_block", "body", "block", "stab_clause", "source"):
678
+ prev = []
679
+ for c in p.named_children:
680
+ if c.start_byte >= n.start_byte:
681
+ break
682
+ prev.append(c)
683
+ for c in reversed(prev):
684
+ if c.type == "binary_operator" and op(c) == "=":
685
+ left = c.child_by_field_name("left")
686
+ if left is not None and left.type == "identifier" and t(left) == name:
687
+ return c.child_by_field_name("right")
688
+ # `%{a: x} = ...` and other patterns: not followed
689
+ if p.type == "call" and call_target(p)[1] in ("def", "defp"):
690
+ break
691
+ n = p
692
+ return None
693
+
694
+ def fn_body(self, clause: Node) -> tuple[list[Node], Node | None]:
695
+ """(parameter nodes, last expression) of a def clause."""
696
+ pos, kw, do = call_args(clause)
697
+ head = pos[0] if pos else None
698
+ if head is not None and head.type == "binary_operator" and op(head) == "when":
699
+ head = head.child_by_field_name("left")
700
+ params: list[Node] = []
701
+ if head is not None and head.type == "call":
702
+ params, _k, _d = call_args(head)
703
+ body = None
704
+ if do is not None:
705
+ stmts = [c for c in kids(do) if c.type not in ("rescue_block", "after_block", "catch_block", "else_block")]
706
+ body = stmts[-1] if stmts else None
707
+ elif "do" in kw:
708
+ body = kw["do"]
709
+ return params, body
710
+
711
+ def follow(self, mod: Mod, fname: str, args: list, sc: Scope) -> list[Q]:
712
+ """A function of the repository that returns a query: its last expression, with the arguments bound."""
713
+ clauses = mod.fns.get(fname) or []
714
+ key = (mod.name, fname)
715
+ if not clauses or key in sc.stack or sc.depth > SETTINGS["ecto_follow_depth"] * 4 or len(sc.stack) >= SETTINGS["ecto_follow_depth"]:
716
+ return []
717
+ out: list[Q] = []
718
+ for clause in clauses:
719
+ params, body = self.fn_body(clause)
720
+ if body is None:
721
+ continue
722
+ env: dict = {}
723
+ for i, p in enumerate(params):
724
+ if p.type == "binary_operator" and op(p) == "\\\\":
725
+ default = p.child_by_field_name("right")
726
+ p = p.child_by_field_name("left")
727
+ if i >= len(args):
728
+ if p is not None and p.type == "identifier":
729
+ env[t(p)] = (default, sc)
730
+ continue
731
+ elif p.type == "binary_operator" and op(p) == "=":
732
+ p = p.child_by_field_name("right") if p.child_by_field_name("right").type == "identifier" else p.child_by_field_name("left")
733
+ if p is None or p.type != "identifier" or i >= len(args):
734
+ continue
735
+ a = args[i]
736
+ env[t(p)] = a if isinstance(a, list) else (a, sc)
737
+ got = self.query(body, Scope(mod.f, mod, clause, env, sc.depth + 1, sc.stack + (key,)))
738
+ for q in got:
739
+ q.followed.append(f"{mod.name}.{fname}")
740
+ if len(clauses) > 1:
741
+ q.notes.append(f"{mod.name}.{fname} has {len(clauses)} clauses; each that builds a query is a variant")
742
+ out.extend(got)
743
+ if len(out) >= SETTINGS["max_variants"]:
744
+ break
745
+ return out[: SETTINGS["max_variants"]]
746
+
747
+ def call(self, node: Node, sc: Scope, piped: list[Q] | None) -> list[Q]:
748
+ mn, fn = call_target(node)
749
+ pos, kw, _do = call_args(node)
750
+ args: list = ([piped] if piped is not None else []) + pos
751
+ if kw:
752
+ args.append(("kw", kw))
753
+ if mn in ("", "Ecto.Query", "Query") and fn == "from":
754
+ return self.from_(pos, kw_list(node), sc, piped)
755
+ if mn in ("", "Ecto.Query", "Query") and fn == "subquery":
756
+ inner = self.arg_query(args[0], sc) if args else []
757
+ out = []
758
+ for q in inner:
759
+ s = Q()
760
+ s.add_src("(" + self.select_sql(q) + ")", None)
761
+ s.notes.extend(q.notes)
762
+ s.runtime += q.runtime
763
+ out.append(s)
764
+ return out
765
+ if mn in ("", "Ecto", "Ecto.Query", "Query") and fn == "assoc" and len(pos) >= 2 and piped is None:
766
+ return self.assoc_query(pos[0], pos[1], sc)
767
+ if mn in ("", "Ecto.Query", "Query") and fn in QUERY_MACROS:
768
+ if not args:
769
+ return []
770
+ base = self.arg_query(args[0], sc)
771
+ if not base:
772
+ return []
773
+ rest = args[1:]
774
+ out = []
775
+ for q in base:
776
+ q2 = q.copy()
777
+ self.macro(q2, fn, rest, sc)
778
+ out.append(q2)
779
+ return out
780
+ # a function of the repository
781
+ target: Mod | None = None
782
+ if mn == "":
783
+ target = sc.m
784
+ if target is not None and fn not in target.fns:
785
+ target = None
786
+ else:
787
+ target = self.ix.mod(sc.m, mn)
788
+ if target is not None and fn in target.fns:
789
+ got = self.follow(target, fn, args, sc)
790
+ if got:
791
+ return got
792
+ # A function this reader cannot follow that is handed the query (Enum.reduce(filters, q, ...), a filter
793
+ # helper in a library): the query, plus what it adds as a run-time part.
794
+ if piped is not None and piped:
795
+ if mn in ("Repo",) or mn.endswith("Repo"):
796
+ return []
797
+ out = []
798
+ for q in piped:
799
+ q2 = q.copy()
800
+ q2.where.append(("AND", mark(t(node))))
801
+ q2.runtime += 1
802
+ q2.notes.append(f"{(mn + '.') if mn else ''}{fn}(...) changes the query at run time")
803
+ out.append(q2)
804
+ return out
805
+ if mn == "Enum" and fn in ("reduce", "reduce_while") and len(pos) >= 2:
806
+ base = self.query(pos[1], self.sub(sc))
807
+ out = []
808
+ for q in base:
809
+ q2 = q.copy()
810
+ q2.where.append(("AND", mark(t(node))))
811
+ q2.runtime += 1
812
+ q2.notes.append("Enum.reduce adds conditions at run time")
813
+ out.append(q2)
814
+ return out
815
+ return []
816
+
817
+ def arg_query(self, a, sc: Scope) -> list[Q]:
818
+ if isinstance(a, list):
819
+ return [q.copy() for q in a]
820
+ if isinstance(a, tuple):
821
+ return []
822
+ return self.query(a, self.sub(sc))
823
+
824
+ # ---- from / macros
825
+ def from_(self, pos: list[Node], kw: dict[str, Node], sc: Scope, piped: list[Q] | None) -> list[Q]:
826
+ binding_names: list[str] = []
827
+ src_node = None
828
+ if piped is not None:
829
+ bases = [q.copy() for q in piped]
830
+ first = pos[0] if pos else None
831
+ else:
832
+ first = pos[0] if pos else None
833
+ bases = None
834
+ if first is not None and first.type == "binary_operator" and op(first) == "in":
835
+ left, src_node = first.child_by_field_name("left"), first.child_by_field_name("right")
836
+ if left is not None:
837
+ if left.type == "list":
838
+ binding_names = [t(x) for x in kids(left)]
839
+ else:
840
+ binding_names = [t(left)]
841
+ elif first is not None and piped is None:
842
+ src_node = first
843
+ if src_node is not None and src_node.type == "unary_operator" and op(src_node) == "^":
844
+ src_node = src_node.child_by_field_name("operand")
845
+ if bases is None:
846
+ bases = self.query(src_node, self.sub(sc)) if src_node is not None else []
847
+ if not bases:
848
+ if src_node is None:
849
+ return []
850
+ raise_unknown = src_node.type in ("identifier", "call", "unary_operator")
851
+ if not raise_unknown:
852
+ return []
853
+ q = Q()
854
+ q.add_src(mark(t(src_node)), None) # the source is decided at run time
855
+ q.runtime += 1
856
+ q.notes.append(f"the source `{trim(t(src_node), 60)}` is decided at run time")
857
+ bases = [q]
858
+ out = []
859
+ for q in bases:
860
+ q = q.copy()
861
+ env = {}
862
+ for i, b in enumerate(binding_names):
863
+ if b and b != "_" and b != "...":
864
+ env[b] = i
865
+ if binding_names and binding_names[-1] not in ("_", "...") and "..." in binding_names:
866
+ env[binding_names[-1]] = len(q.srcs) - 1
867
+ ordered = kw if isinstance(kw, list) else list(kw.items())
868
+ last_join = None
869
+ for k, v in ordered:
870
+ if k in JOIN_KW:
871
+ last_join = self.join(q, JOIN_KW[k], v, env, sc)
872
+ elif k == "on" and last_join is not None:
873
+ q.joins[last_join] += " ON " + self.expr(v, q, env, sc)
874
+ elif k == "as":
875
+ idx = len(q.srcs) - 1 if last_join is not None else 0
876
+ q.named[t(v).lstrip(":")] = idx
877
+ else:
878
+ self.clause(q, k, v, env, sc)
879
+ for i, j in enumerate(q.joins):
880
+ if " ON " not in j and not j.startswith(("CROSS", "ARRAY", "LEFT ARRAY")):
881
+ q.joins[i] = j + " ON TRUE"
882
+ out.append(q)
883
+ return out
884
+
885
+ def bindings(self, q: Q, node: Node | None) -> dict[str, int]:
886
+ env: dict[str, int] = {}
887
+ if node is None or node.type != "list":
888
+ return env
889
+ items = kids(node)
890
+ names = []
891
+ for x in items:
892
+ if x.type == "keywords":
893
+ for k, v in pairs(x):
894
+ if k in q.named:
895
+ env[t(v)] = q.named[k]
896
+ continue
897
+ if x.type == "tuple" and len(kids(x)) == 2:
898
+ k = t(kids(x)[0]).lstrip(":")
899
+ if k in q.named:
900
+ env[t(kids(x)[1])] = q.named[k]
901
+ continue
902
+ names.append(t(x))
903
+ if "..." in names:
904
+ i = names.index("...")
905
+ for j, nm in enumerate(names[:i]):
906
+ env[nm] = j
907
+ tail = names[i + 1:]
908
+ for j, nm in enumerate(tail):
909
+ env[nm] = len(q.srcs) - len(tail) + j
910
+ else:
911
+ for j, nm in enumerate(names):
912
+ if j < len(q.srcs):
913
+ env[nm] = j
914
+ return env
915
+
916
+ def macro(self, q: Q, fn: str, rest: list, sc: Scope) -> None:
917
+ kw = {}
918
+ pos = []
919
+ for a in rest:
920
+ if isinstance(a, tuple) and a and a[0] == "kw":
921
+ kw = a[1]
922
+ else:
923
+ pos.append(a)
924
+ if fn == "join":
925
+ qual = t(pos[0]).lstrip(":") if pos else "inner"
926
+ env = self.bindings(q, pos[1]) if len(pos) > 1 else {}
927
+ expr = pos[2] if len(pos) > 2 else None
928
+ if expr is None:
929
+ return
930
+ idx = self.join(q, JOIN_QUAL.get(qual, "INNER JOIN"), expr, env, sc)
931
+ if idx is not None:
932
+ if "on" in kw:
933
+ q.joins[idx] += " ON " + self.expr(kw["on"], q, env, sc)
934
+ elif not q.joins[idx].startswith(("CROSS", "ARRAY", "LEFT ARRAY")) and " ON " not in q.joins[idx]:
935
+ q.joins[idx] += " ON TRUE"
936
+ if "as" in kw:
937
+ q.named[t(kw["as"]).lstrip(":")] = len(q.srcs) - 1
938
+ return
939
+ if fn in ("first", "last"):
940
+ pk = (q.root_mod.pk if q.root_mod else []) or ["id"]
941
+ field = t(pos[0]).lstrip(":") if pos else pk[0]
942
+ q.order = [f"{q.srcs[0]['alias']}.{q_ident(field)}" + (" DESC" if fn == "last" else "")]
943
+ q.limit = "1"
944
+ return
945
+ if fn in ("preload", "exclude", "windows", "hints", "reverse_order"):
946
+ if fn == "preload" and pos:
947
+ q.preload.extend(self.preload_names(pos[-1]))
948
+ if fn == "exclude":
949
+ what = t(pos[0]).lstrip(":") if pos else ""
950
+ if what in ("where", "order_by", "select", "limit", "offset", "preload", "group_by"):
951
+ setattr(q, {"order_by": "order", "group_by": "group"}.get(what, what), [] if what in ("where", "order_by", "group_by", "preload") else None)
952
+ return
953
+ if fn == "prefix":
954
+ return
955
+ if fn in ("union", "union_all", "intersect", "except", "with_cte", "combinations"):
956
+ q.notes.append(f"{fn}(...) is not written out")
957
+ q.runtime += 1
958
+ q.where.append(("AND", mark(fn + "(...)")))
959
+ return
960
+ env = self.bindings(q, pos[0]) if len(pos) > 1 and pos[0] is not None and not isinstance(pos[0], (list, tuple)) and pos[0].type == "list" else {}
961
+ val = pos[1] if len(pos) > 1 and env is not None and pos[0] is not None and not isinstance(pos[0], (list, tuple)) and pos[0].type == "list" else (pos[0] if pos else None)
962
+ if val is None and kw:
963
+ # `where(q, foo: ^x)` keyword filters, `update(q, set: [...])`
964
+ if fn in ("where", "or_where"):
965
+ conds = [f"{q.srcs[0]['alias']}.{q_ident(self.col(q, 0, k))} = {self.value(v, q, {}, sc)}" for k, v in kw.items()]
966
+ q.where.append(("OR" if fn == "or_where" else "AND", " AND ".join(conds)))
967
+ return
968
+ if fn == "update":
969
+ self.clause(q, "update", kw, {}, sc)
970
+ return
971
+ return
972
+ if val is None:
973
+ return
974
+ if val.type == "keywords" and fn in ("where", "or_where"):
975
+ conds = [f"{q.srcs[0]['alias']}.{q_ident(self.col(q, 0, k))} = {self.value(v, q, env, sc)}" for k, v in pairs(val)]
976
+ q.where.append(("OR" if fn == "or_where" else "AND", " AND ".join(conds)))
977
+ return
978
+ self.clause(q, fn, val, env, sc)
979
+
980
+ def clause(self, q: Q, k: str, v, env: dict, sc: Scope) -> None:
981
+ if k in ("where", "or_where"):
982
+ if isinstance(v, Node) and v.type == "list" and any(x.type == "keywords" for x in kids(v)):
983
+ conds = [f"{q.srcs[0]['alias']}.{q_ident(self.col(q, 0, a))} = {self.value(b, q, env, sc)}" for a, b in pairs(v)]
984
+ q.where.append(("OR" if k == "or_where" else "AND", " AND ".join(conds)))
985
+ else:
986
+ q.where.append(("OR" if k == "or_where" else "AND", self.expr(v, q, env, sc)))
987
+ elif k in ("having", "or_having"):
988
+ q.having.append(self.expr(v, q, env, sc))
989
+ elif k == "select":
990
+ q.select = self.select(v, q, env, sc)
991
+ elif k == "select_merge":
992
+ q.select_merge.append(self.select(v, q, env, sc))
993
+ elif k == "order_by":
994
+ q.order.extend(self.order(v, q, env, sc))
995
+ elif k == "group_by":
996
+ items = kids(v) if v.type == "list" else [v]
997
+ q.group.extend(self.expr(x, q, env, sc) for x in items)
998
+ elif k == "limit":
999
+ q.limit = self.value(v, q, env, sc)
1000
+ elif k == "offset":
1001
+ q.offset = self.value(v, q, env, sc)
1002
+ elif k == "distinct":
1003
+ if t(v) == "true":
1004
+ q.distinct = "DISTINCT"
1005
+ elif t(v) not in ("false", "nil"):
1006
+ items = kids(v) if v.type == "list" else [v]
1007
+ q.distinct = "DISTINCT ON (" + ", ".join(self.order_item(x, q, env, sc)[0] for x in items) + ")"
1008
+ elif k == "lock":
1009
+ st = string_text(v)
1010
+ q.lock = st[0] if st and not st[1] else mark(t(v))
1011
+ elif k == "preload":
1012
+ q.preload.extend(self.preload_names(v))
1013
+ elif k == "update":
1014
+ items = pairs(v) if isinstance(v, Node) else list(v.items())
1015
+ for kind, kv in items:
1016
+ for col, val in (pairs(kv) if isinstance(kv, Node) else []):
1017
+ c = f"{q_ident(self.col(q, 0, col))}"
1018
+ vv = self.value(val, q, env, sc)
1019
+ if kind == "set":
1020
+ q.update.append(f"{c} = {vv}")
1021
+ elif kind == "inc":
1022
+ q.update.append(f"{c} = {q.srcs[0]['alias']}.{c} + {vv}")
1023
+ elif kind == "push":
1024
+ q.update.append(f"{c} = array_append({q.srcs[0]['alias']}.{c}, {vv})")
1025
+ elif kind == "pull":
1026
+ q.update.append(f"{c} = array_remove({q.srcs[0]['alias']}.{c}, {vv})")
1027
+ elif k in ("prefix", "hints", "windows", "on", "as"):
1028
+ return
1029
+
1030
+ def join(self, q: Q, kind: str, v: Node, env: dict, sc: Scope) -> int | None:
1031
+ """Adds a joined source; returns the index of the join clause written, or None."""
1032
+ name = ""
1033
+ src = v
1034
+ if v.type == "binary_operator" and op(v) == "in":
1035
+ name, src = t(v.child_by_field_name("left")), v.child_by_field_name("right")
1036
+ src = strip(src)
1037
+ if src is not None and src.type == "unary_operator" and op(src) == "^":
1038
+ src = strip(src.child_by_field_name("operand"))
1039
+ if src is not None and src.type == "call" and call_target(src)[1] == "assoc" and call_target(src)[0] in ("", "Ecto", "Ecto.Query"):
1040
+ p, _k, _d = call_args(src)
1041
+ if len(p) >= 2 and t(p[0]) in env:
1042
+ owner = env[t(p[0])]
1043
+ idx = self.assoc_join(q, kind, owner, t(p[1]).lstrip(":"))
1044
+ if idx is not None:
1045
+ if name:
1046
+ env[name] = len(q.srcs) - 1
1047
+ return idx
1048
+ sql = mark(t(src))
1049
+ q.runtime += 1
1050
+ mod = None
1051
+ else:
1052
+ got = self.query(src, self.sub(sc)) if src is not None else []
1053
+ mod = None
1054
+ if got and len(got[0].srcs) == 1 and not got[0].where and not got[0].joins:
1055
+ sql, mod = got[0].srcs[0]["sql"], got[0].srcs[0]["mod"]
1056
+ elif got:
1057
+ sql = "(" + self.select_sql(got[0]) + ")"
1058
+ else:
1059
+ sql = mark(t(src))
1060
+ q.runtime += 1
1061
+ q.notes.append(f"a joined source `{trim(t(src), 50)}` is decided at run time")
1062
+ i = q.add_src(sql, mod)
1063
+ if name:
1064
+ env[name] = i
1065
+ q.joins.append(f"{kind} {sql} AS {q.srcs[i]['alias']}")
1066
+ return len(q.joins) - 1
1067
+
1068
+ def assoc_join(self, q: Q, kind: str, owner: int, assoc: str) -> int | None:
1069
+ om = q.srcs[owner]["mod"]
1070
+ if om is None or assoc not in om.assocs:
1071
+ return None
1072
+ a = om.assocs[assoc]
1073
+ oal = q.srcs[owner]["alias"]
1074
+ if a.through:
1075
+ cur, last = owner, None
1076
+ for step in a.through:
1077
+ last = self.assoc_join(q, kind, cur, step)
1078
+ if last is None:
1079
+ return None
1080
+ cur = len(q.srcs) - 1
1081
+ return last
1082
+ tm = self.ix.mods.get(a.target)
1083
+ if tm is None or not tm.table:
1084
+ return None
1085
+ if a.kind == "many_to_many":
1086
+ jt = a.join_through
1087
+ jmod = None
1088
+ if jt.startswith("@mod:"):
1089
+ jmod = self.ix.mods.get(jt[5:])
1090
+ if jmod is None or not jmod.table:
1091
+ return None
1092
+ jt = self.ix.table_of(jmod)
1093
+ keys = a.join_keys or [(underscore(om.name) + "_id", "id"), (underscore(tm.name) + "_id", "id")]
1094
+ ji = q.add_src(q_table(jt), jmod)
1095
+ jal = q.srcs[ji]["alias"]
1096
+ q.joins.append(f"{kind} {q_table(jt)} AS {jal} ON {jal}.{q_ident(keys[0][0])} = {oal}.{q_ident(keys[0][1])}")
1097
+ ti = q.add_src(q_table(self.ix.table_of(tm)), tm)
1098
+ tal = q.srcs[ti]["alias"]
1099
+ q.joins.append(f"{kind} {q_table(self.ix.table_of(tm))} AS {tal} ON {tal}.{q_ident(keys[1][1])} = {jal}.{q_ident(keys[1][0])}")
1100
+ return len(q.joins) - 1
1101
+ ti = q.add_src(q_table(self.ix.table_of(tm)), tm)
1102
+ tal = q.srcs[ti]["alias"]
1103
+ if a.kind == "belongs_to":
1104
+ on = f"{tal}.{q_ident(a.references)} = {oal}.{q_ident(a.fk)}"
1105
+ else:
1106
+ on = f"{tal}.{q_ident(a.fk)} = {oal}.{q_ident(om.pk[0] if om.pk else 'id')}"
1107
+ q.joins.append(f"{kind} {q_table(self.ix.table_of(tm))} AS {tal} ON {on}")
1108
+ return len(q.joins) - 1
1109
+
1110
+ def assoc_target(self, assoc: str, owner: Mod | None) -> tuple[Mod, Assoc] | None:
1111
+ """The association by name: on the owner's schema when known, else the one schema that defines it (or all that
1112
+ define it agree on target and key)."""
1113
+ if owner is not None and assoc in owner.assocs:
1114
+ return owner, owner.assocs[assoc]
1115
+ cands = [(m, a) for m, a in self.ix.assoc_by_name.get(assoc, []) if not a.through]
1116
+ if not cands:
1117
+ return None
1118
+ keys = {(a.kind, a.target, a.fk, a.join_through) for _m, a in cands}
1119
+ return cands[0] if len(keys) == 1 else None
1120
+
1121
+ def assoc_query(self, struct: Node, assoc_node: Node, sc: Scope, owner: Mod | None = None, many: bool = False) -> list[Q]:
1122
+ name = t(assoc_node).lstrip(":")
1123
+ if assoc_node.type == "list" or not re.fullmatch(r"\w+[?!]?", name):
1124
+ return []
1125
+ found = self.assoc_target(name, owner)
1126
+ if found is None:
1127
+ return []
1128
+ om, a = found
1129
+ tm = self.ix.mods.get(a.target)
1130
+ if tm is None or not tm.table:
1131
+ return []
1132
+ q = self.from_mod(tm)
1133
+ ids = mark(t(struct)) if not many else mark(t(struct) + " ids")
1134
+ cmp = (lambda col, v: f"s0.{q_ident(col)} = ANY({v})") if many else (lambda col, v: f"s0.{q_ident(col)} = {v}")
1135
+ if a.kind == "belongs_to":
1136
+ q.where.append(("AND", cmp(a.references, ids)))
1137
+ elif a.kind == "many_to_many":
1138
+ jt = a.join_through
1139
+ if jt.startswith("@mod:"):
1140
+ jm = self.ix.mods.get(jt[5:])
1141
+ if jm is None or not jm.table:
1142
+ return []
1143
+ jt = self.ix.table_of(jm)
1144
+ keys = a.join_keys or [(underscore(om.name) + "_id", "id"), (underscore(tm.name) + "_id", "id")]
1145
+ q.add_src(q_table(jt), None)
1146
+ q.joins.append(f"INNER JOIN {q_table(jt)} AS s1 ON s1.{q_ident(keys[1][0])} = s0.{q_ident(keys[1][1])}")
1147
+ q.where.append(("AND", cmp(keys[0][0], ids).replace("s0.", "s1.", 1)))
1148
+ else:
1149
+ q.where.append(("AND", cmp(a.fk, ids)))
1150
+ if owner is None:
1151
+ q.notes.append(f"association :{name}, found by its name")
1152
+ return [q]
1153
+
1154
+ def preload_names(self, v: Node | None) -> list[str]:
1155
+ if v is None:
1156
+ return []
1157
+ if v.type == "atom":
1158
+ return [t(v)[1:]]
1159
+ out = []
1160
+ if v.type == "list":
1161
+ for x in kids(v):
1162
+ if x.type == "atom":
1163
+ out.append(t(x)[1:])
1164
+ elif x.type == "keywords":
1165
+ out.extend(k for k, _ in pairs(x))
1166
+ if v.type == "keywords":
1167
+ out.extend(k for k, _ in pairs(v))
1168
+ return out
1169
+
1170
+ # ---- expressions
1171
+ def col(self, q: Q, idx: int, field: str) -> str:
1172
+ mod = q.srcs[idx]["mod"] if idx < len(q.srcs) else None
1173
+ if mod is not None and field in mod.fields:
1174
+ return mod.fields[field][0]
1175
+ return field
1176
+
1177
+ def value(self, v: Node | None, q: Q, env: dict, sc: Scope) -> str:
1178
+ v = strip(v)
1179
+ if v is None:
1180
+ return "NULL"
1181
+ if v.type == "unary_operator" and op(v) == "^":
1182
+ inner = strip(v.child_by_field_name("operand"))
1183
+ lit = self.attr_literal(inner, sc)
1184
+ return lit if lit is not None else mark(t(inner))
1185
+ lit = self.attr_literal(v, sc)
1186
+ if lit is not None:
1187
+ return lit
1188
+ return self.expr(v, q, env, sc)
1189
+
1190
+ def attr_literal(self, v: Node | None, sc: Scope) -> str | None:
1191
+ """`@batch_size` bound to a number or string literal in the module."""
1192
+ if v is None or v.type != "unary_operator" or op(v) != "@" or sc.m is None:
1193
+ return None
1194
+ inner = v.child_by_field_name("operand")
1195
+ name = call_target(inner)[1] if inner is not None and inner.type == "call" else t(inner)
1196
+ val = sc.m.attrs.get(name)
1197
+ if val is not None and val.type in ("integer", "float"):
1198
+ return t(val).replace("_", "")
1199
+ st = string_text(val) if val is not None else None
1200
+ if st is not None and not st[1]:
1201
+ return "'" + st[0].replace("'", "''") + "'"
1202
+ return None
1203
+
1204
+ def expr(self, v: Node | None, q: Q, env: dict, sc: Scope) -> str:
1205
+ v = strip(v)
1206
+ if v is None:
1207
+ return "NULL"
1208
+ typ = v.type
1209
+ if typ == "unary_operator":
1210
+ o = op(v)
1211
+ inner = v.child_by_field_name("operand")
1212
+ if o == "^":
1213
+ return mark(t(inner))
1214
+ if o in ("not", "!"):
1215
+ if inner is not None and inner.type == "call" and call_target(inner) == ("", "is_nil"):
1216
+ p, _k, _d = call_args(inner)
1217
+ if p:
1218
+ return f"{self.expr(p[0], q, env, sc)} IS NOT NULL"
1219
+ return f"NOT ({self.expr(inner, q, env, sc)})"
1220
+ if o == "-":
1221
+ return "-" + self.expr(inner, q, env, sc)
1222
+ return mark(t(v))
1223
+ if typ == "binary_operator":
1224
+ o = op(v)
1225
+ left, right = v.child_by_field_name("left"), v.child_by_field_name("right")
1226
+ if o in ("in", "not in"):
1227
+ lhs = self.expr(left, q, env, sc)
1228
+ r = strip(right)
1229
+ neg = o == "not in"
1230
+ if r is not None and r.type == "unary_operator" and op(r) == "^":
1231
+ return f"{'NOT (' if neg else ''}{lhs} = ANY({mark(t(r.child_by_field_name('operand')))}){')' if neg else ''}"
1232
+ if r is not None and r.type == "list":
1233
+ items = [self.value(x, q, env, sc) for x in kids(r)]
1234
+ return f"{lhs} {'NOT IN' if neg else 'IN'} ({', '.join(items) or 'NULL'})"
1235
+ if r is not None and r.type == "call" and call_target(r)[1] == "subquery":
1236
+ p, _k, _d = call_args(r)
1237
+ sub = self.query(p[0], self.sub(sc)) if p else []
1238
+ if sub:
1239
+ return f"{lhs} {'NOT IN' if neg else 'IN'} ({self.select_sql(sub[0])})"
1240
+ return f"{lhs} {'NOT IN' if neg else 'IN'} ({mark(t(right))})"
1241
+ if o in ("==", "!=") and strip(right) is not None and strip(right).type == "nil":
1242
+ return f"{self.expr(left, q, env, sc)} IS {'NOT ' if o == '!=' else ''}NULL"
1243
+ if o in BINOP:
1244
+ le, re_ = self.expr(left, q, env, sc), self.expr(right, q, env, sc)
1245
+ if o in ("and", "or", "&&", "||"):
1246
+ return f"({le}) {BINOP[o]} ({re_})"
1247
+ return f"{le} {BINOP[o]} {re_}"
1248
+ if o == "<>":
1249
+ return f"{self.expr(left, q, env, sc)} || {self.expr(right, q, env, sc)}"
1250
+ return mark(t(v))
1251
+ if typ == "call":
1252
+ mn, fn = call_target(v)
1253
+ pos, kw, _d = call_args(v)
1254
+ tg = v.child_by_field_name("target")
1255
+ if tg is not None and tg.type == "dot" and not pos and not any(c.type == "arguments" for c in v.children):
1256
+ pass
1257
+ if tg is not None and tg.type == "dot":
1258
+ left = tg.child_by_field_name("left")
1259
+ right = tg.child_by_field_name("right")
1260
+ if left is not None and left.type == "identifier" and t(left) in env and right is not None:
1261
+ i = env[t(left)]
1262
+ return f"{q.srcs[i]['alias']}.{q_ident(self.col(q, i, t(right)))}"
1263
+ if left is not None and left.type == "identifier" and t(left) not in env:
1264
+ return mark(t(v))
1265
+ if mn == "":
1266
+ if fn == "is_nil" and pos:
1267
+ return f"{self.expr(pos[0], q, env, sc)} IS NULL"
1268
+ if fn == "field" and len(pos) == 2 and t(pos[0]) in env:
1269
+ i = env[t(pos[0])]
1270
+ f_ = pos[1]
1271
+ if f_.type == "atom":
1272
+ return f"{q.srcs[i]['alias']}.{q_ident(self.col(q, i, t(f_)[1:]))}"
1273
+ return f"{q.srcs[i]['alias']}.{mark(t(f_))}"
1274
+ if fn == "fragment" and pos:
1275
+ st = string_text(pos[0])
1276
+ if st is None:
1277
+ return mark(t(v))
1278
+ parts = st[0].split("?")
1279
+ if len(parts) - 1 != len(pos) - 1:
1280
+ return mark(t(v))
1281
+ out = parts[0]
1282
+ for a, rest in zip(pos[1:], parts[1:]):
1283
+ out += self.value(a, q, env, sc) + rest
1284
+ return "(" + out + ")"
1285
+ if fn in ("like", "ilike") and len(pos) == 2:
1286
+ return f"{self.expr(pos[0], q, env, sc)} {fn.upper()} {self.value(pos[1], q, env, sc)}"
1287
+ if fn == "count":
1288
+ if not pos:
1289
+ return "count(*)"
1290
+ inner = self.expr(pos[0], q, env, sc) if pos[0].type != "identifier" or t(pos[0]) not in env else "*"
1291
+ if len(pos) > 1 and t(pos[1]) == ":distinct":
1292
+ return f"count(DISTINCT {inner})"
1293
+ return f"count({inner})"
1294
+ if fn in AGG and pos:
1295
+ return f"{AGG[fn]}({', '.join(self.expr(p, q, env, sc) for p in pos)})"
1296
+ if fn in ("type", "selected_as") and pos:
1297
+ inner = self.value(pos[0], q, env, sc)
1298
+ if fn == "selected_as" and len(pos) > 1:
1299
+ return f"{inner} AS {q_ident(t(pos[1]).lstrip(':'))}"
1300
+ return inner
1301
+ if fn == "exists" and pos:
1302
+ sub = self.query(pos[0], self.sub(sc))
1303
+ if sub:
1304
+ return f"EXISTS ({self.select_sql(sub[0])})"
1305
+ if fn in ("ago", "from_now", "datetime_add", "date_add") and pos:
1306
+ return mark(t(v))
1307
+ return mark(t(v))
1308
+ if typ == "identifier":
1309
+ nm = t(v)
1310
+ if nm in env:
1311
+ i = env[nm]
1312
+ return f"{q.srcs[i]['alias']}.*"
1313
+ return mark(nm)
1314
+ if typ in ("string", "sigil"):
1315
+ st = string_text(v)
1316
+ if st is not None and not st[1]:
1317
+ return "'" + st[0].replace("'", "''") + "'"
1318
+ return mark(t(v))
1319
+ if typ in ("integer", "float"):
1320
+ return t(v).replace("_", "")
1321
+ if typ == "boolean":
1322
+ return t(v).upper()
1323
+ if typ == "nil":
1324
+ return "NULL"
1325
+ if typ == "atom":
1326
+ return "'" + t(v)[1:] + "'"
1327
+ if typ == "list":
1328
+ return "ARRAY[" + ", ".join(self.value(x, q, env, sc) for x in kids(v)) + "]"
1329
+ return mark(t(v))
1330
+
1331
+ def all_cols(self, q: Q, i: int) -> list[str]:
1332
+ mod = q.srcs[i]["mod"]
1333
+ al = q.srcs[i]["alias"]
1334
+ if mod is not None and mod.fields:
1335
+ return [f"{al}.{q_ident(c)}" for c in mod.columns()]
1336
+ return [f"{al}.*"]
1337
+
1338
+ def select(self, v: Node, q: Q, env: dict, sc: Scope) -> str:
1339
+ v = strip(v)
1340
+ if v is None:
1341
+ return "*"
1342
+ items: list[str] = []
1343
+ if v.type == "identifier" and t(v) in env:
1344
+ items = self.all_cols(q, env[t(v)])
1345
+ elif v.type == "map":
1346
+ for c in kids(v):
1347
+ if c.type == "map_content":
1348
+ for x in kids(c):
1349
+ if x.type == "keywords":
1350
+ items.extend(self.select(val, q, env, sc) for _k, val in pairs(x))
1351
+ elif x.type == "binary_operator" and op(x) == "=>":
1352
+ items.append(self.select(x.child_by_field_name("right"), q, env, sc))
1353
+ elif x.type == "binary_operator" and op(x) == "|":
1354
+ items.append(self.select(x.child_by_field_name("left"), q, env, sc))
1355
+ for kk in kids(x.child_by_field_name("right")):
1356
+ if kk.type == "keywords":
1357
+ items.extend(self.select(val, q, env, sc) for _k, val in pairs(kk))
1358
+ elif c.type == "struct":
1359
+ continue
1360
+ elif v.type in ("tuple", "list"):
1361
+ for x in kids(v):
1362
+ if x.type == "keywords":
1363
+ items.extend(self.select(val, q, env, sc) for _k, val in pairs(x))
1364
+ else:
1365
+ items.append(self.select(x, q, env, sc))
1366
+ elif v.type == "call" and call_target(v) in (("", "struct"), ("", "map")):
1367
+ p, _k, _d = call_args(v)
1368
+ if len(p) == 2 and t(p[0]) in env:
1369
+ i = env[t(p[0])]
1370
+ fields = self.ix.atom_list(sc.m, p[1]) if sc.m is not None else None
1371
+ if fields:
1372
+ items = [f"{q.srcs[i]['alias']}.{q_ident(self.col(q, i, f_))}" for f_ in fields]
1373
+ else:
1374
+ items = self.all_cols(q, i)
1375
+ elif v.type == "call" and call_target(v) == ("", "merge"):
1376
+ p, _k, _d = call_args(v)
1377
+ items = [self.select(x, q, env, sc) for x in p]
1378
+ else:
1379
+ items = [self.expr(v, q, env, sc)]
1380
+ return ", ".join(x for x in items if x) or "*"
1381
+
1382
+ def order_item(self, x: Node, q: Q, env: dict, sc: Scope, direction: str = "") -> tuple[str, str]:
1383
+ return self.expr(x, q, env, sc), direction
1384
+
1385
+ def order(self, v: Node, q: Q, env: dict, sc: Scope) -> list[str]:
1386
+ v = strip(v)
1387
+ out = []
1388
+ dirs = {"asc": "", "desc": " DESC", "asc_nulls_first": " NULLS FIRST", "asc_nulls_last": " NULLS LAST",
1389
+ "desc_nulls_first": " DESC NULLS FIRST", "desc_nulls_last": " DESC NULLS LAST"}
1390
+ if v.type == "unary_operator" and op(v) == "^":
1391
+ q.runtime += 1
1392
+ return [mark(t(v.child_by_field_name("operand")))]
1393
+ items = kids(v) if v.type == "list" else [v]
1394
+ for x in items:
1395
+ if x.type == "keywords":
1396
+ for k, val in pairs(x):
1397
+ targets = kids(val) if val.type == "list" else [val]
1398
+ for tv in targets:
1399
+ col = f"{q.srcs[0]['alias']}.{q_ident(self.col(q, 0, t(tv)[1:]))}" if tv.type == "atom" else self.expr(tv, q, env, sc)
1400
+ out.append(col + dirs.get(k, ""))
1401
+ elif x.type == "tuple" and len(kids(x)) == 2:
1402
+ out.append(self.expr(kids(x)[1], q, env, sc) + dirs.get(t(kids(x)[0]).lstrip(":"), ""))
1403
+ elif x.type == "atom":
1404
+ out.append(f"{q.srcs[0]['alias']}.{q_ident(self.col(q, 0, t(x)[1:]))}")
1405
+ else:
1406
+ out.append(self.expr(x, q, env, sc))
1407
+ return out
1408
+
1409
+ # ---- SQL
1410
+ def _where(self, q: Q) -> str:
1411
+ acc = ""
1412
+ for conj, cond in q.where:
1413
+ if not acc:
1414
+ acc = f"({cond})"
1415
+ elif conj == "OR":
1416
+ acc = f"({acc} OR ({cond}))"
1417
+ else:
1418
+ acc = f"{acc} AND ({cond})"
1419
+ return acc
1420
+
1421
+ def from_clause(self, q: Q) -> str:
1422
+ s = q.srcs[0]
1423
+ out = f" FROM {s['sql']} AS {s['alias']}"
1424
+ for j in q.joins:
1425
+ out += " " + j
1426
+ return out
1427
+
1428
+ def select_sql(self, q: Q, select: str | None = None) -> str:
1429
+ cols = select or q.select or ", ".join(self.all_cols(q, 0))
1430
+ if q.select_merge:
1431
+ cols = ", ".join([cols] + q.select_merge)
1432
+ sql = "SELECT " + (q.distinct + " " if q.distinct else "") + cols + self.from_clause(q)
1433
+ w = self._where(q)
1434
+ if w:
1435
+ sql += " WHERE " + w
1436
+ if q.group:
1437
+ sql += " GROUP BY " + ", ".join(q.group)
1438
+ if q.having:
1439
+ sql += " HAVING " + " AND ".join(f"({h})" for h in q.having)
1440
+ if q.order:
1441
+ sql += " ORDER BY " + ", ".join(q.order)
1442
+ if q.limit:
1443
+ sql += " LIMIT " + q.limit
1444
+ if q.offset:
1445
+ sql += " OFFSET " + q.offset
1446
+ if q.lock:
1447
+ sql += " " + q.lock
1448
+ return sql
1449
+
1450
+ def scoped(self, q: Q) -> str:
1451
+ """`WHERE` for an update / delete of the query's rows; joins become `pk IN (SELECT ...)`."""
1452
+ s = q.srcs[0]
1453
+ if q.joins:
1454
+ pk = (s["mod"].pk if s["mod"] is not None else []) or ["id"]
1455
+ inner = Q()
1456
+ inner.__dict__.update(q.copy().__dict__)
1457
+ inner.select, inner.order, inner.limit, inner.offset, inner.select_merge = f"{s['alias']}.{q_ident(pk[0])}", [], None, None, []
1458
+ return f" WHERE {s['alias']}.{q_ident(pk[0])} IN ({self.select_sql(inner)})"
1459
+ w = self._where(q)
1460
+ return " WHERE " + w if w else ""
1461
+
1462
+
1463
+ # ---------------------------------------------------------------------------------------------- call sites
1464
+ class Run:
1465
+ def __init__(self, ix: Index, files: list):
1466
+ self.ix, self.files = ix, files
1467
+ self.e = Ecto(ix)
1468
+ self.out: list[RawSite] = []
1469
+
1470
+ def repo_of(self, m: Mod | None, name: str) -> tuple[bool, str]:
1471
+ """(is an Ecto repo, engine)."""
1472
+ full = self.ix.resolve(m, name)
1473
+ rm = self.ix.mods.get(full)
1474
+ if rm is not None:
1475
+ return (rm.repo_engine is not None, rm.repo_engine or "")
1476
+ if name.split(".")[-1].endswith("Repo"):
1477
+ repos = [x for x in self.ix.mods.values() if x.repo_engine is not None and x.name.split(".")[-1] == name.split(".")[-1]]
1478
+ if len(repos) == 1:
1479
+ return True, repos[0].repo_engine or ""
1480
+ return True, ""
1481
+ return False, ""
1482
+
1483
+ def _scan_file(self, f) -> None:
1484
+ # enclosing module and function of each node, by byte ranges
1485
+ mods = sorted((m for m in self.ix.mods.values() if m.f is f), key=lambda m: m.node.start_byte)
1486
+ for n in walk(f.root):
1487
+ if n.type != "call":
1488
+ continue
1489
+ mn, fn = call_target(n)
1490
+ if not mn or fn not in REPO_FUNCS:
1491
+ continue
1492
+ if not (mn.split(".")[-1].endswith("Repo")):
1493
+ continue
1494
+ m = None
1495
+ for x in mods:
1496
+ if x.node.start_byte <= n.start_byte < x.node.end_byte:
1497
+ m = x
1498
+ is_repo, engine = self.repo_of(m, mn)
1499
+ if not is_repo:
1500
+ continue
1501
+ clause = self.enclosing_def(n)
1502
+ sc = Scope(f, m, clause, {}, 0, ())
1503
+ try:
1504
+ self.site(f, m, n, mn, fn, engine, sc)
1505
+ except RecursionError:
1506
+ self.miss(f, n, "expression too deep", f.test)
1507
+
1508
+ @staticmethod
1509
+ def enclosing_def(n: Node) -> Node | None:
1510
+ p = n.parent
1511
+ while p is not None:
1512
+ if p.type == "call" and call_target(p)[0] == "" and call_target(p)[1] in ("def", "defp", "defmacro", "defmacrop"):
1513
+ return p
1514
+ p = p.parent
1515
+ return None
1516
+
1517
+ def symbol(self, m: Mod | None, clause: Node | None) -> str:
1518
+ name = ""
1519
+ if clause is not None:
1520
+ pos, _k, _d = call_args(clause)
1521
+ head = pos[0] if pos else None
1522
+ if head is not None and head.type == "binary_operator" and op(head) == "when":
1523
+ head = head.child_by_field_name("left")
1524
+ name = t(head) if head is not None and head.type == "identifier" else call_target(head)[1] if head is not None and head.type == "call" else ""
1525
+ return ".".join(x for x in ((m.name if m else ""), name) if x)
1526
+
1527
+ @staticmethod
1528
+ def in_loop(n: Node) -> bool:
1529
+ p = n.parent
1530
+ while p is not None:
1531
+ if p.type == "call":
1532
+ mn, fn = call_target(p)
1533
+ if mn == "" and fn in ("def", "defp"):
1534
+ return False
1535
+ if (mn == "" and fn == "for") or LOOP_FUNCS.match(f"{mn}.{fn}"):
1536
+ if p.child_by_field_name("target") is not None and not (p.child_by_field_name("target").start_byte <= n.start_byte < p.child_by_field_name("target").end_byte):
1537
+ return True
1538
+ p = p.parent
1539
+ return False
1540
+
1541
+ def miss(self, f, n: Node, reason: str, test: bool) -> None:
1542
+ STATS.miss(LIB, reason, f.rel, n.start_point[0] + 1, test)
1543
+
1544
+ def emit(self, f, m, n: Node, start: Node, sink: str, sql: str | None, resolution: str, table: str, operation: str,
1545
+ engine: str, sc: Scope, notes: list[str], confidence: str, mechanism: str, expr: Node | None = None) -> None:
1546
+ orm = {"library": LIB, "model_or_table": table, "operation": operation, "confidence": confidence,
1547
+ "mechanism": mechanism if not self.in_loop(n) or mechanism != "orm_api" else "orm_api_in_loop"}
1548
+ if notes:
1549
+ orm["notes"] = "; ".join(dict.fromkeys(notes))
1550
+ self.out.append(RawSite(
1551
+ file=f.rel, line=start.start_point[0] + 1, end_line=n.end_point[0] + 1, language="elixir", kind="call",
1552
+ sink=sink, symbol=self.symbol(m, sc.fn), sql=sql, resolution=resolution,
1553
+ expr=trim(t(expr if expr is not None else n)), in_loop=self.in_loop(n), engine_hint=engine, is_test=f.test,
1554
+ known_sink=True, orm=orm))
1555
+
1556
+ def site(self, f, m: Mod | None, n: Node, mn: str, fn: str, engine: str, sc: Scope) -> None:
1557
+ pos, kw, _d = call_args(n)
1558
+ parent = n.parent
1559
+ piped_node = None
1560
+ if parent is not None and parent.type == "binary_operator" and op(parent) == "|>" and parent.child_by_field_name("right") is not None \
1561
+ and parent.child_by_field_name("right").id == n.id:
1562
+ piped_node = parent.child_by_field_name("left")
1563
+ args = ([piped_node] if piped_node is not None else []) + pos
1564
+ start = piped_node if piped_node is not None else n
1565
+ sink = f"{mn}.{fn}"
1566
+ test = f.test
1567
+ STATS.seen(LIB, test)
1568
+ e = self.e
1569
+ base = fn.rstrip("!")
1570
+ if base in ("query",):
1571
+ sql_node = args[0] if args else None
1572
+ text, res = self.raw_sql(sql_node, sc)
1573
+ if text is None:
1574
+ self.emit(f, m, n, start, sink, None, "unresolved", "", "raw", engine, sc,
1575
+ ["raw SQL held where this reader cannot follow it"], "low", "orm_raw_fragment", sql_node)
1576
+ self.miss(f, n, "raw SQL text not found", test)
1577
+ return
1578
+ self.emit(f, m, n, start, sink, text, res, "", "raw", engine, sc, [], "high", "orm_raw_fragment", sql_node)
1579
+ STATS.hit(LIB, 1, test)
1580
+ return
1581
+ if not args:
1582
+ self.miss(f, n, "no query argument", test)
1583
+ return
1584
+ first = args[0]
1585
+ notes: list[str] = []
1586
+ if base in ("all", "one", "stream", "exists?", "aggregate", "delete_all", "update_all", "get", "get_by", "reload"):
1587
+ if base == "reload":
1588
+ qs = self.struct_query(first, sc)
1589
+ else:
1590
+ qs = e.query(first, sc)
1591
+ if not qs:
1592
+ self.unknown(f, m, n, start, sink, engine, sc, first, base, "the query's source is not known here")
1593
+ return
1594
+ sqls = []
1595
+ for q in qs:
1596
+ q = q.copy()
1597
+ op_name = "select"
1598
+ if base in ("get",) and len(args) > 1:
1599
+ pk = (q.root_mod.pk if q.root_mod else []) or ["id"]
1600
+ q.where.append(("AND", f"s0.{q_ident(pk[0])} = {e.value(args[1], q, {}, sc)}"))
1601
+ elif base == "get_by" and len(args) > 1:
1602
+ kv = pairs(args[1]) if args[1].type in ("list", "keywords") else []
1603
+ if not kv and args[1].type == "map":
1604
+ kv = [(k, v) for c in kids(args[1]) if c.type == "map_content" for x in kids(c) if x.type == "keywords" for k, v in pairs(x)]
1605
+ if kv:
1606
+ q.where.append(("AND", " AND ".join(f"s0.{q_ident(e.col(q, 0, k))} = {e.value(v, q, {}, sc)}" for k, v in kv)))
1607
+ else:
1608
+ q.where.append(("AND", mark(t(args[1]))))
1609
+ q.runtime += 1
1610
+ if base == "get_by" and kw and len(args) == 1:
1611
+ q.where.append(("AND", " AND ".join(f"s0.{q_ident(e.col(q, 0, k))} = {e.value(v, q, {}, sc)}" for k, v in kw.items())))
1612
+ if base == "exists?":
1613
+ sql = "SELECT TRUE" + e.from_clause(q) + (" WHERE " + e._where(q) if q.where else "") + " LIMIT 1"
1614
+ elif base == "aggregate":
1615
+ agg = t(args[1]).lstrip(":") if len(args) > 1 else "count"
1616
+ field = t(args[2]).lstrip(":") if len(args) > 2 else ""
1617
+ target = f"s0.{q_ident(e.col(q, 0, field))}" if field else "*"
1618
+ agg_sql = f"{agg}({target})"
1619
+ if q.limit or q.offset or q.distinct or q.group:
1620
+ sql = f"SELECT {agg}(*) FROM (" + e.select_sql(q) + ") AS s"
1621
+ else:
1622
+ q.order = []
1623
+ sql = e.select_sql(q, select=agg_sql)
1624
+ op_name = "count" if agg == "count" else "aggregate"
1625
+ elif base == "delete_all":
1626
+ s0 = q.srcs[0]
1627
+ sql = f"DELETE FROM {s0['sql']} AS {s0['alias']}" + e.scoped(q)
1628
+ op_name = "delete"
1629
+ elif base == "update_all":
1630
+ upd = args[1] if len(args) > 1 else None
1631
+ if upd is not None:
1632
+ e.clause(q, "update", upd, {}, sc)
1633
+ elif kw:
1634
+ e.clause(q, "update", kw, {}, sc)
1635
+ s0 = q.srcs[0]
1636
+ if not q.update:
1637
+ q.update.append(mark(t(upd) if upd is not None else "updates") + " = " + mark("values"))
1638
+ q.runtime += 1
1639
+ sql = f"UPDATE {s0['sql']} AS {s0['alias']} SET " + ", ".join(q.update) + e.scoped(q)
1640
+ op_name = "update"
1641
+ else:
1642
+ sql = e.select_sql(q)
1643
+ sqls.append((sql, q, op_name))
1644
+ for pl in q.preload if base in ("all", "one", "get", "get_by") else []:
1645
+ pq = self.preload_query(pl, q.root_mod)
1646
+ if pq is not None:
1647
+ sqls.append((e.select_sql(pq), pq, "select"))
1648
+ self.emit_all(f, m, n, start, sink, engine, sc, sqls, first)
1649
+ return
1650
+ if base == "preload":
1651
+ names = e.preload_names(args[1]) if len(args) > 1 else []
1652
+ owner = self.struct_mod(first, sc)
1653
+ sqls = []
1654
+ for nm in names:
1655
+ pq = self.preload_query(nm, owner)
1656
+ if pq is not None:
1657
+ sqls.append((e.select_sql(pq), pq, "select"))
1658
+ if not sqls:
1659
+ self.unknown(f, m, n, start, sink, engine, sc, args[1] if len(args) > 1 else first, "select",
1660
+ "the association's schema is not known here")
1661
+ return
1662
+ self.emit_all(f, m, n, start, sink, engine, sc, sqls, args[1] if len(args) > 1 else first)
1663
+ return
1664
+ if base in ("insert", "update", "delete", "insert_or_update"):
1665
+ mod = self.struct_mod(first, sc)
1666
+ if mod is None or not mod.table:
1667
+ self.unknown(f, m, n, start, sink, engine, sc, first, base, "the struct's schema is not known here")
1668
+ return
1669
+ table = q_table(self.ix.table_of(mod))
1670
+ pk = mod.pk or ["id"]
1671
+ fields, how = self.changed_fields(first, mod, sc)
1672
+ notes = [] if how == "exact" else [how]
1673
+ conf = "high" if how == "exact" else "medium"
1674
+ if base == "delete":
1675
+ sql = f"DELETE FROM {table} WHERE {q_ident(pk[0])} = {mark(t(first) + '.' + pk[0])}"
1676
+ op_name = "delete"
1677
+ elif base == "insert" or base == "insert_or_update":
1678
+ cols = [c for c in fields if c not in mod.pk or c in self.literal_keys(first)]
1679
+ for ts in ("inserted_at", "updated_at"):
1680
+ if ts in mod.fields and ts not in cols:
1681
+ cols.append(ts)
1682
+ cols_sql = [mod.fields[c][0] if c in mod.fields else c for c in cols]
1683
+ sql = f"INSERT INTO {table} ({', '.join(q_ident(c) for c in cols_sql)}) VALUES ({', '.join(mark(c) for c in cols)})"
1684
+ if mod.pk:
1685
+ sql += f" RETURNING {q_ident(mod.pk[0])}"
1686
+ op_name = "insert"
1687
+ oc = kw.get("on_conflict")
1688
+ if oc is not None:
1689
+ if t(oc) == ":nothing":
1690
+ sql = sql.replace(" RETURNING", " ON CONFLICT DO NOTHING RETURNING") if " RETURNING" in sql else sql + " ON CONFLICT DO NOTHING"
1691
+ else:
1692
+ notes.append(f"on_conflict: {trim(t(oc), 60)}")
1693
+ if base == "insert_or_update":
1694
+ notes.append("insert_or_update: an UPDATE when the struct is already loaded")
1695
+ else:
1696
+ cols = [c for c in fields if c not in mod.pk]
1697
+ if "updated_at" in mod.fields and "updated_at" not in cols:
1698
+ cols.append("updated_at")
1699
+ if not cols:
1700
+ cols = [c for c in mod.fields if c not in mod.pk]
1701
+ sets = ", ".join(f"{q_ident(mod.fields[c][0] if c in mod.fields else c)} = {mark(c)}" for c in cols)
1702
+ sql = f"UPDATE {table} SET {sets} WHERE {q_ident(pk[0])} = {mark(pk[0])}"
1703
+ op_name = "update"
1704
+ self.emit(f, m, n, start, sink, sql, "orm", self.ix.table_of(mod), op_name, engine, sc, notes, conf, "orm_api", first)
1705
+ STATS.hit(LIB, 1, test)
1706
+ return
1707
+ if base == "insert_all":
1708
+ src = args[0]
1709
+ qs = e.query(src, sc)
1710
+ if not qs:
1711
+ self.unknown(f, m, n, start, sink, engine, sc, src, "insert", "the target table is not known here")
1712
+ return
1713
+ q = qs[0]
1714
+ mod = q.root_mod
1715
+ rows = args[1] if len(args) > 1 else None
1716
+ cols = self.row_keys(rows, sc)
1717
+ conf, notes = "high", []
1718
+ if cols is None:
1719
+ cols = [c for c in (mod.fields if mod else {}) if c not in (mod.pk if mod else [])]
1720
+ notes.append("the rows' keys are decided at run time: the schema's fields are listed")
1721
+ conf = "medium"
1722
+ if not cols:
1723
+ self.unknown(f, m, n, start, sink, engine, sc, src, "insert", "the rows' columns are not known here")
1724
+ return
1725
+ cols_sql = [e.col(q, 0, c) for c in cols]
1726
+ sql = f"INSERT INTO {q.srcs[0]['sql']} ({', '.join(q_ident(c) for c in cols_sql)}) VALUES ({', '.join(mark(c) for c in cols)})"
1727
+ oc = kw.get("on_conflict")
1728
+ if oc is not None:
1729
+ if t(oc) == ":nothing":
1730
+ sql += " ON CONFLICT DO NOTHING"
1731
+ else:
1732
+ notes.append(f"on_conflict: {trim(t(oc), 60)}")
1733
+ notes.append("one VALUES row stands for every row inserted")
1734
+ self.emit(f, m, n, start, sink, sql, "orm", self.ix.table_of(mod) if mod else q.srcs[0]["sql"].strip('"'), "insert",
1735
+ engine, sc, notes, conf, "orm_api", rows)
1736
+ STATS.hit(LIB, 1, test)
1737
+ return
1738
+ self.miss(f, n, f"Repo.{fn} not translated", test)
1739
+
1740
+ def emit_all(self, f, m, n, start, sink, engine, sc, sqls, expr) -> None:
1741
+ seen = set()
1742
+ cap = SETTINGS["max_variants"]
1743
+ k = 0
1744
+ for sql, q, op_name in sqls:
1745
+ if sql in seen:
1746
+ continue
1747
+ seen.add(sql)
1748
+ k += 1
1749
+ if k > cap * 2:
1750
+ break
1751
+ notes = list(q.notes)
1752
+ if q.followed:
1753
+ notes.append("query built in " + ", ".join(dict.fromkeys(q.followed)))
1754
+ conf = "high"
1755
+ if q.runtime or "«" in re.sub(r"(?:=|ANY\(|IN \(|LIMIT|OFFSET|VALUES \(|, |<>|>=|<=|>|<|LIKE|ILIKE)\s*«[^»]*»", "", sql):
1756
+ conf = "medium"
1757
+ if len(sqls) > 1:
1758
+ notes.append(f"{min(len(sqls), cap * 2)} statements for this call")
1759
+ mod = q.root_mod
1760
+ table = self.ix.table_of(mod) if mod is not None else q.srcs[0]["sql"].strip('"')
1761
+ self.emit(f, m, n, start, sink, sql, "orm", table, op_name, engine, sc, notes, conf, "orm_api", expr)
1762
+ STATS.hit(LIB, min(k, cap * 2), f.test)
1763
+
1764
+ def unknown(self, f, m, n, start, sink, engine, sc, node, operation, reason) -> None:
1765
+ self.emit(f, m, n, start, sink, None, "unresolved", "", operation, engine, sc, [reason], "low", "orm_api", node)
1766
+ self.miss(f, n, reason, f.test)
1767
+
1768
+ def preload_query(self, name: str, owner: Mod | None) -> Q | None:
1769
+ e = self.e
1770
+ found = e.assoc_target(name, owner)
1771
+ if found is None:
1772
+ return None
1773
+ om, a = found
1774
+ tm = self.ix.mods.get(a.target)
1775
+ if tm is None or not tm.table:
1776
+ return None
1777
+ q = e.from_mod(tm)
1778
+ ids = mark(f"ids of the loaded {om.name.split('.')[-1]} rows")
1779
+ if a.kind == "belongs_to":
1780
+ q.where.append(("AND", f"s0.{q_ident(a.references)} = ANY({ids})"))
1781
+ elif a.kind == "many_to_many":
1782
+ jt = a.join_through
1783
+ if jt.startswith("@mod:"):
1784
+ jm = self.ix.mods.get(jt[5:])
1785
+ if jm is None or not jm.table:
1786
+ return None
1787
+ jt = self.ix.table_of(jm)
1788
+ keys = a.join_keys or [(underscore(om.name) + "_id", "id"), (underscore(tm.name) + "_id", "id")]
1789
+ q.add_src(q_table(jt), None)
1790
+ q.joins.append(f"INNER JOIN {q_table(jt)} AS s1 ON s0.{q_ident(keys[1][1])} = s1.{q_ident(keys[1][0])}")
1791
+ q.where.append(("AND", f"s1.{q_ident(keys[0][0])} = ANY({ids})"))
1792
+ else:
1793
+ q.where.append(("AND", f"s0.{q_ident(a.fk)} = ANY({ids})"))
1794
+ q.notes.append(f"preload of :{name}" + ("" if owner is not None else ", association found by its name"))
1795
+ return q
1796
+
1797
+ def struct_query(self, node: Node, sc: Scope) -> list[Q]:
1798
+ mod = self.struct_mod(node, sc)
1799
+ if mod is None or not mod.table:
1800
+ return []
1801
+ q = self.e.from_mod(mod)
1802
+ pk = mod.pk or ["id"]
1803
+ q.where.append(("AND", f"s0.{q_ident(pk[0])} = {mark(t(node) + '.' + pk[0])}"))
1804
+ return [q]
1805
+
1806
+ def struct_mod(self, node: Node | None, sc: Scope, depth: int = 0) -> Mod | None:
1807
+ """The schema of a struct or changeset expression: `%Site{}`, `Site.changeset(...)`, a pipe that starts with
1808
+ one, a variable assigned one of those, a `Repo.get(Site, ...)` result."""
1809
+ node = strip(node)
1810
+ if node is None or depth > 6:
1811
+ return None
1812
+ if node.type == "map":
1813
+ for c in kids(node):
1814
+ if c.type == "struct":
1815
+ m = self.ix.mod(sc.m, t(c).lstrip("%"))
1816
+ if m is not None and m.table:
1817
+ return m
1818
+ return None
1819
+ if node.type == "binary_operator" and op(node) == "|>":
1820
+ right = node.child_by_field_name("right")
1821
+ if right is not None and right.type == "call":
1822
+ mn, fn = call_target(right)
1823
+ if mn:
1824
+ m = self.ix.mod(sc.m, mn)
1825
+ if m is not None and m.table:
1826
+ return m
1827
+ elif fn in ("changeset",) and sc.m is not None and sc.m.table:
1828
+ return sc.m
1829
+ return self.struct_mod(node.child_by_field_name("left"), sc, depth + 1)
1830
+ if node.type == "call":
1831
+ mn, fn = call_target(node)
1832
+ pos, _k, _d = call_args(node)
1833
+ if mn and not mn.endswith("Repo"):
1834
+ m = self.ix.mod(sc.m, mn)
1835
+ if m is not None and m.table:
1836
+ return m
1837
+ if mn in ("Ecto.Changeset", "Changeset") and pos:
1838
+ return self.struct_mod(pos[0], sc, depth + 1)
1839
+ elif mn.endswith("Repo") and fn.rstrip("!") in ("get", "get_by", "one", "insert", "update", "reload") and pos:
1840
+ qs = self.e.query(pos[0], sc)
1841
+ if qs and qs[0].root_mod is not None:
1842
+ return qs[0].root_mod
1843
+ return self.struct_mod(pos[0], sc, depth + 1)
1844
+ elif mn == "":
1845
+ if fn in ("change", "cast", "put_change", "put_assoc", "change_struct", "force_change") and pos:
1846
+ return self.struct_mod(pos[0], sc, depth + 1)
1847
+ if sc.m is not None and sc.m.table and fn in sc.m.fns and "changeset" in fn:
1848
+ return sc.m
1849
+ return None
1850
+ if node.type == "identifier":
1851
+ rhs = self.e.assignment(node, t(node), sc)
1852
+ if rhs is not None:
1853
+ return self.struct_mod(rhs, sc, depth + 1)
1854
+ # a parameter named after a schema: `def update_site(site, attrs)` -> Site, when that name is unique
1855
+ nm = t(node)
1856
+ cands = [m for m in self.ix.mods.values() if m.table and underscore(m.name) == nm]
1857
+ if len(cands) == 1:
1858
+ return cands[0]
1859
+ return None
1860
+
1861
+ def literal_keys(self, node: Node | None) -> list[str]:
1862
+ node = strip(node)
1863
+ if node is None or node.type != "map":
1864
+ return []
1865
+ out = []
1866
+ for c in kids(node):
1867
+ if c.type == "map_content":
1868
+ for x in kids(c):
1869
+ if x.type == "keywords":
1870
+ out.extend(k for k, _ in pairs(x))
1871
+ return out
1872
+
1873
+ def changed_fields(self, node: Node | None, mod: Mod, sc: Scope) -> tuple[list[str], str]:
1874
+ """The fields an insert / update writes: the struct literal's keys, the keywords of `change(...)`, the
1875
+ fields `cast` takes in the changeset function called. With none of those, every field (said so)."""
1876
+ found: list[str] = []
1877
+ exact = True
1878
+ stack = [strip(node)]
1879
+ seen = 0
1880
+ while stack and seen < 50:
1881
+ n = stack.pop()
1882
+ seen += 1
1883
+ if n is None:
1884
+ continue
1885
+ if n.type == "map":
1886
+ found.extend(self.literal_keys(n))
1887
+ continue
1888
+ if n.type == "binary_operator" and op(n) == "|>":
1889
+ stack.append(n.child_by_field_name("left"))
1890
+ stack.append(n.child_by_field_name("right"))
1891
+ continue
1892
+ if n.type == "call":
1893
+ mn, fn = call_target(n)
1894
+ pos, kw, _d = call_args(n)
1895
+ if fn in ("change", "put_change", "force_change", "change_struct"):
1896
+ found.extend(kw.keys())
1897
+ if fn in ("put_change", "force_change") and len(pos) >= 2 and pos[-2].type == "atom":
1898
+ found.append(t(pos[-2])[1:])
1899
+ for p in pos[:1]:
1900
+ stack.append(p)
1901
+ continue
1902
+ target = self.ix.mod(sc.m, mn) if mn else sc.m
1903
+ if target is not None and fn in target.casts:
1904
+ found.extend(target.casts[fn])
1905
+ for p in pos[:1]:
1906
+ stack.append(p)
1907
+ continue
1908
+ if target is not None and fn in target.fns:
1909
+ exact = False
1910
+ for p in pos[:1]:
1911
+ stack.append(p)
1912
+ continue
1913
+ if n.type == "identifier":
1914
+ rhs = self.e.assignment(n, t(n), sc)
1915
+ if rhs is not None:
1916
+ stack.append(rhs)
1917
+ fields = [x for x in dict.fromkeys(found) if x in mod.fields or x + "_id" in mod.fields]
1918
+ fields = [x if x in mod.fields else x + "_id" for x in fields]
1919
+ if not fields:
1920
+ return [c for c in mod.fields if c not in mod.pk], "the fields written are decided at run time: every field of the schema is listed"
1921
+ return fields, "exact" if exact else "fields from the changeset functions read; a helper may change more"
1922
+
1923
+ def row_keys(self, rows: Node | None, sc: Scope) -> list[str] | None:
1924
+ rows = strip(rows)
1925
+ if rows is None:
1926
+ return None
1927
+ if rows.type == "identifier":
1928
+ rhs = self.e.assignment(rows, t(rows), sc)
1929
+ return self.row_keys(rhs, sc) if rhs is not None else None
1930
+ if rows.type == "list" and kids(rows):
1931
+ first = kids(rows)[0]
1932
+ if first.type == "map":
1933
+ keys = self.literal_keys(first)
1934
+ return keys or None
1935
+ if first.type == "list" or first.type == "keywords":
1936
+ keys = [k for k, _ in pairs(first)]
1937
+ return keys or None
1938
+ # Enum.map(xs, fn x -> %{a: ..} end) / for x <- xs, do: %{...}
1939
+ for n in walk(rows):
1940
+ if n.type == "map" and n.start_byte > rows.start_byte:
1941
+ keys = self.literal_keys(n)
1942
+ if keys:
1943
+ return keys
1944
+ return None
1945
+
1946
+ def raw_sql(self, node: Node | None, sc: Scope, depth: int = 0) -> tuple[str | None, str]:
1947
+ node = strip(node)
1948
+ if node is None or depth > 4:
1949
+ return None, ""
1950
+ st = string_text(node)
1951
+ if st is not None:
1952
+ return st[0], ("template" if st[1] else "literal")
1953
+ if node.type == "identifier":
1954
+ rhs = self.e.assignment(node, t(node), sc)
1955
+ if rhs is not None:
1956
+ txt, res = self.raw_sql(rhs, sc, depth + 1)
1957
+ return txt, ("constant" if res == "literal" else res)
1958
+ if node.type == "unary_operator" and op(node) == "@" and sc.m is not None:
1959
+ inner = node.child_by_field_name("operand")
1960
+ name = call_target(inner)[1] if inner is not None and inner.type == "call" else t(inner)
1961
+ val = sc.m.attrs.get(name)
1962
+ if val is not None:
1963
+ txt, res = self.raw_sql(val, sc, depth + 1)
1964
+ return txt, ("constant" if res == "literal" else res)
1965
+ if node.type == "binary_operator" and op(node) == "<>":
1966
+ a, ra = self.raw_sql(node.child_by_field_name("left"), sc, depth + 1)
1967
+ b, rb = self.raw_sql(node.child_by_field_name("right"), sc, depth + 1)
1968
+ if a is not None and b is not None:
1969
+ return a + b, ("template" if "template" in (ra, rb) else "constant")
1970
+ return None, ""
1971
+
1972
+
1973
+ # ---------------------------------------------------------------------------------------------- tables
1974
+ MIGRATION_DIR = re.compile(r"(^|/)priv/[^/]*repo[^/]*/migrations/|(^|/)migrations/")
1975
+
1976
+
1977
+ def migration_tables(files: list, schema_tables: dict[str, Table]) -> dict[str, Table]:
1978
+ out: dict[str, Table] = {}
1979
+ for f in sorted(files, key=lambda f: f.rel):
1980
+ if not MIGRATION_DIR.search(f.rel) or b"table(" not in f.src:
1981
+ continue
1982
+ for n in walk(f.root):
1983
+ if n.type != "call":
1984
+ continue
1985
+ mn, fn = call_target(n)
1986
+ if mn or fn not in ("create", "create_if_not_exists", "alter"):
1987
+ continue
1988
+ pos, _kw, do = call_args(n)
1989
+ if not pos or pos[0].type != "call" or call_target(pos[0])[1] != "table":
1990
+ continue
1991
+ tp, tkw, _ = call_args(pos[0])
1992
+ if not tp:
1993
+ continue
1994
+ name = t(tp[0]).lstrip(":").strip('"')
1995
+ if not re.fullmatch(r"\w+", name):
1996
+ continue
1997
+ prefix = string_text(tkw["prefix"])[0] if "prefix" in tkw and string_text(tkw["prefix"]) else ""
1998
+ full = (prefix + "." if prefix else "") + name
1999
+ tbl = out.get(full)
2000
+ if tbl is None:
2001
+ if fn == "alter" and full not in out:
2002
+ tbl = Table(name=full, defined_at=[])
2003
+ else:
2004
+ tbl = Table(name=full, defined_at=[])
2005
+ out[full] = tbl
2006
+ if fn != "alter" and t(tkw.get("primary_key")) != "false":
2007
+ tbl.columns.append({"name": "id", "type": "bigserial"})
2008
+ tbl.primary_key = "id"
2009
+ tbl.defined_at.append(f"{f.rel}:{n.start_point[0] + 1}")
2010
+ if do is None:
2011
+ continue
2012
+ for s in kids(do):
2013
+ if s.type == "identifier" and t(s) == "timestamps":
2014
+ for c in ("inserted_at", "updated_at"):
2015
+ tbl.columns.append({"name": c, "type": "timestamp"})
2016
+ continue
2017
+ if s.type != "call":
2018
+ continue
2019
+ smn, sfn = call_target(s)
2020
+ sp, skw, _ = call_args(s)
2021
+ if sfn == "timestamps":
2022
+ for c in ("inserted_at", "updated_at"):
2023
+ if c in skw and t(skw[c]) == "false":
2024
+ continue
2025
+ cname = t(skw[c]).lstrip(":") if c in skw else c
2026
+ tbl.columns.append({"name": cname, "type": "timestamp"})
2027
+ continue
2028
+ if not sp or sp[0].type != "atom":
2029
+ continue
2030
+ col = t(sp[0])[1:]
2031
+ if sfn in ("add", "add_if_not_exists", "modify"):
2032
+ ty = ""
2033
+ if len(sp) > 1:
2034
+ tyn = sp[1]
2035
+ if tyn.type == "atom":
2036
+ ty = ECTO_TYPES.get(t(tyn)[1:], t(tyn)[1:])
2037
+ elif tyn.type == "call" and call_target(tyn)[1] == "references":
2038
+ ty = "bigint" if "type" not in call_args(tyn)[1] else ECTO_TYPES.get(t(call_args(tyn)[1]["type"])[1:], "bigint")
2039
+ elif tyn.type == "tuple":
2040
+ inner = kids(tyn)[-1] if kids(tyn) else None
2041
+ ty = ECTO_TYPES.get(t(inner).lstrip(":"), "text") + "[]"
2042
+ else:
2043
+ st = string_text(tyn)
2044
+ ty = st[0] if st else "text"
2045
+ if t(skw.get("primary_key")) == "true":
2046
+ tbl.primary_key = col
2047
+ tbl.columns = [c for c in tbl.columns if c["name"] != "id" or col == "id"]
2048
+ existing = [c for c in tbl.columns if c["name"] == col]
2049
+ if existing:
2050
+ existing[0]["type"] = ty or existing[0]["type"]
2051
+ else:
2052
+ tbl.columns.append({"name": col, "type": ty})
2053
+ elif sfn == "remove":
2054
+ tbl.columns = [c for c in tbl.columns if c["name"] != col]
2055
+ return out
2056
+
2057
+
2058
+ def build_tables(ix: Index, files: list) -> list[Table]:
2059
+ by_name: dict[str, Table] = {}
2060
+ for m in ix.mods.values():
2061
+ if not m.table or m.clickhouse_schema:
2062
+ continue
2063
+ name = ix.table_of(m)
2064
+ if name in by_name:
2065
+ continue
2066
+ cols = []
2067
+ for fname, (col, ty) in m.fields.items():
2068
+ base = ty.lstrip(":")
2069
+ sqlty = ECTO_TYPES.get(base, "")
2070
+ if not sqlty:
2071
+ if ty.startswith("{:array"):
2072
+ inner = re.search(r":(\w+)\}?$", ty)
2073
+ sqlty = ECTO_TYPES.get(inner.group(1), "text") + "[]" if inner else "text[]"
2074
+ elif "Enum" in ty:
2075
+ sqlty = "varchar(255)"
2076
+ else:
2077
+ sqlty = "text"
2078
+ if col == "id" and base in ("id", "") and m.pk == ["id"]:
2079
+ sqlty = "bigserial"
2080
+ cols.append({"name": col, "type": sqlty})
2081
+ by_name[name] = Table(name=name, columns=cols, primary_key=", ".join(m.pk),
2082
+ defined_at=[f"{m.f.rel}:{m.schema_line}"], test_only=m.f.test)
2083
+ mig = migration_tables(files, by_name)
2084
+ for name, tbl in mig.items():
2085
+ if name in by_name:
2086
+ # the migrations' column types are SQL; the schema may lack columns it does not map
2087
+ have = {c["name"]: c for c in by_name[name].columns}
2088
+ for c in tbl.columns:
2089
+ if c["name"] in have:
2090
+ if c["type"]:
2091
+ have[c["name"]]["type"] = c["type"]
2092
+ else:
2093
+ by_name[name].columns.append(dict(c))
2094
+ by_name[name].defined_at.extend(tbl.defined_at[:3])
2095
+ elif tbl.columns:
2096
+ by_name[name] = tbl
2097
+ return list(by_name.values())
2098
+
2099
+
2100
+ # ---------------------------------------------------------------------------------------------- entry
2101
+ def run(root: Path, files: list) -> list[RawSite]:
2102
+ STATS.clear()
2103
+ TABLES.clear()
2104
+ ix = Index()
2105
+ for f in files:
2106
+ try:
2107
+ ix.add_file(f)
2108
+ except RecursionError:
2109
+ continue
2110
+ ix.finish()
2111
+ uses_ecto = any(m.table or m.repo_engine is not None for m in ix.mods.values())
2112
+ if not uses_ecto:
2113
+ return []
2114
+ try:
2115
+ TABLES.extend(build_tables(ix, files))
2116
+ except Exception:
2117
+ pass
2118
+ r = Run(ix, files)
2119
+ out: list[RawSite] = []
2120
+ for f in files:
2121
+ if b"Repo" not in f.src:
2122
+ continue
2123
+ try:
2124
+ r._scan_file(f)
2125
+ except RecursionError:
2126
+ continue
2127
+ out.extend(r.out)
2128
+ return out
2129
+
2130
+
2131
+ def summary_extras() -> dict:
2132
+ return STATS.summary()
2133
+
2134
+
2135
+ def tables() -> list:
2136
+ out = list(TABLES)
2137
+ TABLES.clear()
2138
+ return out