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,734 @@
1
+ """SeaORM (Rust): entity calls translated to SQL by rule.
2
+
3
+ Entities come from the repository's own entity modules: `#[sea_orm(table_name = "users")] pub struct Model { ... }`
4
+ gives the table, its columns (snake case of the field, or `column_name = "..."`) and primary key; the module's file
5
+ name is the module (`users::Entity`, `users::Column::Email`, `users::ActiveModel`), and `pub use
6
+ super::users::Entity as User;` re-exports (a prelude) add names.
7
+
8
+ model::UserAttributes::find()
9
+ .filter(model::UserAttributesColumn::UserId.eq(user_id))
10
+ .order_by_asc(model::UserAttributesColumn::AttributeName)
11
+ .all(&self.sql_pool)
12
+ -> SELECT "user_attributes"."user_id", ... FROM "user_attributes" WHERE "user_attributes"."user_id" = «user_id»
13
+ ORDER BY "user_attributes"."attribute_name" ASC
14
+
15
+ `Entity::insert / insert_many / update / update_many / delete_many / delete_by_id`, and `ActiveModel` `.insert /
16
+ .update / .save / .delete(db)` on a value built in the same function, likewise. A condition this reader cannot read
17
+ (a `Cond` built by a helper from a request filter) is a «run-time part» in the WHERE clause; a query kept in a
18
+ variable and extended under a condition gets that step as a run-time part. A chain whose entity cannot be told is
19
+ counted with the reason, no SQL.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import re
25
+
26
+ from tree_sitter import Node
27
+
28
+ from .base import RawSite, trim
29
+ from .orm_jpa import OrmTable
30
+
31
+ LIB = "sea-orm"
32
+ EXECUTORS = {"all", "one", "exec", "exec_with_returning", "exec_without_returning", "count", "stream", "paginate",
33
+ "into_tuple_all", "exists"}
34
+ AM_EXECUTORS = {"insert", "update", "save", "delete"}
35
+ COMPARE = {"eq": "=", "ne": "<>", "gt": ">", "gte": ">=", "lt": "<", "lte": "<=", "like": "LIKE", "not_like": "NOT LIKE"}
36
+ NOOP = {"into_model", "into_json", "into_tuple", "into_values", "select_only", "distinct", "into_partial_model",
37
+ "lock_exclusive", "lock_shared", "do_nothing", "to_owned", "clone", "into_query"}
38
+
39
+
40
+ def _txt(n: Node | None) -> str:
41
+ return n.text.decode("utf-8", "replace") if n is not None else ""
42
+
43
+
44
+ def _ph(text: str) -> str:
45
+ return "«" + trim(" ".join(text.split()), 80).replace("»", ">").replace("«", "<") + "»"
46
+
47
+
48
+ def snake(name: str) -> str:
49
+ return re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", name).lower()
50
+
51
+
52
+ def qi(name: str) -> str:
53
+ return '"' + name.replace('"', '""') + '"'
54
+
55
+
56
+ class Entity:
57
+ def __init__(self, module: str, table: str, at: str):
58
+ self.module, self.table, self.at = module, table, at
59
+ self.columns: dict[str, str] = {} # field (snake) -> column
60
+ self.types: dict[str, str] = {}
61
+ self.pk: list[str] = []
62
+ self.relations: dict[str, tuple[str, str, str]] = {} # Relation variant -> (other module, from col, to col)
63
+
64
+
65
+ MODEL_RX = re.compile(r'#\[sea_orm\(([^\]]*?)table_name\s*=\s*"([^"]+)"([^\]]*)\)\]\s*(?:#\[[^\]]*\]\s*)*pub\s+struct\s+Model\s*\{', re.S)
66
+ FIELD_RX = re.compile(r'((?:#\[[^\]]*\]\s*)*)pub\s+(\w+)\s*:\s*([^,\n]+)')
67
+ REEXPORT_RX = re.compile(r"\bpub\s+use\s+(?:(?:super|crate|self)::)*(?:[\w:]*::)?(\w+)::(Entity|Column|ActiveModel|Model)\s+as\s+(\w+)\s*;")
68
+ RELATION_RX = re.compile(r'#\[sea_orm\(\s*(?:belongs_to|has_one|has_many)\s*=\s*"(?:super|crate)::(?:[\w:]*::)?(\w+)::Entity"'
69
+ r'(?:\s*,\s*from\s*=\s*"Column::(\w+)"\s*,\s*to\s*=\s*"(?:super|crate)::(?:[\w:]*::)?\w+::Column::(\w+)")?[^\]]*\)\]\s*(\w+)', re.S)
70
+
71
+
72
+ class Model:
73
+ def __init__(self):
74
+ self.entities: dict[str, Entity] = {} # module name -> entity
75
+ self.names: dict[str, tuple[str, str]] = {} # re-exported name -> (module, kind)
76
+
77
+ def read(self, rel: str, text: str) -> None:
78
+ for m in MODEL_RX.finditer(text):
79
+ module = rel.rsplit("/", 1)[-1][:-3]
80
+ if module in ("mod", "lib"):
81
+ module = rel.rsplit("/", 2)[-2] if rel.count("/") else module
82
+ ent = Entity(module, m.group(2), f"{rel}:{text.count(chr(10), 0, m.start()) + 1}")
83
+ body_start = m.end()
84
+ depth, i = 1, body_start
85
+ while i < len(text) and depth:
86
+ depth += {"{": 1, "}": -1}.get(text[i], 0)
87
+ i += 1
88
+ body = text[body_start:i - 1]
89
+ for fm in FIELD_RX.finditer(body):
90
+ attrs, field, ty = fm.group(1), fm.group(2), fm.group(3).strip()
91
+ cn = re.search(r'column_name\s*=\s*"([^"]+)"', attrs)
92
+ if re.search(r"\bignore\b", attrs):
93
+ continue
94
+ ent.columns[field] = cn.group(1) if cn else field
95
+ ent.types[field] = ty
96
+ if "primary_key" in attrs:
97
+ ent.pk.append(field)
98
+ for rm in RELATION_RX.finditer(text):
99
+ ent.relations[rm.group(4)] = (rm.group(1), snake(rm.group(2) or ""), snake(rm.group(3) or ""))
100
+ self.entities[module] = ent
101
+ for m in REEXPORT_RX.finditer(text):
102
+ self.names[m.group(3)] = (m.group(1), m.group(2))
103
+
104
+ def resolve(self, path: str, here: str = "") -> tuple[Entity, str] | None:
105
+ """`model::User` / `users::Entity` / `Entity` (inside users.rs) / `UserColumn` -> (entity, kind)."""
106
+ parts = [p for p in re.sub(r"<[^>]*>", "", path).split("::") if p]
107
+ if not parts:
108
+ return None
109
+ last = parts[-1]
110
+ if last in self.names:
111
+ mod, kind = self.names[last]
112
+ if mod in self.entities:
113
+ return self.entities[mod], kind
114
+ if last in ("Entity", "Column", "ActiveModel", "Model"):
115
+ mod = parts[-2] if len(parts) >= 2 else here
116
+ if mod in ("Self", "self", "super", "crate") and len(parts) == 2:
117
+ mod = here
118
+ if mod in self.entities:
119
+ return self.entities[mod], last
120
+ return None
121
+
122
+ def orm_tables(self) -> list[OrmTable]:
123
+ out = []
124
+ for e in self.entities.values():
125
+ pk = [e.columns.get(k, k) for k in e.pk]
126
+ out.append(OrmTable(name=e.table, columns=[{"name": c, "type": _sql_type(e.types.get(f, ""))} for f, c in e.columns.items()],
127
+ defined_at=[e.at], primary_key=", ".join(pk),
128
+ indexes=[{"name": "", "columns": pk, "unique": True, "primary": True}] if pk else [],
129
+ source="sea-orm"))
130
+ return out
131
+
132
+
133
+ def _sql_type(rust: str) -> str:
134
+ r = rust.replace("Option<", "").rstrip(">").strip()
135
+ if re.search(r"\b(i64|u64)\b", r):
136
+ return "bigint"
137
+ if re.search(r"\b(i32|u32|i16|u16|i8|u8)\b", r):
138
+ return "integer"
139
+ if re.search(r"\bf(32|64)\b|Decimal", r):
140
+ return "double precision"
141
+ if r == "bool":
142
+ return "boolean"
143
+ if "Vec<u8>" in rust:
144
+ return "bytea"
145
+ if "DateTime" in r:
146
+ return "timestamp"
147
+ if "Date" in r:
148
+ return "date"
149
+ if "Uuid" in r:
150
+ return "uuid"
151
+ if "Json" in r:
152
+ return "jsonb"
153
+ return "text"
154
+
155
+
156
+ class Skip(Exception):
157
+ pass
158
+
159
+
160
+ class Q:
161
+ def __init__(self, ent: Entity, kind: str):
162
+ self.ent, self.kind = ent, kind
163
+ self.where: list[str] = []
164
+ self.order: list[str] = []
165
+ self.select: list[str] | None = None
166
+ self.group: list[str] = []
167
+ self.joins: list[str] = []
168
+ self.join_cols: list[str] = []
169
+ self.limit = self.offset = None
170
+ self.set: list[str] = []
171
+ self.values: list[str] | None = None
172
+ self.count = False
173
+ self.tail: list[str] = []
174
+ self.notes: list[str] = []
175
+ self.runtime = 0
176
+ self.executor = ""
177
+
178
+
179
+ def strip(n: Node | None) -> Node | None:
180
+ while n is not None and n.type in ("await_expression", "try_expression", "parenthesized_expression", "reference_expression"):
181
+ kids = [c for c in n.named_children if c.type != "mutable_specifier"]
182
+ if not kids:
183
+ break
184
+ n = kids[0]
185
+ return n
186
+
187
+
188
+ def call_parts(n: Node) -> tuple[Node | None, str, list[Node], str] | None:
189
+ """(receiver or None, method name, args, path text of a path call)."""
190
+ if n is None or n.type != "call_expression":
191
+ return None
192
+ fn = n.child_by_field_name("function")
193
+ args_n = n.child_by_field_name("arguments")
194
+ args = [a for a in (args_n.named_children if args_n is not None else []) if a.type != "comment"]
195
+ if fn is None:
196
+ return None
197
+ if fn.type == "generic_function":
198
+ fn = fn.child_by_field_name("function") or fn
199
+ if fn.type == "field_expression":
200
+ return fn.child_by_field_name("value"), _txt(fn.child_by_field_name("field")), args, ""
201
+ if fn.type in ("scoped_identifier", "identifier"):
202
+ text = re.sub(r"\s+", "", _txt(fn))
203
+ return None, text.split("::")[-1], args, text
204
+ return None
205
+
206
+
207
+ def unroll(node: Node) -> tuple[Node | None, list[tuple[str, list[Node], Node]]]:
208
+ steps = []
209
+ cur = strip(node)
210
+ while cur is not None and cur.type == "call_expression":
211
+ parts = call_parts(cur)
212
+ if parts is None or parts[0] is None:
213
+ break
214
+ steps.append((parts[1], parts[2], cur))
215
+ cur = strip(parts[0])
216
+ steps.reverse()
217
+ return cur, steps
218
+
219
+
220
+ def outermost(node: Node) -> Node:
221
+ cur = node
222
+ while True:
223
+ p = cur.parent
224
+ while p is not None and p.type in ("await_expression", "try_expression", "parenthesized_expression"):
225
+ cur, p = p, p.parent
226
+ if p is not None and p.type == "field_expression" and p.child_by_field_name("value") is not None \
227
+ and p.child_by_field_name("value").id == cur.id:
228
+ call = p.parent
229
+ if call is not None and call.type == "generic_function":
230
+ call = call.parent
231
+ if call is not None and call.type == "call_expression":
232
+ cur = call
233
+ continue
234
+ return cur
235
+
236
+
237
+ def conditional(node: Node, anchor: Node) -> bool:
238
+ n = node.parent
239
+ while n is not None and n.type != "function_item":
240
+ if n.type in ("if_expression", "match_expression", "match_arm", "for_expression", "while_expression", "loop_expression",
241
+ "closure_expression"):
242
+ if not (n.start_byte <= anchor.start_byte and anchor.end_byte <= n.end_byte):
243
+ return True
244
+ n = n.parent
245
+ return False
246
+
247
+
248
+ class SeaOrm:
249
+ def __init__(self, ctx, model: Model, stats):
250
+ self.ctx, self.m, self.stats = ctx, model, stats
251
+
252
+ def here(self, rs) -> str:
253
+ return rs.rel.rsplit("/", 1)[-1][:-3]
254
+
255
+ # ---- expressions
256
+ def column(self, rs, node: Node | None) -> tuple[Entity, str] | None:
257
+ n = strip(node)
258
+ if n is None:
259
+ return None
260
+ text = re.sub(r"\s+", "", _txt(n))
261
+ if n.type == "scoped_identifier":
262
+ base, _, variant = text.rpartition("::")
263
+ got = self.m.resolve(base, self.here(rs))
264
+ if got is not None and got[1] == "Column":
265
+ ent = got[0]
266
+ field = snake(variant)
267
+ return ent, ent.columns.get(field, field)
268
+ return None
269
+
270
+ def colref(self, rs, node: Node | None, q: Q) -> str | None:
271
+ got = self.column(rs, node)
272
+ if got is None:
273
+ return None
274
+ ent, col = got
275
+ return f"{qi(ent.table)}.{qi(col)}"
276
+
277
+ def value(self, node: Node | None) -> str:
278
+ n = strip(node)
279
+ if n is None:
280
+ return "NULL"
281
+ if n.type in ("integer_literal", "float_literal"):
282
+ return re.sub(r"_|[iuf](8|16|32|64|128|size)$", "", _txt(n))
283
+ if n.type == "boolean_literal":
284
+ return _txt(n).upper()
285
+ if n.type == "string_literal":
286
+ inner = "".join(_txt(c) for c in n.named_children if c.type == "string_content")
287
+ return "'" + inner.replace("'", "''") + "'"
288
+ return _ph(_txt(n))
289
+
290
+ def cond(self, rs, node: Node | None, q: Q, depth: int = 0) -> str:
291
+ n = strip(node)
292
+ if n is None or depth > 30:
293
+ return _ph(_txt(node))
294
+ if n.type == "call_expression":
295
+ parts = call_parts(n)
296
+ if parts is not None:
297
+ recv, name, args, path = parts
298
+ if recv is not None:
299
+ left = self.colref(rs, recv, q)
300
+ if left is not None:
301
+ if name in COMPARE and args:
302
+ return f"{left} {COMPARE[name]} {self.value(args[0])}"
303
+ if name in ("is_in", "is_not_in") and args:
304
+ return f"{left} {'NOT IN' if name == 'is_not_in' else 'IN'} ({self.value(args[0])})"
305
+ if name in ("is_null", "is_not_null"):
306
+ return f"{left} IS {'NOT ' if name == 'is_not_null' else ''}NULL"
307
+ if name in ("contains", "starts_with", "ends_with") and args:
308
+ return f"{left} LIKE {self.value(args[0])}"
309
+ if name in ("between", "not_between") and len(args) == 2:
310
+ return f"{left} {'NOT ' if name == 'not_between' else ''}BETWEEN {self.value(args[0])} AND {self.value(args[1])}"
311
+ if name in ("in_subquery", "not_in_subquery") and args:
312
+ sub = self.subquery(rs, args[0])
313
+ return f"{left} {'NOT IN' if name == 'not_in_subquery' else 'IN'} ({sub})"
314
+ # Cond::all().add(a).add(b)
315
+ root, steps = unroll(n)
316
+ rp = call_parts(root) if root is not None else None
317
+ if rp is not None and rp[0] is None and rp[3] in ("Cond::all", "Condition::all", "Cond::any", "Condition::any"):
318
+ joiner = " AND " if rp[3].endswith("all") else " OR "
319
+ items = []
320
+ for nm, a, _n in steps:
321
+ if nm in ("add", "add_option") and a:
322
+ items.append("(" + self.cond(rs, a[0], q, depth + 1) + ")")
323
+ elif nm == "not":
324
+ items = ["NOT (" + joiner.join(items) + ")"] if items else items
325
+ else:
326
+ items.append(_ph(nm))
327
+ q.runtime += 1
328
+ return joiner.join(items) if items else "TRUE"
329
+ if name in ("and", "or") and args:
330
+ return f"({self.cond(rs, recv, q, depth + 1)}) {name.upper()} ({self.cond(rs, args[0], q, depth + 1)})"
331
+ if name == "not" and not args:
332
+ return f"NOT ({self.cond(rs, recv, q, depth + 1)})"
333
+ q.runtime += 1
334
+ return _ph(_txt(n))
335
+
336
+ def subquery(self, rs, node: Node) -> str:
337
+ root, steps = unroll(strip(node))
338
+ q = self.start(rs, root)
339
+ if q is None:
340
+ return _ph(_txt(node))
341
+ for nm, a, n in steps:
342
+ self.step(rs, q, nm, a, n, False)
343
+ return self.sql(q)
344
+
345
+ # ---- chains
346
+ def start(self, rs, root: Node | None) -> Q | None:
347
+ parts = call_parts(root) if root is not None else None
348
+ if parts is None or parts[0] is not None or "::" not in parts[3]:
349
+ return None
350
+ base, _, fn = parts[3].rpartition("::")
351
+ got = self.m.resolve(base, self.here(rs))
352
+ if got is None or got[1] != "Entity":
353
+ return None
354
+ ent = got[0]
355
+ args = parts[2]
356
+ if fn == "find":
357
+ return Q(ent, "select")
358
+ if fn == "find_by_id":
359
+ q = Q(ent, "select")
360
+ self._by_id(q, args)
361
+ return q
362
+ if fn in ("insert", "insert_many"):
363
+ q = Q(ent, "insert")
364
+ if args:
365
+ q.values = self.am_fields(rs, args[0], root, many=fn == "insert_many")
366
+ return q
367
+ if fn == "update":
368
+ q = Q(ent, "update")
369
+ fields = self.am_fields(rs, args[0], root) if args else None
370
+ q.set = [f"{qi(ent.columns.get(c, c))} = {_ph(c)}" for c in (fields or []) if c not in ent.pk]
371
+ if not q.set:
372
+ q.set = [f"{qi(c)} = {_ph(f)}" for f, c in ent.columns.items() if f not in ent.pk]
373
+ q.notes.append("the columns set are decided at run time: every column of the model is listed")
374
+ for k in ent.pk:
375
+ q.where.append(f"{qi(ent.table)}.{qi(ent.columns.get(k, k))} = {_ph(k)}")
376
+ return q
377
+ if fn == "update_many":
378
+ return Q(ent, "update")
379
+ if fn in ("delete_many",):
380
+ return Q(ent, "delete")
381
+ if fn in ("delete_by_id",):
382
+ q = Q(ent, "delete")
383
+ self._by_id(q, args)
384
+ return q
385
+ if fn == "delete":
386
+ q = Q(ent, "delete")
387
+ for k in ent.pk:
388
+ q.where.append(f"{qi(ent.table)}.{qi(ent.columns.get(k, k))} = {_ph(k)}")
389
+ return q
390
+ return None
391
+
392
+ def _by_id(self, q: Q, args: list[Node]) -> None:
393
+ ent = q.ent
394
+ if not ent.pk:
395
+ raise Skip("entity without a primary key")
396
+ a = strip(args[0]) if args else None
397
+ vals = [c for c in a.named_children] if a is not None and a.type == "tuple_expression" and len(ent.pk) > 1 else [a]
398
+ for i, k in enumerate(ent.pk):
399
+ v = vals[i] if i < len(vals) else None
400
+ q.where.append(f"{qi(ent.table)}.{qi(ent.columns.get(k, k))} = {self.value(v) if v is not None else _ph(k)}")
401
+
402
+ def am_fields(self, rs, node: Node, at: Node, many: bool = False) -> list[str] | None:
403
+ """The fields an ActiveModel literal sets (`Set(..)` / `ActiveValue::Set(..)`), following a variable."""
404
+ n = strip(node)
405
+ depth = 0
406
+ while n is not None and n.type == "identifier" and depth < 4:
407
+ n = self.let_value(rs, _txt(n), at)
408
+ depth += 1
409
+ if n is None:
410
+ return None
411
+ lit = None
412
+ for x in self._walk(n):
413
+ if x.type == "struct_expression" and _txt(x.child_by_field_name("name")).endswith("ActiveModel"):
414
+ lit = x
415
+ break
416
+ if lit is None:
417
+ return None
418
+ body = lit.child_by_field_name("body")
419
+ out = []
420
+ for c in (body.named_children if body is not None else []):
421
+ if c.type == "field_initializer":
422
+ name = _txt(c.child_by_field_name("field"))
423
+ val = _txt(c.child_by_field_name("value"))
424
+ if "NotSet" in val:
425
+ continue
426
+ out.append(name)
427
+ elif c.type == "shorthand_field_initializer":
428
+ out.append(_txt(c))
429
+ return out or None
430
+
431
+ @staticmethod
432
+ def _walk(n: Node):
433
+ stack = [n]
434
+ while stack:
435
+ x = stack.pop()
436
+ yield x
437
+ stack.extend(reversed(x.children))
438
+
439
+ def let_value(self, rs, name: str, at: Node) -> Node | None:
440
+ fn = rs._enclosing(at, ("function_item",))
441
+ if fn is None:
442
+ return None
443
+ best = None
444
+ for x in self._walk(fn):
445
+ if x.start_byte >= at.start_byte:
446
+ break
447
+ if x.type == "let_declaration":
448
+ pat = x.child_by_field_name("pattern")
449
+ if pat is not None and _txt(pat).replace("mut ", "").strip() == name:
450
+ best = x.child_by_field_name("value")
451
+ return best
452
+
453
+ def step(self, rs, q: Q, name: str, args: list[Node], node: Node, cond: bool) -> None:
454
+ ent = q.ent
455
+ if name in ("filter", "having"):
456
+ c = self.cond(rs, args[0], q) if args else "TRUE"
457
+ if cond:
458
+ c = _ph(_txt(node)) if "«" not in c else c
459
+ q.runtime += 1
460
+ q.notes.append("a condition added under an if/match is a run-time part")
461
+ q.where.append(c)
462
+ elif name in ("order_by_asc", "order_by_desc", "order_by"):
463
+ col = self.colref(rs, args[0], q) if args else None
464
+ if col is None:
465
+ col = _ph(_txt(args[0]) if args else "order")
466
+ q.runtime += 1
467
+ d = " DESC" if name == "order_by_desc" or (name == "order_by" and len(args) > 1 and "Desc" in _txt(args[1])) else " ASC"
468
+ q.order.append(col + d)
469
+ elif name in ("limit", "offset"):
470
+ v = self.value(args[0]) if args else "NULL"
471
+ setattr(q, name, v)
472
+ elif name in ("column", "columns", "column_as", "expr", "expr_as"):
473
+ q.select = q.select or []
474
+ for a in args[:1]:
475
+ cols = [a] if strip(a) is None or strip(a).type != "array_expression" else strip(a).named_children
476
+ for c in cols:
477
+ cr = self.colref(rs, c, q)
478
+ q.select.append(cr if cr is not None else _ph(_txt(c)))
479
+ elif name == "group_by":
480
+ cr = self.colref(rs, args[0], q) if args else None
481
+ q.group.append(cr or _ph(_txt(args[0]) if args else "group"))
482
+ elif name in ("find_also_related", "find_with_related", "inner_join", "left_join", "reverse_join"):
483
+ other = self.m.resolve(_txt(args[0]), self.here(rs)) if args else None
484
+ if other is None:
485
+ raise Skip("joined entity not known")
486
+ oe = other[0]
487
+ on = self.join_on(ent, oe)
488
+ kind = "INNER JOIN" if name == "inner_join" else "LEFT JOIN"
489
+ q.joins.append(f"{kind} {qi(oe.table)} ON {on}")
490
+ if name in ("find_also_related", "find_with_related"):
491
+ q.join_cols.extend(f"{qi(oe.table)}.{qi(c)}" for c in oe.columns.values())
492
+ elif name in ("find_also_linked", "find_with_linked"):
493
+ q.joins.append(f"LEFT JOIN {_ph(_txt(args[0]) if args else 'linked')} ON TRUE")
494
+ q.runtime += 1
495
+ q.notes.append("a Linked chain of joins is not written out")
496
+ elif name in ("col_expr",) and len(args) >= 2:
497
+ cr = self.column(rs, args[0])
498
+ q.set.append(f"{qi(cr[1]) if cr else _ph(_txt(args[0]))} = {self.value(args[1])}")
499
+ elif name == "set" and args:
500
+ fields = self.am_fields(rs, args[0], node) or []
501
+ q.set.extend(f"{qi(ent.columns.get(c, c))} = {_ph(c)}" for c in fields)
502
+ elif name == "on_conflict" and args:
503
+ q.tail.append("ON CONFLICT " + _ph(_txt(args[0])))
504
+ q.notes.append("ON CONFLICT clause built by OnConflict")
505
+ elif name == "paginate":
506
+ q.executor = name
507
+ q.limit = self.value(args[1]) if len(args) > 1 else _ph("page size")
508
+ q.offset = _ph("page * page size")
509
+ elif name == "count":
510
+ q.count = True
511
+ q.executor = name
512
+ elif name in EXECUTORS:
513
+ q.executor = name
514
+ elif name in NOOP:
515
+ pass
516
+ elif name in ("filter_by_id",):
517
+ self._by_id(q, args)
518
+ else:
519
+ q.notes.append(f".{name}(...) is not read")
520
+ q.runtime += 1
521
+
522
+ def join_on(self, a: Entity, b: Entity) -> str:
523
+ for ra, rb, swap in ((a, b, False), (b, a, True)):
524
+ for _v, (mod, frm, to) in ra.relations.items():
525
+ if mod == rb.module and frm and to:
526
+ return f"{qi(ra.table)}.{qi(ra.columns.get(frm, frm))} = {qi(rb.table)}.{qi(rb.columns.get(to, to))}"
527
+ return _ph(f"{a.module} to {b.module} relation")
528
+
529
+ def sql(self, q: Q) -> str:
530
+ e = q.ent
531
+ t = qi(e.table)
532
+ where = " WHERE " + " AND ".join(f"({w})" if " OR " in w else w for w in q.where) if q.where else ""
533
+ if q.kind == "select":
534
+ cols = ", ".join(q.select) if q.select else ", ".join(f"{t}.{qi(c)}" for c in e.columns.values())
535
+ if q.join_cols and not q.select:
536
+ cols += ", " + ", ".join(q.join_cols)
537
+ if q.count:
538
+ cols = "COUNT(*)"
539
+ sql = f"SELECT {cols} FROM {t}" + "".join(" " + j for j in q.joins) + where
540
+ if q.group:
541
+ sql += " GROUP BY " + ", ".join(q.group)
542
+ if q.order and not q.count:
543
+ sql += " ORDER BY " + ", ".join(q.order)
544
+ if q.limit and not q.count:
545
+ sql += " LIMIT " + q.limit
546
+ if q.offset and not q.count:
547
+ sql += " OFFSET " + q.offset
548
+ return sql
549
+ if q.kind == "insert":
550
+ fields = q.values
551
+ if not fields:
552
+ fields = list(e.columns)
553
+ q.notes.append("the columns set are decided at run time: every column of the model is listed")
554
+ cols = [e.columns.get(f, f) for f in fields]
555
+ return (f"INSERT INTO {t} ({', '.join(qi(c) for c in cols)}) VALUES ({', '.join(_ph(f) for f in fields)})"
556
+ + "".join(" " + x for x in q.tail))
557
+ if q.kind == "update":
558
+ if not q.set:
559
+ raise Skip("update with no columns set")
560
+ return f"UPDATE {t} SET {', '.join(q.set)}" + where
561
+ if q.kind == "delete":
562
+ return f"DELETE FROM {t}" + where
563
+ raise Skip("unknown statement kind")
564
+
565
+ # ---- driver
566
+ def sites(self, rs, test_file: bool) -> list[RawSite]:
567
+ out = []
568
+ seen: set[int] = set()
569
+ stack = [rs.root]
570
+ calls = []
571
+ while stack:
572
+ n = stack.pop()
573
+ if n.type == "call_expression":
574
+ calls.append(n)
575
+ stack.extend(n.children)
576
+ for call in calls:
577
+ top = outermost(call)
578
+ if top.id in seen:
579
+ continue
580
+ seen.add(top.id)
581
+ root, steps = unroll(top)
582
+ names = [s[0] for s in steps]
583
+ if not steps:
584
+ continue
585
+ last = names[-1]
586
+ test = test_file or rs.is_test_node(top)
587
+ q = None
588
+ later: list[tuple[str, list[Node], Node, bool]] = []
589
+ try:
590
+ q = self.start(rs, root)
591
+ if q is None and root is not None and root.type in ("identifier", "field_expression", "call_expression"):
592
+ # an ActiveModel kept in a variable: `new_user.insert(db)`; or a query kept in a variable
593
+ exec_i = next((i for i, nm in enumerate(names) if nm in AM_EXECUTORS | EXECUTORS), None)
594
+ if exec_i is None:
595
+ continue
596
+ if root.type == "identifier":
597
+ val = self.let_value(rs, _txt(root), top)
598
+ if val is None:
599
+ continue
600
+ vroot, vsteps = unroll(strip(val))
601
+ q = self.start(rs, vroot)
602
+ if q is not None:
603
+ later = [(nm, a, n, False) for nm, a, n in vsteps]
604
+ # `q = q.filter(..)` reassignments between the let and the call
605
+ later.extend(self.reassigned(rs, _txt(root), val, top))
606
+ elif names[exec_i] in AM_EXECUTORS and exec_i == 0:
607
+ fields = self.am_fields(rs, root, top)
608
+ ent = self.am_entity(rs, val)
609
+ if ent is None:
610
+ continue
611
+ q = self.am_query(ent, names[exec_i], fields)
612
+ steps = steps[1:]
613
+ else:
614
+ continue
615
+ else:
616
+ continue
617
+ if q is None:
618
+ continue
619
+ if not any(nm in EXECUTORS or nm in AM_EXECUTORS for nm in names) and not any(nm in EXECUTORS for nm, *_ in later):
620
+ holder = top.parent
621
+ while holder is not None and holder.type in ("await_expression", "try_expression"):
622
+ holder = holder.parent
623
+ if holder is not None and holder.type == "let_declaration":
624
+ continue # run later through the variable
625
+ if holder is not None and holder.type == "arguments":
626
+ continue # a subquery of another statement
627
+ self.stats.seen(LIB, test)
628
+ self.stats.miss(LIB, "query built here and executed elsewhere (returned or passed on)", rs.rel, top.start_point[0] + 1, test)
629
+ continue
630
+ self.stats.seen(LIB, test)
631
+ for nm, a, n, c in later:
632
+ self.step(rs, q, nm, a, n, c)
633
+ done = False
634
+ for nm, a, n in steps:
635
+ if done:
636
+ break # what runs on the result (.into_iter(), .map(...)) is Rust, not SQL
637
+ if nm in EXECUTORS or (nm in AM_EXECUTORS and q.kind != "select"):
638
+ done = True
639
+ if nm in AM_EXECUTORS and q.kind in ("insert", "update", "delete") and not a:
640
+ continue
641
+ if nm in ("insert", "update", "delete", "save") and q.kind != "select" and a:
642
+ q.executor = nm
643
+ continue
644
+ self.step(rs, q, nm, a, n, False)
645
+ sql = self.sql(q)
646
+ except Skip as exc:
647
+ self.stats.seen(LIB, test)
648
+ self.stats.miss(LIB, str(exc), rs.rel, top.start_point[0] + 1, test)
649
+ continue
650
+ except RecursionError:
651
+ continue
652
+ conf = "high" if not q.runtime and not q.notes else "medium"
653
+ orm = {"library": LIB, "model_or_table": q.ent.table, "operation": "count" if q.count else q.kind,
654
+ "confidence": conf, "mechanism": "orm_api_in_loop" if rs.in_loop(top) else "orm_api"}
655
+ if q.notes:
656
+ orm["notes"] = "; ".join(dict.fromkeys(q.notes))
657
+ out.append(RawSite(
658
+ file=rs.rel, line=top.start_point[0] + 1, end_line=top.end_point[0] + 1, language="rust", kind="call",
659
+ sink="sea_orm." + (q.executor or last), symbol=rs.symbol(top), sql=sql, resolution="orm",
660
+ expr=trim(_txt(top)), in_loop=rs.in_loop(top), engine_hint="", is_test=test, known_sink=True, orm=orm))
661
+ self.stats.hit(LIB, 1, test)
662
+ return out
663
+
664
+ def reassigned(self, rs, name: str, decl_val: Node, at: Node) -> list[tuple[str, list[Node], Node, bool]]:
665
+ fn = rs._enclosing(at, ("function_item",))
666
+ out = []
667
+ if fn is None:
668
+ return out
669
+ for x in self._walk(fn):
670
+ if x.start_byte <= decl_val.end_byte or x.start_byte >= at.start_byte:
671
+ continue
672
+ if x.type == "assignment_expression" and _txt(x.child_by_field_name("left")) == name:
673
+ r, st = unroll(strip(x.child_by_field_name("right")))
674
+ if r is not None and _txt(r) == name:
675
+ cond = conditional(x, at)
676
+ out.extend((nm, a, n, cond) for nm, a, n in st)
677
+ return out
678
+
679
+ def am_entity(self, rs, val: Node) -> Entity | None:
680
+ for x in self._walk(val):
681
+ if x.type == "struct_expression":
682
+ name = re.sub(r"\s+", "", _txt(x.child_by_field_name("name")))
683
+ got = self.m.resolve(name, self.here(rs))
684
+ if got is not None and got[1] == "ActiveModel":
685
+ return got[0]
686
+ if x.type == "call_expression":
687
+ parts = call_parts(x)
688
+ if parts is not None and parts[1] in ("into_active_model", "from") and parts[3]:
689
+ got = self.m.resolve(parts[3].rpartition("::")[0], self.here(rs))
690
+ if got is not None:
691
+ return got[0]
692
+ return None
693
+
694
+ def am_query(self, ent: Entity, op: str, fields: list[str] | None) -> Q:
695
+ if op in ("insert",):
696
+ q = Q(ent, "insert")
697
+ q.values = fields
698
+ return q
699
+ if op == "delete":
700
+ q = Q(ent, "delete")
701
+ else:
702
+ q = Q(ent, "update")
703
+ cols = [c for c in (fields or []) if c not in ent.pk]
704
+ if not cols:
705
+ cols = [f for f in ent.columns if f not in ent.pk]
706
+ q.notes.append("the columns set are decided at run time: every column of the model is listed")
707
+ q.set = [f"{qi(ent.columns.get(c, c))} = {_ph(c)}" for c in cols]
708
+ if op == "save":
709
+ q.notes.append("save(): an INSERT when the primary key is not set")
710
+ for k in ent.pk:
711
+ q.where.append(f"{qi(ent.table)}.{qi(ent.columns.get(k, k))} = {_ph(k)}")
712
+ return q
713
+
714
+
715
+ def run(ctx, stats) -> tuple[list[RawSite], list[OrmTable]]:
716
+ model = Model()
717
+ for rs in ctx.files.values():
718
+ if (b"sea_orm" in rs.src and b"table_name" in rs.src) or (b"pub use" in rs.src and b"::Entity as" in rs.src):
719
+ try:
720
+ model.read(rs.rel, rs.src.decode("utf-8", "replace"))
721
+ except Exception:
722
+ continue
723
+ if not model.entities:
724
+ return [], []
725
+ s = SeaOrm(ctx, model, stats)
726
+ out: list[RawSite] = []
727
+ for rs in ctx.files.values():
728
+ if b"sea_orm" not in rs.src and not any(name.encode() in rs.src for name in list(model.names)[:200]):
729
+ continue
730
+ try:
731
+ out.extend(s.sites(rs, ctx.is_test_file(rs.rel)))
732
+ except RecursionError:
733
+ continue
734
+ return out, model.orm_tables()