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,1248 @@
1
+ """Rust database access through Diesel (translated) and SeaORM (counted).
2
+
3
+ Diesel: the `table!` schema (schema.rs) gives the tables, columns and primary keys; `joinable!` gives the join
4
+ keys. A query DSL chain that reaches an executor (`load`, `first`, `get_result(s)`, `execute`, `load_stream`)
5
+ becomes SQL:
6
+
7
+ users::table.filter(users::id.eq(x)).inner_join(posts::table).select(users::name).order(users::id.desc())
8
+ .limit(10).load(conn)
9
+ -> SELECT users.name FROM users INNER JOIN posts ON posts.user_id = users.id WHERE users.id = ?
10
+ ORDER BY users.id DESC LIMIT 10
11
+
12
+ `diesel::insert_into / update / delete` likewise. A query kept in a variable (`let mut q = t::table.into_boxed()`)
13
+ and extended later is followed inside its function; a step added inside an `if`, `match` or loop is a
14
+ «run-time part». A helper function that returns the start of a query (`Self::joins()`) is read where it is
15
+ defined. A method this reader does not know (a project's own extension trait) is kept as a run-time part.
16
+
17
+ Nothing is invented: a chain whose root table cannot be resolved is counted, with the reason.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import re
23
+ from pathlib import Path
24
+
25
+ from tree_sitter import Node
26
+
27
+ from .base import RawSite, trim
28
+ from .orm_jpa import OrmTable
29
+ from .orm_stats import Stats
30
+
31
+ STATS = Stats()
32
+ TABLES: list = []
33
+
34
+ # With joins and no explicit select, the columns of every joined table are listed up to this many; past it
35
+ # each table is written `t.*`. A setting: `[discover] orm_max_select_columns`.
36
+ DEFAULT_MAX_SELECT_COLUMNS = 400
37
+ MAX_SELECT_COLUMNS = DEFAULT_MAX_SELECT_COLUMNS
38
+ # How many helper functions deep a query's start is followed. A setting: `[discover] orm_helper_depth`.
39
+ DEFAULT_HELPER_DEPTH = 6
40
+ HELPER_DEPTH = DEFAULT_HELPER_DEPTH
41
+
42
+ EXECUTORS = {"load", "first", "get_result", "get_results", "execute", "load_stream", "load_iter"}
43
+ COMPARE = {"eq": "=", "ne": "<>", "gt": ">", "ge": ">=", "lt": "<", "le": "<=", "is_distinct_from": "IS DISTINCT FROM",
44
+ "is_not_distinct_from": "IS NOT DISTINCT FROM", "like": "LIKE", "not_like": "NOT LIKE", "ilike": "ILIKE",
45
+ "not_ilike": "NOT ILIKE", "contains": "@>", "is_contained_by": "<@", "overlaps_with": "&&", "concat": "||",
46
+ "similar_to": "SIMILAR TO"}
47
+ AGG = {"count": "COUNT", "max": "MAX", "min": "MIN", "sum": "SUM", "avg": "AVG", "lower": "LOWER", "upper": "UPPER",
48
+ "coalesce": "COALESCE", "count_distinct": "COUNT(DISTINCT", "length": "LENGTH", "date": "DATE", "any": "ANY",
49
+ "all": "ALL", "array_agg": "ARRAY_AGG", "greatest": "GREATEST", "least": "LEAST", "nullif": "NULLIF"}
50
+ QUERY_STEPS = {"filter", "or_filter", "find", "select", "inner_join", "left_join", "left_outer_join", "order", "order_by",
51
+ "then_order_by", "limit", "offset", "group_by", "having", "distinct", "distinct_on", "count", "into_boxed",
52
+ "for_update", "returning", "values", "set"}
53
+ NOOP_STEPS = {"into_boxed", "nullable", "single_value", "as_query", "assume_not_null", "into_sql", "as_sql", "internal_into_boxed",
54
+ "select_by", "tag", "aliased"}
55
+ TABLE_MACRO = re.compile(r"\btable!\s*\{")
56
+ JOINABLE = re.compile(r"\bjoinable!\s*\(\s*(\w+)\s*->\s*(\w+)\s*\(\s*(\w+)\s*\)\s*\)")
57
+ ALIAS_MACRO = re.compile(r"\balias!\s*\(([^)]*)\)")
58
+
59
+
60
+ def _txt(node: Node | None) -> str:
61
+ return node.text.decode("utf-8", "replace") if node is not None else ""
62
+
63
+
64
+ def _ph(node: Node | str) -> str:
65
+ text = node if isinstance(node, str) else _txt(node)
66
+ return "«" + trim(text, 80).replace("»", ">").replace("«", "<") + "»"
67
+
68
+
69
+ # ---------------------------------------------------------------------------------------------- schema
70
+ class Schema:
71
+ def __init__(self) -> None:
72
+ self.tables: dict[str, dict] = {} # rust module name -> {sql, columns{rust: sql}, pk[], at}
73
+ self.joins: dict[tuple[str, str], str] = {} # (child, parent) -> foreign key column of child
74
+ self.aliases: dict[str, str] = {} # alias name -> table module
75
+
76
+ def read(self, rel: str, text: str) -> None:
77
+ for m in TABLE_MACRO.finditer(text):
78
+ end = _balanced(text, m.end() - 1, "{", "}")
79
+ if end < 0:
80
+ continue
81
+ body = text[m.end():end - 1]
82
+ body = re.sub(r"//[^\n]*", "", body)
83
+ hm = re.search(r"((?:#\[[^\]]*\]\s*)*)(?:(\w+)\s*\.\s*)?(\w+)\s*(?:\(([^)]*)\))?\s*\{", body)
84
+ if hm is None:
85
+ continue
86
+ attrs, schema, name, pk = hm.group(1), hm.group(2), hm.group(3), hm.group(4)
87
+ sql_name = re.search(r'sql_name\s*=\s*"([^"]+)"', attrs or "")
88
+ cols_end = _balanced(body, hm.end() - 1, "{", "}")
89
+ cols_text = body[hm.end():cols_end - 1] if cols_end > 0 else body[hm.end():]
90
+ columns: dict[str, str] = {}
91
+ types: dict[str, str] = {}
92
+ pending = ""
93
+ for cm in re.finditer(r'((?:#\[[^\]]*\]\s*)*)(\w+)\s*->\s*([^,\n]+(?:<[^>]*>)?)', cols_text):
94
+ sn = re.search(r'sql_name\s*=\s*"([^"]+)"', cm.group(1) or "")
95
+ columns[cm.group(2)] = sn.group(1) if sn else cm.group(2)
96
+ types[cm.group(2)] = cm.group(3).strip().rstrip(",")
97
+ if not columns:
98
+ continue
99
+ table_sql = (schema + "." if schema else "") + (sql_name.group(1) if sql_name else name)
100
+ keys = [k.strip() for k in (pk or "id").split(",") if k.strip()]
101
+ self.tables[name] = {"sql": table_sql, "columns": columns, "types": types, "pk": keys,
102
+ "at": f"{rel}:{text.count(chr(10), 0, m.start()) + 1}"}
103
+ for m in JOINABLE.finditer(text):
104
+ self.joins[(m.group(1), m.group(2))] = m.group(3)
105
+ for m in ALIAS_MACRO.finditer(text):
106
+ for part in m.group(1).split(","):
107
+ am = re.match(r"\s*([\w:]+)\s+as\s+(\w+)", part)
108
+ if am:
109
+ self.aliases[am.group(2)] = am.group(1).split("::")[-1]
110
+
111
+ def orm_tables(self) -> list[OrmTable]:
112
+ out = []
113
+ for name, t in self.tables.items():
114
+ pk = [t["columns"].get(k, k) for k in t["pk"]]
115
+ out.append(OrmTable(
116
+ name=t["sql"], columns=[{"name": sql, "type": t["types"].get(rust, "")} for rust, sql in t["columns"].items()],
117
+ defined_at=[t["at"]], primary_key=", ".join(pk),
118
+ indexes=[{"name": "", "columns": pk, "unique": True, "primary": True}], source="diesel"))
119
+ return out
120
+
121
+
122
+ def _balanced(text: str, start: int, open_: str, close: str) -> int:
123
+ depth, i, n = 0, start, len(text)
124
+ while i < n:
125
+ c = text[i]
126
+ if c == open_:
127
+ depth += 1
128
+ elif c == close:
129
+ depth -= 1
130
+ if depth == 0:
131
+ return i + 1
132
+ i += 1
133
+ return -1
134
+
135
+
136
+ # --------------------------------------------------------------------------------------------- queries
137
+ class Skip(Exception):
138
+ pass
139
+
140
+
141
+ class Query:
142
+ def __init__(self) -> None:
143
+ self.kind = "select"
144
+ self.root = "" # table module of the FROM / target
145
+ self.tables: list[str] = [] # table modules in the statement, in join order
146
+ self.from_sql = ""
147
+ self.joins: list[str] = []
148
+ self.where: list[str] = []
149
+ self.select: list[str] = []
150
+ self.order: list[str] = []
151
+ self.group: list[str] = []
152
+ self.having: list[str] = []
153
+ self.limit = ""
154
+ self.offset = ""
155
+ self.distinct = ""
156
+ self.tail: list[str] = []
157
+ self.sets: list[str] = []
158
+ self.columns: list[str] = []
159
+ self.values: list[str] = []
160
+ self.conflict = ""
161
+ self.returning: list[str] = []
162
+ self.count = False
163
+ self.executor = ""
164
+ self.unknown: list[str] = []
165
+ self.runtime = False
166
+ self.last = ""
167
+
168
+
169
+ class File:
170
+ """Use declarations by scope, and the calls of one Rust file."""
171
+
172
+ def __init__(self, rs, diesel: "Diesel"):
173
+ self.rs = rs
174
+ self.d = diesel
175
+ self.uses: dict[int, dict[str, list[str]]] = {} # scope node id (0 = file) -> local name -> path
176
+ self.globs: dict[int, list[list[str]]] = {}
177
+ self._collect(rs.root, 0)
178
+
179
+ def _collect(self, node: Node, scope: int) -> None:
180
+ from .rust import expand_use
181
+ stack = [(node, scope)]
182
+ while stack:
183
+ n, sc = stack.pop()
184
+ for c in n.children:
185
+ if c.type == "use_declaration":
186
+ try:
187
+ found = expand_use(_txt(c))
188
+ except Exception:
189
+ continue
190
+ for local, full in found.items():
191
+ if local == "*":
192
+ self.globs.setdefault(sc, []).extend(g for g in full if g)
193
+ else:
194
+ self.uses.setdefault(sc, {})[local] = full
195
+ elif c.type in ("function_item", "block", "impl_item", "mod_item", "declaration_list", "closure_expression"):
196
+ stack.append((c, c.id if c.type in ("block", "declaration_list") else sc))
197
+ elif c.child_count:
198
+ stack.append((c, sc))
199
+
200
+ def lookup(self, name: str, at: Node) -> list[str] | None:
201
+ n = at
202
+ while n is not None:
203
+ if n.type in ("block", "declaration_list"):
204
+ hit = self.uses.get(n.id, {}).get(name)
205
+ if hit is not None:
206
+ return hit
207
+ n = n.parent
208
+ return self.uses.get(0, {}).get(name)
209
+
210
+ def glob_paths(self, at: Node) -> list[list[str]]:
211
+ out: list[list[str]] = []
212
+ n = at
213
+ while n is not None:
214
+ if n.type in ("block", "declaration_list"):
215
+ out.extend(self.globs.get(n.id, ()))
216
+ n = n.parent
217
+ out.extend(self.globs.get(0, ()))
218
+ return out
219
+
220
+
221
+ class Diesel:
222
+ def __init__(self, ctx, schema: Schema):
223
+ self.ctx = ctx
224
+ self.s = schema
225
+ self.files: dict[str, File] = {}
226
+ self.depth = 0
227
+
228
+ def file(self, rs) -> File:
229
+ f = self.files.get(rs.rel)
230
+ if f is None:
231
+ f = File(rs, self)
232
+ self.files[rs.rel] = f
233
+ return f
234
+
235
+ # ---- paths ------------------------------------------------------------------------------------
236
+ def path(self, f: File, node: Node) -> tuple[str, str] | None:
237
+ """(table module, column or "" for the table itself) for a path expression, or None."""
238
+ text = re.sub(r"\s+", "", _txt(node))
239
+ if not re.fullmatch(r"[A-Za-z_][\w:]*", text):
240
+ return None
241
+ segs = text.split("::")
242
+ if len(segs) == 1 and self._shadowed(node, segs[0]):
243
+ return None # a local variable or parameter with the name of a table
244
+ head = f.lookup(segs[0], node)
245
+ if head is not None:
246
+ segs = head + segs[1:]
247
+ elif segs[0] in ("self", "crate", "super"):
248
+ segs = segs[1:]
249
+ t = self.s.tables
250
+ bare = head is None and len(segs) == 1
251
+ # [.., T, "table"] | [.., T, "dsl", T] | [.., T, col] | [.., T, "dsl"|"columns", col] | [.., T, "star"]
252
+ for i in range(len(segs) - 1, -1, -1):
253
+ if bare:
254
+ break # an unimported bare name: a local variable, unless a glob import has it
255
+ seg = segs[i]
256
+ if seg in t:
257
+ rest = [x for x in segs[i + 1:] if x not in ("dsl", "columns")]
258
+ if not rest or rest == ["table"] or rest == [seg]:
259
+ return seg, ""
260
+ if len(rest) == 1 and rest[0] in t[seg]["columns"]:
261
+ return seg, rest[0]
262
+ if rest in (["star"], ["all_columns"]):
263
+ return seg, "*"
264
+ return None
265
+ if len(segs) == 1:
266
+ name = segs[0]
267
+ if name in self.s.aliases and f.lookup(name, node) is None:
268
+ return None
269
+ for g in f.glob_paths(node):
270
+ gs = [x for x in g if x not in ("dsl", "columns")]
271
+ if gs and gs[-1] in t:
272
+ if name in t[gs[-1]]["columns"]:
273
+ return gs[-1], name
274
+ if name == gs[-1]:
275
+ return gs[-1], ""
276
+ return None
277
+
278
+ @staticmethod
279
+ def _shadowed(node: Node, name: str) -> bool:
280
+ fn = node.parent
281
+ while fn is not None and fn.type != "function_item":
282
+ fn = fn.parent
283
+ if fn is None:
284
+ return False
285
+ before = fn.text[: max(0, node.start_byte - fn.start_byte)].decode("utf-8", "replace")
286
+ n = re.escape(name)
287
+ return bool(re.search(rf"\blet\s+(?:mut\s+)?{n}\b|[(,|]\s*(?:mut\s+)?{n}\s*:|\bfor\s+{n}\s+in\b|\|\s*{n}\s*[,|]|\b(?:Some|Ok)\({n}\)", before))
288
+
289
+ def col(self, table: str, column: str, alias: str = "") -> str:
290
+ t = self.s.tables[table]
291
+ q = alias or t["sql"]
292
+ if column == "*":
293
+ return ", ".join(f"{q}.{c}" for c in t["columns"].values())
294
+ return f"{q}.{t['columns'].get(column, column)}"
295
+
296
+ # ---- expressions ------------------------------------------------------------------------------
297
+ @staticmethod
298
+ def strip(node: Node | None) -> Node | None:
299
+ while node is not None and node.type in ("await_expression", "try_expression", "reference_expression",
300
+ "parenthesized_expression", "unary_expression") and node.named_child_count >= 1:
301
+ if node.type == "unary_expression" and not _txt(node).startswith(("&", "*")):
302
+ break
303
+ node = node.named_children[-1] if node.type == "reference_expression" else node.named_children[0]
304
+ return node
305
+
306
+ @staticmethod
307
+ def call_parts(node: Node) -> tuple[Node | None, str, list[Node]] | None:
308
+ """(receiver or None, function / method name, arguments) of a call expression."""
309
+ if node.type != "call_expression":
310
+ return None
311
+ fn = node.child_by_field_name("function")
312
+ args = node.child_by_field_name("arguments")
313
+ arglist = [a for a in args.named_children if a.type not in ("line_comment", "block_comment")] if args is not None else []
314
+ if fn is not None and fn.type == "generic_function":
315
+ fn = fn.child_by_field_name("function")
316
+ if fn is None:
317
+ return None
318
+ if fn.type == "field_expression":
319
+ return fn.child_by_field_name("value"), _txt(fn.child_by_field_name("field")), arglist
320
+ return None, _txt(fn).split("::")[-1].strip(), arglist
321
+
322
+ def value(self, f: File, node: Node) -> str:
323
+ node = self.strip(node)
324
+ if node is None:
325
+ return "?"
326
+ t = node.type
327
+ if t in ("integer_literal", "float_literal"):
328
+ return re.sub(r"_|[iuf](8|16|32|64|128|size)$", "", _txt(node))
329
+ if t == "boolean_literal":
330
+ return _txt(node).upper()
331
+ if t == "string_literal":
332
+ return "'" + _txt(node)[1:-1].replace("'", "''") + "'"
333
+ e = self.expr(f, node, strict=True)
334
+ if e is None and t == "call_expression" and self._mentions_schema(_txt(node)):
335
+ return _ph(node)
336
+ return e if e is not None else "?"
337
+
338
+ def _mentions_schema(self, text: str) -> bool:
339
+ return any(m.group(1) in self.s.tables for m in re.finditer(r"\b(\w+)::\w+", text))
340
+
341
+ def _unused(self) -> str:
342
+ return "?"
343
+
344
+ def expr(self, f: File, node: Node | None, strict: bool = False, alias: str = "") -> str | None:
345
+ """A column expression, predicate or order item as SQL. With `strict`, None when it is not a Diesel
346
+ expression (a Rust value); otherwise a «run-time part»."""
347
+ node = self.strip(node)
348
+ if node is None:
349
+ return None if strict else "«?»"
350
+ self.depth += 1
351
+ try:
352
+ if self.depth > 40:
353
+ return None if strict else _ph(node)
354
+ t = node.type
355
+ if t in ("identifier", "scoped_identifier"):
356
+ p = self.path(f, node)
357
+ if p is not None:
358
+ return self.s.tables[p[0]]["sql"] if not p[1] else self.col(p[0], p[1], alias)
359
+ last = _txt(node).split("::")[-1]
360
+ if last == "now" and re.fullmatch(r"(?:[\w:]*dsl::)?now", _txt(node)) and not self._shadowed(node, "now"):
361
+ return "CURRENT_TIMESTAMP"
362
+ if last in ("count_star",):
363
+ return "COUNT(*)"
364
+ return None if strict else _ph(node)
365
+ if t == "tuple_expression":
366
+ parts = [self.expr(f, c, strict, alias) for c in node.named_children]
367
+ if any(p is None for p in parts):
368
+ return None
369
+ return ", ".join(parts)
370
+ if t == "binary_expression":
371
+ left, right = node.child_by_field_name("left"), node.child_by_field_name("right")
372
+ op = _txt(node.child_by_field_name("operator"))
373
+ le = self.expr(f, left, True, alias)
374
+ if le is None:
375
+ return None if strict else _ph(node)
376
+ return f"({le} {op} {self.value(f, right)})"
377
+ if t == "macro_invocation" or t == "closure_expression":
378
+ return None if strict else _ph(node)
379
+ if t != "call_expression":
380
+ return None if strict else _ph(node)
381
+ parts = self.call_parts(node)
382
+ if parts is None:
383
+ return None if strict else _ph(node)
384
+ recv, name, args = parts
385
+ if recv is None:
386
+ if name == "not" and args:
387
+ return "NOT (" + (self.expr(f, args[0], False, alias) or "") + ")"
388
+ if name in ("exists", "not_exists") and args:
389
+ sub = self.subquery(f, args[0])
390
+ return ("NOT " if name == "not_exists" else "") + "EXISTS (" + sub + ")"
391
+ if name == "count_star":
392
+ return "COUNT(*)"
393
+ if name == "sql" and args and args[0].type in ("string_literal", "raw_string_literal"):
394
+ from .rust import decode_literal
395
+ raw = decode_literal(_txt(args[0]))
396
+ return raw if raw is not None else _ph(node)
397
+ if name in AGG:
398
+ inner = ", ".join(self.value(f, a) for a in args)
399
+ return AGG[name] + "(" + inner + ")" + (")" if "(" in AGG[name] else "")
400
+ if name == "now" and re.fullmatch(r"(?:[\w:]*dsl::)?now", re.sub(r"\s|\(.*", "", _txt(node))):
401
+ return "CURRENT_TIMESTAMP"
402
+ return None if strict else _ph(node)
403
+ # alias.field(col) / alias.fields((a, b))
404
+ rtext = _txt(recv)
405
+ if name in ("field", "fields") and args:
406
+ aname = rtext.split("::")[-1]
407
+ if aname in self.s.aliases:
408
+ return self.expr(f, args[0], strict, alias=aname)
409
+ left = self.expr(f, recv, True, alias)
410
+ if left is None:
411
+ # a query used as an expression: table.filter(..).select(..) inside eq_any / exists
412
+ if self.chain_root(f, node) is not None:
413
+ return "(" + self.subquery(f, node) + ")"
414
+ return None if strict else _ph(node)
415
+ if name in COMPARE and len(args) == 1:
416
+ return f"{left} {COMPARE[name]} {self.value(f, args[0])}"
417
+ if name in ("eq_any", "ne_all") and len(args) == 1:
418
+ a = self.strip(args[0])
419
+ inner = "?"
420
+ if a is not None and self.chain_root(f, a) is not None:
421
+ inner = self.subquery(f, a)
422
+ elif a is not None and a.type == "identifier":
423
+ decl = self._local(a) # a subquery kept in a local variable
424
+ if decl is not None and self.chain_root(f, decl) is not None:
425
+ inner = self.subquery(f, decl)
426
+ return f"{left} {'IN' if name == 'eq_any' else 'NOT IN'} ({inner})"
427
+ if name in ("is_null", "is_not_null"):
428
+ return f"{left} IS {'NOT ' if name == 'is_not_null' else ''}NULL"
429
+ if name in ("and", "or") and len(args) == 1:
430
+ return f"({left} {name.upper()} {self.expr(f, args[0], False, alias)})"
431
+ if name in ("between", "not_between") and len(args) == 2:
432
+ return f"{left} {'NOT ' if name == 'not_between' else ''}BETWEEN {self.value(f, args[0])} AND {self.value(f, args[1])}"
433
+ if name in ("desc", "asc"):
434
+ return f"{left} {name.upper()}"
435
+ if name in ("nulls_first", "nulls_last"):
436
+ return f"{left} NULLS {'FIRST' if name == 'nulls_first' else 'LAST'}"
437
+ if name in ("nullable", "assume_not_null", "into_sql", "single_value", "aliased", "expression"):
438
+ return left
439
+ if name in ("is_true", "is_false"):
440
+ return f"{left} = {'TRUE' if name == 'is_true' else 'FALSE'}"
441
+ if name in ("retrieve_as_text", "retrieve_as_object", "retrieve_by_path_as_text") and args:
442
+ return f"{left} ->> {self.value(f, args[0])}"
443
+ if name in AGG and not args:
444
+ return f"{AGG[name]}({left})"
445
+ if name == "escape":
446
+ return left
447
+ return None if strict else _ph(node)
448
+ finally:
449
+ self.depth -= 1
450
+
451
+ # ---- chains -----------------------------------------------------------------------------------
452
+ def unroll(self, node: Node) -> tuple[Node, list[tuple[str, list[Node], Node]]]:
453
+ """The root expression of a method chain and its steps, innermost first."""
454
+ steps: list[tuple[str, list[Node], Node]] = []
455
+ cur = self.strip(node)
456
+ while cur is not None and cur.type == "call_expression":
457
+ parts = self.call_parts(cur)
458
+ if parts is None or parts[0] is None:
459
+ break
460
+ steps.append((parts[1], parts[2], cur))
461
+ cur = self.strip(parts[0])
462
+ steps.reverse()
463
+ return cur, steps
464
+
465
+ def chain_root(self, f: File, node: Node) -> tuple | None:
466
+ """What a chain starts from: ("table", module) | ("alias", name) | ("dml", kind, call) | ("fn", node)."""
467
+ root, _steps = self.unroll(node)
468
+ return self.root_of(f, root)
469
+
470
+ def root_of(self, f: File, root: Node | None) -> tuple | None:
471
+ if root is None:
472
+ return None
473
+ if root.type in ("identifier", "scoped_identifier"):
474
+ p = self.path(f, root)
475
+ if p is not None and not p[1]:
476
+ return ("table", p[0])
477
+ name = _txt(root).split("::")[-1]
478
+ if name in self.s.aliases:
479
+ return ("alias", name)
480
+ return None
481
+ if root.type == "call_expression":
482
+ parts = self.call_parts(root)
483
+ if parts is None or parts[0] is not None:
484
+ return None
485
+ name = parts[1]
486
+ fn_text = re.sub(r"\s+", "", _txt(root.child_by_field_name("function")))
487
+ typed = re.search(r"(?:^|::)[A-Z]\w*(?:<[^>]*>)?::\w+$", fn_text) is not None
488
+ if name in ("insert_into", "insert_or_ignore_into", "replace_into", "update", "delete", "select") and parts[2] and not typed:
489
+ return ("dml", name, root)
490
+ return ("fn", root)
491
+ return None
492
+
493
+ def helper(self, f: File, call: Node) -> tuple[File, Node] | None:
494
+ """The tail expression of the function a call names, when it is found in this file or is unique."""
495
+ parts = self.call_parts(call)
496
+ if parts is None:
497
+ return None
498
+ name = parts[1]
499
+ cands = [(f.rs, n) for n in f.rs.fns.get(name, ())]
500
+ if not cands:
501
+ cands = list(self.ctx.fns.get(name, ()))
502
+ if len(cands) > 1:
503
+ # `Crate::by_name(..)`: the one defined in an `impl Crate` block
504
+ fn_text = re.sub(r"\s+", "", _txt(call.child_by_field_name("function")))
505
+ owner = fn_text.split("::")[-2] if fn_text.count("::") >= 1 else ""
506
+ owner = re.sub(r"<.*", "", owner)
507
+ if owner and owner[:1].isupper() and owner != "Self":
508
+ def impl_of(rs_fn):
509
+ n = rs_fn[1].parent
510
+ while n is not None and n.type != "impl_item":
511
+ n = n.parent
512
+ return re.sub(r"<.*", "", _txt(n.child_by_field_name("type"))).split("::")[-1] if n is not None else ""
513
+ cands = [c for c in cands if impl_of(c) == owner]
514
+ if len(cands) != 1:
515
+ return None
516
+ rs, fn = cands[0]
517
+ body = fn.child_by_field_name("body")
518
+ if body is None or not body.named_children:
519
+ return None
520
+ tail = body.named_children[-1]
521
+ if tail.type == "expression_statement":
522
+ inner = tail.named_children[0] if tail.named_children else None
523
+ if inner is None or inner.type != "return_expression":
524
+ return None
525
+ tail = inner.named_children[0] if inner.named_children else None
526
+ if tail is None or tail.type in ("let_declaration",):
527
+ return None
528
+ return self.file(rs), tail
529
+
530
+ def start(self, f: File, q: Query, root: Node, depth: int = 0) -> None:
531
+ r = self.root_of(f, root)
532
+ if r is None and root is not None and root.type == "identifier" and depth < HELPER_DEPTH:
533
+ decl = self._local(root)
534
+ if decl is not None:
535
+ droot, dsteps = self.unroll(decl)
536
+ self.start(f, q, droot, depth + 1)
537
+ for name, args, node in dsteps:
538
+ self.step(f, q, name, args, node, False)
539
+ return
540
+ if r is None:
541
+ raise Skip("the query starts from a value built elsewhere (a parameter, a field or a macro)")
542
+ if r[0] == "table":
543
+ self._from(q, r[1])
544
+ elif r[0] == "alias":
545
+ base = self.s.aliases[r[1]]
546
+ if base not in self.s.tables:
547
+ raise Skip("alias of a table that is not in the schema")
548
+ q.root = base
549
+ q.tables.append(base)
550
+ q.from_sql = f"{self.s.tables[base]['sql']} AS {r[1]}"
551
+ elif r[0] == "dml":
552
+ self._dml(f, q, r[1], r[2])
553
+ else:
554
+ if depth >= HELPER_DEPTH:
555
+ raise Skip("query helper functions nested too deeply")
556
+ bt = self._belonging_to(f, q, r[1])
557
+ if bt:
558
+ return
559
+ h = self.helper(f, r[1])
560
+ if h is None:
561
+ raise Skip("the query starts from a function whose body is not found or not a query")
562
+ hf, tail = h
563
+ hroot, hsteps = self.unroll(tail)
564
+ self.start(hf, q, hroot, depth + 1)
565
+ for name, args, node in hsteps:
566
+ self.step(hf, q, name, args, node, False)
567
+
568
+ def _belonging_to(self, f: File, q: Query, call: Node) -> bool:
569
+ """`Child::belonging_to(&parent)` (diesel associations): the child's rows whose foreign key is the parent's id.
570
+ The key comes from the one `joinable!(child -> parent (fk))` of the child table, or `parent_id` of the parent type."""
571
+ parts = self.call_parts(call)
572
+ if parts is None or parts[1] not in ("belonging_to", "query") or (parts[1] == "belonging_to" and not parts[2]):
573
+ return False
574
+ fn_text = re.sub(r"\s+", "", _txt(call.child_by_field_name("function")))
575
+ model = re.sub(r"<.*", "", fn_text.split("::")[-2]) if "::" in fn_text else ""
576
+ if model == "Self":
577
+ n = call.parent
578
+ while n is not None and n.type != "impl_item":
579
+ n = n.parent
580
+ model = re.sub(r"<.*", "", _txt(n.child_by_field_name("type"))).split("::")[-1] if n is not None else ""
581
+ table = self.d_models().get(model)
582
+ if parts[1] == "query":
583
+ # `Model::query()` (derive(HasQuery)): the model's table, its columns selected
584
+ if table is None or parts[2] or not self._has_query(model):
585
+ return False
586
+ self._from(q, table)
587
+ return True
588
+ if table is None:
589
+ return False
590
+ parent = self._value_model(self.strip(parts[2][0])) if self.strip(parts[2][0]) is not None and self.strip(parts[2][0]).type in ("identifier", "self") else None
591
+ fks = [fk for (child, par), fk in self.s.joins.items() if child == table and (parent is None or par == parent)]
592
+ if len(fks) != 1:
593
+ raise Skip("belonging_to: the foreign key of the association is not known")
594
+ self._from(q, table)
595
+ q.where.append(f"{self.col(table, fks[0])} = {_ph(_txt(parts[2][0]) + '.id')}")
596
+ return True
597
+
598
+ def _has_query(self, model: str) -> bool:
599
+ """The model derives `HasQuery` (diesel 2.3), so `Model::query()` is its table."""
600
+ found = getattr(self, "_hasquery", None)
601
+ if found is None:
602
+ found = set()
603
+ pat = re.compile(rb"derive\([^)]*\bHasQuery\b[^)]*\)\]\s*(?:#\[[^\]]*\]\s*|///[^\n]*\n\s*)*(?:pub(?:\([^)]*\))?\s+)?struct\s+(\w+)", re.S)
604
+ for rs in self.ctx.files.values():
605
+ if b"HasQuery" in rs.src:
606
+ found.update(m.group(1).decode() for m in pat.finditer(rs.src))
607
+ self._hasquery = found
608
+ return model in found
609
+
610
+ def _from(self, q: Query, table: str) -> None:
611
+ q.root = table
612
+ q.tables.append(table)
613
+ q.from_sql = self.s.tables[table]["sql"]
614
+
615
+ def _target(self, f: File, q: Query, node: Node) -> None:
616
+ """The target of update / delete: a table, or a table narrowed with find / filter."""
617
+ root, steps = self.unroll(node)
618
+ r = self.root_of(f, root)
619
+ if r is None and root is not None and root.type == "identifier":
620
+ decl = self._local(root)
621
+ if decl is not None:
622
+ self._target(f, q, decl)
623
+ for name, args, n in steps:
624
+ self.step(f, q, name, args, n, False)
625
+ return
626
+ if r is None and not steps and root is not None and root.type in ("identifier", "self"):
627
+ model = self._value_model(root)
628
+ if model is not None:
629
+ self._from(q, model)
630
+ for key in self.s.tables[model]["pk"]:
631
+ q.where.append(f"{self.col(model, key)} = ?")
632
+ return
633
+ if r is None or r[0] not in ("table",):
634
+ if r is not None and r[0] == "fn":
635
+ h = self.helper(f, r[1])
636
+ if h is not None:
637
+ self._target(h[0], q, h[1])
638
+ for name, args, n in steps:
639
+ self.step(f, q, name, args, n, False)
640
+ return
641
+ raise Skip("update / delete target is not a table of the schema")
642
+ self._from(q, r[1])
643
+ for name, args, n in steps:
644
+ self.step(f, q, name, args, n, False)
645
+
646
+ def _dml(self, f: File, q: Query, name: str, call: Node) -> None:
647
+ args = self.call_parts(call)[2]
648
+ if name in ("insert_into", "insert_or_ignore_into", "replace_into"):
649
+ q.kind = "insert"
650
+ p = self.path(f, self.strip(args[0]))
651
+ if p is None or p[1]:
652
+ raise Skip("insert target is not a table of the schema")
653
+ self._from(q, p[0])
654
+ if name == "insert_or_ignore_into":
655
+ q.conflict = "ON CONFLICT DO NOTHING"
656
+ elif name == "update":
657
+ q.kind = "update"
658
+ self._target(f, q, args[0])
659
+ elif name == "delete":
660
+ q.kind = "delete"
661
+ self._target(f, q, args[0])
662
+ else:
663
+ q.kind = "select"
664
+ q.select = [self.expr(f, args[0]) or "«?»"]
665
+
666
+ def subquery(self, f: File, node: Node) -> str:
667
+ q = Query()
668
+ root, steps = self.unroll(node)
669
+ try:
670
+ self.start(f, q, root)
671
+ for name, args, n in steps:
672
+ self.step(f, q, name, args, n, False)
673
+ except Skip:
674
+ return _ph(node)
675
+ return self.sql(q)
676
+
677
+ def _assignments(self, f: File, q: Query, arg: Node) -> list[tuple[str, str]] | None:
678
+ """`col.eq(v)` or a tuple of them as (column, value) pairs; None for a struct (Insertable / AsChangeset)."""
679
+ arg = self.strip(arg)
680
+ items = arg.named_children if arg is not None and arg.type == "tuple_expression" else [arg]
681
+ out = []
682
+ for it in items:
683
+ it = self.strip(it)
684
+ parts = self.call_parts(it) if it is not None and it.type == "call_expression" else None
685
+ if parts is None or parts[0] is None or parts[1] != "eq" or len(parts[2]) != 1:
686
+ return None
687
+ p = self.path(f, self.strip(parts[0]))
688
+ if p is None or not p[1]:
689
+ return None
690
+ out.append((self.s.tables[p[0]]["columns"].get(p[1], p[1]), self.value(f, parts[2][0])))
691
+ return out or None
692
+
693
+ def step(self, f: File, q: Query, name: str, args: list[Node], node: Node, conditional: bool) -> None:
694
+ if name in EXECUTORS:
695
+ q.executor = name
696
+ if name == "first" and not q.limit:
697
+ q.limit = "1"
698
+ return
699
+ if q.executor:
700
+ return # after the executor: result handling
701
+ if conditional:
702
+ text = _ph(name + "(" + ", ".join(_txt(a) for a in args) + ")")
703
+ if name in ("filter", "or_filter", "find"):
704
+ q.where.append(text)
705
+ elif name in ("order", "order_by", "then_order_by", "then_order"):
706
+ q.order.append(text)
707
+ elif name == "limit":
708
+ q.limit = q.limit or text
709
+ elif name == "offset":
710
+ q.offset = q.offset or text
711
+ elif name in ("inner_join", "left_join", "left_outer_join"):
712
+ q.joins.append(("INNER JOIN " if name == "inner_join" else "LEFT JOIN ") + text + " ON TRUE")
713
+ elif name not in NOOP_STEPS:
714
+ q.tail.append(text)
715
+ return
716
+ if name in NOOP_STEPS:
717
+ return
718
+ if name in ("filter", "or_filter", "having") and args:
719
+ target = q.having if name == "having" else q.where
720
+ piece = self.expr(f, args[0]) or _ph(args[0])
721
+ if name == "or_filter" and target:
722
+ target[:] = ["(" + " AND ".join(target) + " OR " + piece + ")"]
723
+ else:
724
+ target.append(piece)
725
+ elif name == "find" and args:
726
+ pk = self.s.tables[q.root]["pk"]
727
+ a = self.strip(args[0])
728
+ vals = a.named_children if a is not None and a.type == "tuple_expression" else [a]
729
+ for k, key in enumerate(pk):
730
+ q.where.append(f"{self.col(q.root, key)} = " + ("?" if k >= len(vals) or len(vals) != len(pk) else self.value(f, vals[k])))
731
+ elif name in ("inner_join", "left_join", "left_outer_join") and args:
732
+ self._join(f, q, "INNER JOIN" if name == "inner_join" else "LEFT JOIN", args[0])
733
+ elif name in ("select", "returning") and args:
734
+ first = self.strip(args[0])
735
+ items = first.named_children if first is not None and first.type == "tuple_expression" else [args[0]]
736
+ cols = []
737
+ for it in items:
738
+ e = self.expr(f, it, True)
739
+ model = self._model_table(f, it) if e is None else None
740
+ if model is not None:
741
+ e = ", ".join(self.col(model, c) for c in self.s.tables[model]["columns"])
742
+ cols.append(e if e is not None else _ph(it))
743
+ if name == "select":
744
+ q.select = cols
745
+ else:
746
+ q.returning = cols
747
+ elif name in ("order", "order_by") and args:
748
+ q.order = [self.expr(f, args[0]) or _ph(args[0])]
749
+ elif name in ("then_order_by", "then_order") and args:
750
+ q.order.append(self.expr(f, args[0]) or _ph(args[0]))
751
+ elif name == "limit" and args:
752
+ q.limit = self._num(args[0])
753
+ elif name == "offset" and args:
754
+ q.offset = self._num(args[0])
755
+ elif name == "distinct":
756
+ q.distinct = "DISTINCT "
757
+ elif name == "distinct_on" and args:
758
+ q.distinct = "DISTINCT ON (" + (self.expr(f, args[0]) or _ph(args[0])) + ") "
759
+ elif name == "group_by" and args:
760
+ q.group.append(self.expr(f, args[0]) or _ph(args[0]))
761
+ elif name == "count":
762
+ q.count = True
763
+ elif name in ("for_update", "for_share", "for_no_key_update", "for_key_share"):
764
+ q.tail.append(name.upper().replace("_", " "))
765
+ elif name in ("skip_locked", "no_wait"):
766
+ q.tail.append("SKIP LOCKED" if name == "skip_locked" else "NOWAIT")
767
+ elif name == "values" and args:
768
+ pairs = self._assignments(f, q, args[0])
769
+ if pairs is not None:
770
+ q.columns, q.values = [c for c, _ in pairs], [v for _, v in pairs]
771
+ else:
772
+ form = trim(_txt(args[0]).lstrip("&"), 50)
773
+ q.columns, q.values = ["«" + form + " columns»"], ["«" + form + "»"]
774
+ elif name == "default_values":
775
+ q.columns, q.values = [], []
776
+ q.tail.append("DEFAULT VALUES")
777
+ elif name == "set" and args:
778
+ pairs = self._assignments(f, q, args[0])
779
+ form = trim(_txt(args[0]).lstrip("&"), 50)
780
+ sets = [f"{c} = {v}" for c, v in pairs] if pairs is not None else ["«" + form + " columns» = «" + form + "»"]
781
+ if q.conflict and q.kind == "insert":
782
+ q.conflict += " SET " + ", ".join(sets)
783
+ else:
784
+ q.sets.extend(sets)
785
+ elif name == "on_conflict" and args:
786
+ cols = self.expr(f, args[0], True)
787
+ q.conflict = "ON CONFLICT (" + (re.sub(r"\b[\w.]+\.", "", cols) if cols else _ph(args[0])) + ")"
788
+ elif name == "on_conflict_do_nothing":
789
+ q.conflict = "ON CONFLICT DO NOTHING"
790
+ elif name == "do_nothing":
791
+ q.conflict += " DO NOTHING"
792
+ elif name == "do_update":
793
+ q.conflict += " DO UPDATE"
794
+ elif name in ("on",):
795
+ pass
796
+ else:
797
+ q.unknown.append(name)
798
+ q.tail.append(_ph("." + name + "(" + ", ".join(_txt(a) for a in args) + ")"))
799
+
800
+ def _value_model(self, ident: Node) -> str | None:
801
+ """The table of a model value (`&self`, a typed parameter or local): `update(&user)` targets its row."""
802
+ name = _txt(ident)
803
+ tname = ""
804
+ if name == "self":
805
+ n = ident.parent
806
+ while n is not None and n.type != "impl_item":
807
+ n = n.parent
808
+ tname = _txt(n.child_by_field_name("type")) if n is not None else ""
809
+ else:
810
+ fn = ident.parent
811
+ while fn is not None and fn.type != "function_item":
812
+ fn = fn.parent
813
+ if fn is None:
814
+ return None
815
+ before = fn.text[: max(0, ident.start_byte - fn.start_byte)].decode("utf-8", "replace")
816
+ m = None
817
+ for m in re.finditer(r"\b(?:let\s+(?:mut\s+)?)?" + re.escape(name) + r"\s*:\s*&?\s*(?:mut\s+)?(?:'\w+\s+)?([A-Z]\w*)", before):
818
+ pass
819
+ tname = m.group(1) if m else ""
820
+ tname = re.sub(r"<.*", "", tname).split("::")[-1].strip()
821
+ if not tname:
822
+ return None
823
+ table = self.d_models().get(tname)
824
+ if table is None:
825
+ snake = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", tname).lower()
826
+ table = next((c for c in (snake + "s", snake) if c in self.s.tables), None)
827
+ return table
828
+
829
+ def _model_table(self, f: File, arg: Node) -> str | None:
830
+ """`Model::as_select()` / `Self::as_select()`: the table the model struct is declared for."""
831
+ text = re.sub(r"\s+", "", _txt(arg))
832
+ m = re.fullmatch(r"(?:[\w:]+::)?(\w+)::as_(?:select|returning)\(\)", text)
833
+ if m is None:
834
+ return None
835
+ name = m.group(1)
836
+ if name == "Self":
837
+ n = arg.parent
838
+ while n is not None and n.type != "impl_item":
839
+ n = n.parent
840
+ name = re.sub(r"<.*", "", _txt(n.child_by_field_name("type"))).split("::")[-1] if n is not None else ""
841
+ table = self.d_models().get(name)
842
+ if table is None and name:
843
+ snake = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", name).lower()
844
+ table = next((c for c in (snake + "s", snake) if c in self.s.tables), None)
845
+ return table
846
+
847
+ def d_models(self) -> dict[str, str]:
848
+ models = getattr(self, "_models", None)
849
+ if models is None:
850
+ models = {}
851
+ pat = re.compile(rb"table_name\s*=\s*([\w:]+)[^\]]*\)\s*\]\s*(?:#\[[^\]]*\]\s*|///[^\n]*\n\s*)*(?:pub(?:\([^)]*\))?\s+)?struct\s+(\w+)")
852
+ for rs in self.ctx.files.values():
853
+ if b"table_name" not in rs.src:
854
+ continue
855
+ for m in pat.finditer(rs.src):
856
+ table = m.group(1).decode().split("::")[-1]
857
+ if table in self.s.tables:
858
+ models.setdefault(m.group(2).decode(), table)
859
+ self._models = models
860
+ return models
861
+
862
+ def _num(self, node: Node) -> str:
863
+ node = self.strip(node)
864
+ return _txt(node) if node is not None and node.type == "integer_literal" else "?"
865
+
866
+ def _join(self, f: File, q: Query, kw: str, arg: Node, depth: int = 0, against: str = "") -> None:
867
+ arg = self.strip(arg)
868
+ if arg is None:
869
+ return
870
+ root, steps = self.unroll(arg)
871
+ r = self.root_of(f, root)
872
+ if r is not None and r[0] == "fn" and depth < HELPER_DEPTH:
873
+ h = self.helper(f, r[1])
874
+ if h is not None:
875
+ self._join(h[0], q, kw, h[1], depth + 1, against)
876
+ return
877
+ if root is not None and root.type == "identifier" and r is None:
878
+ # a local bound to a join helper: `let j: my_join = my_join(x);`
879
+ decl = self._local(root)
880
+ if decl is not None and depth < HELPER_DEPTH:
881
+ self._join(f, q, kw, decl, depth + 1, against)
882
+ return
883
+ if r is None or r[0] not in ("table", "alias"):
884
+ q.joins.append(f"{kw} {_ph(arg)} ON TRUE")
885
+ q.runtime = True
886
+ return
887
+ table = r[1] if r[0] == "table" else self.s.aliases.get(r[1], "")
888
+ if table not in self.s.tables:
889
+ q.joins.append(f"{kw} {_ph(arg)} ON TRUE")
890
+ return
891
+ sql = self.s.tables[table]["sql"] + (f" AS {r[1]}" if r[0] == "alias" else "")
892
+ on = ""
893
+ nested: list[tuple[str, Node]] = []
894
+ for name, args, _n in steps:
895
+ if name == "on" and args:
896
+ on = self.expr(f, args[0]) or _ph(args[0])
897
+ elif name in ("inner_join", "left_join", "left_outer_join") and args:
898
+ nested.append(("INNER JOIN" if name == "inner_join" else "LEFT JOIN", args[0]))
899
+ if not on:
900
+ on = self._joinable(q, table, against or q.root)
901
+ q.joins.append(f"{kw} {sql} ON {on}")
902
+ q.tables.append(table)
903
+ for nkw, narg in nested:
904
+ self._join(f, q, nkw, narg, depth + 1, table)
905
+
906
+ def _joinable(self, q: Query, table: str, against: str) -> str:
907
+ t = self.s.tables
908
+ for other in ([against] if against in t else []):
909
+ fk = self.s.joins.get((table, other))
910
+ if fk and len(t[other]["pk"]) == 1:
911
+ return f"{self.col(table, fk)} = {self.col(other, t[other]['pk'][0])}"
912
+ fk = self.s.joins.get((other, table))
913
+ if fk and len(t[table]["pk"]) == 1:
914
+ return f"{self.col(other, fk)} = {self.col(table, t[table]['pk'][0])}"
915
+ q.runtime = True
916
+ return "«join condition»"
917
+
918
+ @staticmethod
919
+ def _local(ident: Node) -> Node | None:
920
+ name = _txt(ident)
921
+ n = ident.parent
922
+ while n is not None and n.type != "function_item":
923
+ if n.type == "block":
924
+ for c in n.named_children:
925
+ if c.start_byte >= ident.start_byte:
926
+ break
927
+ if c.type == "let_declaration":
928
+ pat = c.child_by_field_name("pattern")
929
+ if pat is not None and _txt(pat).replace("mut ", "").strip() == name:
930
+ return c.child_by_field_name("value")
931
+ n = n.parent
932
+ return None
933
+
934
+ def sql(self, q: Query) -> str:
935
+ t = self.s.tables
936
+ if q.kind == "select":
937
+ if q.count:
938
+ cols = "COUNT(*)"
939
+ elif q.select:
940
+ cols = ", ".join(q.select)
941
+ else:
942
+ names = [x for x in q.tables if x in t]
943
+ total = sum(len(t[x]["columns"]) for x in names)
944
+ if names and total <= MAX_SELECT_COLUMNS and " AS " not in q.from_sql:
945
+ cols = ", ".join(self.col(x, c) for x in dict.fromkeys(names) for c in t[x]["columns"])
946
+ else:
947
+ cols = ", ".join(f"{t[x]['sql']}.*" for x in dict.fromkeys(names)) or "*"
948
+ out = f"SELECT {q.distinct}{cols}"
949
+ if q.from_sql:
950
+ out += f" FROM {q.from_sql}"
951
+ out += "".join(" " + j for j in q.joins)
952
+ if q.where:
953
+ out += " WHERE " + " AND ".join(q.where)
954
+ if q.group:
955
+ out += " GROUP BY " + ", ".join(q.group)
956
+ if q.having:
957
+ out += " HAVING " + " AND ".join(q.having)
958
+ if q.order:
959
+ out += " ORDER BY " + ", ".join(q.order)
960
+ if q.limit:
961
+ out += " LIMIT " + q.limit
962
+ if q.offset:
963
+ out += " OFFSET " + q.offset
964
+ return out + "".join(" " + x for x in q.tail)
965
+ table = t[q.root]["sql"]
966
+ if q.kind == "insert":
967
+ out = f"INSERT INTO {table}"
968
+ if q.columns:
969
+ out += " (" + ", ".join(q.columns) + ") VALUES (" + ", ".join(q.values) + ")"
970
+ elif "DEFAULT VALUES" in q.tail:
971
+ out += " DEFAULT VALUES"
972
+ else:
973
+ out += " («columns») VALUES («values»)"
974
+ if q.conflict:
975
+ out += " " + q.conflict
976
+ elif q.kind == "update":
977
+ out = f"UPDATE {table} SET " + (", ".join(q.sets) if q.sets else "«columns» = «values»")
978
+ if q.where:
979
+ out += " WHERE " + " AND ".join(q.where)
980
+ else:
981
+ out = f"DELETE FROM {table}"
982
+ if q.where:
983
+ out += " WHERE " + " AND ".join(q.where)
984
+ if q.returning:
985
+ out += " RETURNING " + ", ".join(q.returning)
986
+ elif q.executor in ("get_result", "get_results", "first", "load") and q.kind != "select":
987
+ out += " RETURNING " + ", ".join(self.col(q.root, c) for c in t[q.root]["columns"])
988
+ return out + "".join(" " + x for x in q.tail if x != "DEFAULT VALUES" and q.kind != "select")
989
+
990
+
991
+ def _conditional(node: Node, anchor: Node) -> bool:
992
+ n = node.parent
993
+ while n is not None and n.type != "function_item":
994
+ if n.type in ("if_expression", "match_expression", "match_arm", "for_expression", "while_expression", "loop_expression"):
995
+ if not (n.start_byte <= anchor.start_byte and anchor.end_byte <= n.end_byte):
996
+ return True
997
+ n = n.parent
998
+ return False
999
+
1000
+
1001
+ def _calls(root: Node):
1002
+ stack = [root]
1003
+ while stack:
1004
+ n = stack.pop()
1005
+ if n.type == "call_expression":
1006
+ yield n
1007
+ stack.extend(n.children)
1008
+
1009
+
1010
+ def _outermost(node: Node) -> Node:
1011
+ """The top of the method chain a call belongs to."""
1012
+ cur = node
1013
+ while True:
1014
+ p = cur.parent
1015
+ while p is not None and p.type in ("await_expression", "try_expression", "parenthesized_expression"):
1016
+ cur, p = p, p.parent
1017
+ if p is not None and p.type == "field_expression" and p.child_by_field_name("value") is not None \
1018
+ and p.child_by_field_name("value").id == cur.id:
1019
+ call = p.parent
1020
+ if call is not None and call.type == "generic_function":
1021
+ call = call.parent
1022
+ if call is not None and call.type == "call_expression":
1023
+ cur = call
1024
+ continue
1025
+ return cur
1026
+
1027
+
1028
+ def diesel_sites(ctx, schema: Schema) -> list[RawSite]:
1029
+ out: list[RawSite] = []
1030
+ d = Diesel(ctx, schema)
1031
+ for rs in ctx.files.values():
1032
+ if b"diesel" not in rs.src and not (b"::table" in rs.src or b"insert_into" in rs.src):
1033
+ continue
1034
+ uses_diesel = "diesel" in rs.crates or "diesel_async" in rs.crates or b"diesel" in rs.src
1035
+ f = d.file(rs)
1036
+ seen: set[int] = set()
1037
+ file_test = ctx.is_test_file(rs.rel)
1038
+ for call in _calls(rs.root):
1039
+ top = _outermost(call)
1040
+ if top.id in seen:
1041
+ continue
1042
+ seen.add(top.id)
1043
+ root, steps = d.unroll(top)
1044
+ if not steps and (root is None or root.type != "call_expression"):
1045
+ continue
1046
+ names = [s[0] for s in steps]
1047
+ has_exec = any(n in EXECUTORS for n in names)
1048
+ r = d.root_of(f, root)
1049
+ is_var = root is not None and root.type == "identifier" and r is None
1050
+ if r is None and not is_var:
1051
+ continue
1052
+ if r is not None and r[0] == "fn" and not has_exec:
1053
+ continue
1054
+ if is_var:
1055
+ continue # handled from the `let` that starts the query
1056
+ if r is not None and r[0] in ("table", "alias") and not any(n in QUERY_STEPS or n in EXECUTORS for n in names):
1057
+ continue # a join target or a column expression, not a statement
1058
+ test = file_test or rs.is_test_node(top)
1059
+ # a chain used inside another statement (a subquery, a join target, an update target)
1060
+ holder = top.parent
1061
+ inner = False
1062
+ while holder is not None and holder.type not in ("function_item", "block", "let_declaration", "expression_statement"):
1063
+ if holder.type == "arguments":
1064
+ inner = True
1065
+ break
1066
+ holder = holder.parent
1067
+ if inner and not (r is not None and r[0] == "dml") and not has_exec:
1068
+ continue
1069
+ if r is not None and r[0] == "fn" and (d.call_parts(r[1]) or (None, ""))[1] not in ("belonging_to", "query"):
1070
+ h = d.helper(f, r[1])
1071
+ if h is None or d.chain_root(h[0], h[1]) is None:
1072
+ continue # not a query helper: some other call that ends in .first() / .execute()
1073
+ if r is not None and r[0] == "dml" and r[1] == "select" and not uses_diesel:
1074
+ continue
1075
+ # the query kept in a variable and extended later
1076
+ later: list[tuple[str, list[Node], Node, bool]] = []
1077
+ wrapper = ""
1078
+ let = top.parent
1079
+ while let is not None and let.type in ("await_expression", "try_expression", "parenthesized_expression"):
1080
+ let = let.parent
1081
+ var = ""
1082
+ if not has_exec and let is not None and let.type == "let_declaration":
1083
+ pat = let.child_by_field_name("pattern")
1084
+ var = _txt(pat).replace("mut ", "").strip() if pat is not None else ""
1085
+ if not re.fullmatch(r"[a-z_]\w*", var):
1086
+ var = ""
1087
+ if var:
1088
+ fn = rs._enclosing(top, ("function_item",))
1089
+ names = {var} # the variable, and the variables a wrapper's result is kept in
1090
+ tops: dict[int, Node] = {}
1091
+ if fn is not None:
1092
+ for c2 in _calls(fn):
1093
+ if c2.start_byte > top.end_byte:
1094
+ t2 = _outermost(c2)
1095
+ tops.setdefault(t2.id, t2)
1096
+ for t2 in sorted(tops.values(), key=lambda n: n.start_byte):
1097
+ root2, steps2 = d.unroll(t2)
1098
+ if root2 is None:
1099
+ continue
1100
+ if root2.type == "call_expression":
1101
+ # through a wrapper: paginate(query, ..).load(conn), Commented::new(query).load(conn),
1102
+ # or `let paged = Self::paginate(query, ..).then_order_by(..);` and `paged.load(conn)`
1103
+ wparts = d.call_parts(root2)
1104
+ wargs = [d.strip(a) for a in (wparts[2] if wparts else [])]
1105
+ if not any(a is not None and a.type == "identifier" and _txt(a) in names for a in wargs):
1106
+ continue
1107
+ if wparts is not None and wparts[1] in ("delete", "update", "insert_into", "select", "exists", "not"):
1108
+ continue # the variable is the target or a subquery of another statement
1109
+ executed = any(s[0] in EXECUTORS for s in steps2)
1110
+ holder2 = t2.parent
1111
+ while holder2 is not None and holder2.type in ("await_expression", "try_expression", "parenthesized_expression"):
1112
+ holder2 = holder2.parent
1113
+ kept = ""
1114
+ if not executed and holder2 is not None and holder2.type == "let_declaration":
1115
+ pat2 = holder2.child_by_field_name("pattern")
1116
+ kept = _txt(pat2).replace("mut ", "").strip() if pat2 is not None else ""
1117
+ if not executed and not re.fullmatch(r"[a-z_]\w*", kept or ""):
1118
+ continue
1119
+ wrapper = _txt(root2.child_by_field_name("function"))
1120
+ if kept:
1121
+ names.add(kept)
1122
+ for nm, a, n in steps2:
1123
+ later.append((nm, a, n, False))
1124
+ continue
1125
+ if root2.type != "identifier" or _txt(root2) not in names or not steps2:
1126
+ continue
1127
+ cond = _conditional(t2, top)
1128
+ for nm, a, n in steps2:
1129
+ later.append((nm, a, n, cond and nm not in EXECUTORS))
1130
+ has_exec = any(nm in EXECUTORS for nm, _a, _n, _c in later)
1131
+ if not has_exec:
1132
+ if var:
1133
+ fn = rs._enclosing(top, ("function_item",))
1134
+ after = fn.text[top.end_byte - fn.start_byte:].decode("utf-8", "replace") if fn is not None else ""
1135
+ if re.search(r"\b(?:delete|update|insert_into|select|exists|not_exists|eq_any|ne_all|values|filter|or_filter|"
1136
+ r"inner_join|left_join|union|union_all|any|not)\s*\(\s*&?" + re.escape(var) + r"\b", after):
1137
+ continue # a subquery or a target of another Diesel statement, which is reported
1138
+ tail_of = top.parent
1139
+ while tail_of is not None and tail_of.type in ("return_expression", "expression_statement", "parenthesized_expression"):
1140
+ tail_of = tail_of.parent
1141
+ if tail_of is not None and tail_of.type == "block" and tail_of.parent is not None and tail_of.parent.type == "function_item" \
1142
+ and tail_of.named_children and tail_of.named_children[-1].end_byte >= top.end_byte and not var:
1143
+ continue # a helper that returns the query: counted at the caller that runs it
1144
+ if r is not None and r[0] in ("table", "alias", "dml") and steps and not inner:
1145
+ STATS.seen("diesel", test)
1146
+ STATS.miss("diesel", "query built here and executed elsewhere (returned or passed on)", rs.rel, top.start_point[0] + 1, test)
1147
+ continue
1148
+ STATS.seen("diesel", test)
1149
+ q = Query()
1150
+ try:
1151
+ d.depth = 0
1152
+ d.start(f, q, root)
1153
+ for nm, a, n in steps:
1154
+ d.step(f, q, nm, a, n, False)
1155
+ for nm, a, n, cond in later:
1156
+ d.step(f, q, nm, a, n, cond)
1157
+ sql = d.sql(q)
1158
+ except Skip as exc:
1159
+ STATS.miss("diesel", str(exc), rs.rel, top.start_point[0] + 1, test)
1160
+ continue
1161
+ except (RecursionError, KeyError):
1162
+ STATS.miss("diesel", "expression not understood", rs.rel, top.start_point[0] + 1, test)
1163
+ continue
1164
+ notes = []
1165
+ conf = "high"
1166
+ if q.unknown:
1167
+ notes.append("methods this reader does not know are kept as run-time parts: " + ", ".join(dict.fromkeys(q.unknown)))
1168
+ conf = "medium"
1169
+ if "«" in sql and conf == "high":
1170
+ conf = "medium"
1171
+ if wrapper:
1172
+ notes.append(f"executed through {wrapper}(...), which may add to the statement")
1173
+ conf = "medium" if conf == "high" else conf
1174
+ if q.runtime:
1175
+ notes.append("a join target or join condition is decided elsewhere")
1176
+ conf = "low" if conf != "high" else "medium"
1177
+ s = RawSite(
1178
+ file=rs.rel, line=top.start_point[0] + 1, end_line=top.end_point[0] + 1, language="rust", kind="call",
1179
+ sink="diesel." + (q.executor or "query"), symbol=rs.symbol(top), sql=sql, resolution="orm", expr=trim(_txt(top)),
1180
+ in_loop=rs.in_loop(top), engine_hint="", is_test=test, known_sink=True)
1181
+ s.orm = {"library": "diesel", "model_or_table": schema.tables[q.root]["sql"] if q.root in schema.tables else "",
1182
+ "operation": q.kind if not q.count else "count", "confidence": conf}
1183
+ if notes:
1184
+ s.orm["notes"] = "; ".join(notes)
1185
+ out.append(s)
1186
+ STATS.hit("diesel", 1, test)
1187
+ return out
1188
+
1189
+
1190
+ SEA_ORM_CALL = re.compile(rb"\b(?:Entity|[A-Z]\w*)::(?:find|find_by_id|insert|insert_many|update|update_many|delete|delete_many|delete_by_id)\s*\(")
1191
+
1192
+
1193
+ def count_sea_orm(ctx) -> None:
1194
+ for rs in ctx.files.values():
1195
+ if b"sea_orm" not in rs.src:
1196
+ continue
1197
+ test = ctx.is_test_file(rs.rel)
1198
+ for m in SEA_ORM_CALL.finditer(rs.src):
1199
+ STATS.seen("sea-orm", test)
1200
+ STATS.miss("sea-orm", "SeaORM calls are counted, not translated (no test repository uses them)", rs.rel,
1201
+ rs.src.count(b"\n", 0, m.start()) + 1, test)
1202
+
1203
+
1204
+ def apply_settings(settings: dict | None) -> None:
1205
+ global MAX_SELECT_COLUMNS, HELPER_DEPTH
1206
+ settings = settings or {}
1207
+ MAX_SELECT_COLUMNS = int(settings.get("orm_max_select_columns", DEFAULT_MAX_SELECT_COLUMNS))
1208
+ HELPER_DEPTH = int(settings.get("orm_helper_depth", DEFAULT_HELPER_DEPTH))
1209
+
1210
+
1211
+ def extend(root: Path, ctx, sites: list[RawSite]) -> list[RawSite]:
1212
+ """Called at the end of rust.extract."""
1213
+ STATS.clear()
1214
+ TABLES.clear()
1215
+ schema = Schema()
1216
+ for rs in ctx.files.values():
1217
+ if b"table!" in rs.src or b"joinable!" in rs.src or b"alias!" in rs.src:
1218
+ try:
1219
+ schema.read(rs.rel, rs.src.decode("utf-8", "replace"))
1220
+ except Exception:
1221
+ continue
1222
+ sea_sites: list[RawSite] = []
1223
+ try:
1224
+ from . import orm_rust_seaorm # SeaORM entities and calls, translated
1225
+ sea_sites, sea_tables = orm_rust_seaorm.run(ctx, STATS)
1226
+ TABLES.extend(sea_tables)
1227
+ if not sea_tables:
1228
+ count_sea_orm(ctx)
1229
+ except Exception:
1230
+ pass
1231
+ sites = sites + sea_sites
1232
+ if not schema.tables:
1233
+ return sites
1234
+ TABLES.extend(schema.orm_tables())
1235
+ try:
1236
+ return sites + diesel_sites(ctx, schema)
1237
+ except RecursionError:
1238
+ return sites
1239
+
1240
+
1241
+ def summary_extras() -> dict:
1242
+ return STATS.summary()
1243
+
1244
+
1245
+ def tables() -> list:
1246
+ out = list(TABLES)
1247
+ TABLES.clear()
1248
+ return out