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,2475 @@
1
+ """SQLAlchemy (Core and ORM, 1.x and 2.0 styles) as SQL sites and table definitions.
2
+
3
+ Tables come from declarative models (`__tablename__`, `Column` / `mapped_column`, `Mapped[...]` annotations,
4
+ `__table_args__`), from `Table(...)` objects, from SQLModel classes, and from Alembic migrations
5
+ (`op.create_table` / `add_column` / `create_index`). Statements are followed as values through a function:
6
+ `select(...)`, `session.query(...)`, `insert/update/delete(...)` and the calls chained on them. A site is emitted
7
+ where the statement is sent (`session.execute/scalars/scalar`, a Query's `all/first/one/count/...`, iteration),
8
+ one more per eager-load relation (`selectinload`, `subqueryload`), and for lazy relationship access on the rows
9
+ of a loop. Anything decided at run time is a «run-time part»; what cannot be decided is counted, not guessed.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import ast
15
+ import os
16
+ import re
17
+ from pathlib import Path
18
+
19
+ from .orm_django_models import OrmTable
20
+ from .orm_django_sql import CONF, HIGH, LOW, MEDIUM, Op
21
+ from .orm_py import SETTINGS, Cls, Emitter, Mod, Project, Stats, const, dotted, kwarg, marker, sql_literal, src, str_const, unmark
22
+
23
+ COLUMN_CALLS = {"Column", "mapped_column", "Field", "column_property", "deferred"}
24
+ REL_CALLS = {"relationship", "Relationship", "relation"}
25
+ EXEC = {"execute", "scalars", "scalar", "exec", "stream", "stream_scalars", "run_sync"}
26
+ RESULT = {"all", "first", "one", "one_or_none", "scalar", "scalars", "scalar_one", "scalar_one_or_none", "fetchall", "fetchone",
27
+ "fetchmany", "unique", "mappings", "partitions", "tuples", "yield_per"}
28
+ SEL_METHODS = {"where", "filter", "filter_by", "join", "outerjoin", "join_from", "outerjoin_from", "select_from", "order_by", "group_by",
29
+ "having", "limit", "offset", "distinct", "options", "with_for_update", "execution_options", "with_only_columns",
30
+ "add_columns", "correlate", "correlate_except", "slice", "params", "with_entities", "union", "union_all", "intersect",
31
+ "except_", "prefix_with", "suffix_with", "with_hint", "enable_eagerloads", "populate_existing", "autoflush",
32
+ "with_loader_criteria", "column", "reduce_columns", "set_label_style", "where_all", "returning", "values",
33
+ "on_conflict_do_update", "on_conflict_do_nothing", "on_duplicate_key_update", "from_select", "with_session",
34
+ "with_parent", "only_return_tuples", "with_labels", "apply_labels", "isouter", "filter_by_all"}
35
+ EAGER = {"joinedload", "selectinload", "subqueryload", "immediateload", "contains_eager"}
36
+ OTHER_LOADS = {"load_only", "defer", "undefer", "raiseload", "noload", "lazyload", "defaultload", "Load", "undefer_group",
37
+ "with_expression", "selectin_polymorphic"}
38
+ TYPES = {"Integer": "INTEGER", "BigInteger": "BIGINT", "SmallInteger": "SMALLINT", "String": "VARCHAR", "Text": "TEXT",
39
+ "Unicode": "VARCHAR", "Float": "FLOAT", "Numeric": "DECIMAL", "Date": "DATE", "DateTime": "TIMESTAMP", "Boolean": "BOOLEAN",
40
+ "Time": "TIME", "JSON": "JSON", "JSONB": "JSONB", "Uuid": "UUID", "UUID": "UUID", "LargeBinary": "BYTEA"}
41
+
42
+
43
+ ANN_WRAPPERS = ("Mapped", "Optional", "Annotated", "WriteOnlyMapped", "DynamicMapped", "Required", "NotRequired", "Final")
44
+
45
+
46
+ def ann_type(node: ast.AST | None) -> str:
47
+ """The Python type a column is annotated with, as the bench reads a column type when the column call names none
48
+ (`id: Mapped[int] = mapped_column(primary_key=True)`, SQLModel `id: UUID = Field(...)`): the innermost name under
49
+ Mapped / Optional / Annotated / `X | None`; `dict` for a mapping, `list` for a sequence; '' when none can be told."""
50
+ for _ in range(6):
51
+ if node is None:
52
+ return ""
53
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
54
+ try:
55
+ node = ast.parse(node.value, mode="eval").body
56
+ except SyntaxError:
57
+ return ""
58
+ continue
59
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.BitOr):
60
+ sides = [s for s in (node.left, node.right) if not (isinstance(s, ast.Constant) and s.value is None)]
61
+ node = sides[0] if sides else None
62
+ continue
63
+ if isinstance(node, ast.Subscript):
64
+ head = (dotted(node.value) or "").split(".")[-1]
65
+ if head in ANN_WRAPPERS:
66
+ inner = node.slice
67
+ node = inner.elts[0] if isinstance(inner, ast.Tuple) and inner.elts else inner
68
+ continue
69
+ if head.lower() in ("dict", "mapping", "mutablemapping"):
70
+ return "dict"
71
+ if head.lower() in ("list", "sequence", "set", "frozenset", "tuple"):
72
+ return "list"
73
+ if head == "Literal":
74
+ return "str"
75
+ return head
76
+ name = (dotted(node) or "").split(".")[-1]
77
+ return name if name and name != "None" else ""
78
+ return ""
79
+
80
+
81
+ def _snake(name: str) -> str:
82
+ return re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "_", name).lower()
83
+
84
+
85
+ # ---- metadata ---------------------------------------------------------------------------------------------------
86
+ class SACol:
87
+ __slots__ = ("attr", "name", "pk", "fk", "index", "unique", "type")
88
+
89
+ def __init__(self, attr: str, name: str, pk: bool = False, fk: str = "", index: bool = False, unique: bool = False, type: str = ""):
90
+ self.attr, self.name, self.pk, self.fk, self.index, self.unique, self.type = attr, name, pk, fk, index, unique, type
91
+
92
+
93
+ class SARel:
94
+ __slots__ = ("attr", "target", "secondary", "lazy", "uselist", "fk_hint", "owner", "line")
95
+
96
+ def __init__(self, attr: str, target, secondary=None, lazy: str = "select", uselist=None, fk_hint: str = "", owner=None, line: int = 0):
97
+ self.attr, self.target, self.secondary, self.lazy, self.uselist, self.fk_hint, self.owner, self.line = \
98
+ attr, target, secondary, lazy, uselist, fk_hint, owner, line
99
+
100
+
101
+ class SATable:
102
+ def __init__(self, name: str, where: str, cls: Cls | None = None):
103
+ self.name, self.where, self.cls = name, where, cls
104
+ self.cols: dict[str, SACol] = {} # attribute name -> column
105
+ self.rels: dict[str, SARel] = {}
106
+ self.indexes: list[dict] = []
107
+ self.synonyms: dict[str, str] = {}
108
+ self.source = "model"
109
+
110
+ def col(self, attr: str) -> SACol | None:
111
+ c = self.cols.get(self.synonyms.get(attr, attr))
112
+ if c is None:
113
+ for x in self.cols.values():
114
+ if x.name == attr:
115
+ return x
116
+ return c
117
+
118
+ def pks(self) -> list[SACol]:
119
+ return [c for c in self.cols.values() if c.pk]
120
+
121
+ def __hash__(self) -> int:
122
+ return id(self)
123
+
124
+ def __eq__(self, other) -> bool:
125
+ return self is other
126
+
127
+
128
+ class SAIndex:
129
+ def __init__(self, project: Project):
130
+ self.project = project
131
+ self.by_cls: dict[int, SATable] = {}
132
+ self.by_name: dict[str, SATable] = {}
133
+ self.by_clsname: dict[str, list[SATable]] = {}
134
+ self.table_vars: dict[tuple[str, str], SATable] = {} # (module, variable) -> Table(...)
135
+ self.alembic: dict[str, SATable] = {}
136
+ self._build()
137
+
138
+ # -- columns ----------------------------------------------------------------------------------------------
139
+ @staticmethod
140
+ def _call_name(node: ast.AST) -> str:
141
+ return (dotted(node.func) or "").split(".")[-1] if isinstance(node, ast.Call) else ""
142
+
143
+ def _column(self, attr: str, call: ast.Call | None, ann: ast.AST | None = None) -> SACol:
144
+ name = attr
145
+ c = SACol(attr, name)
146
+ if call is None:
147
+ c.type = ann_type(ann)
148
+ return c
149
+ inner = call
150
+ if self._call_name(call) in ("deferred", "column_property") and call.args and isinstance(call.args[0], ast.Call):
151
+ inner = call.args[0]
152
+ if inner.args and str_const(inner.args[0]) and self._call_name(inner) != "Field":
153
+ c.name = str_const(inner.args[0])
154
+ if str_const(kwarg(inner, "name")):
155
+ c.name = str_const(kwarg(inner, "name"))
156
+ if str_const(kwarg(inner, "sa_column_kwargs")):
157
+ pass
158
+ for a in inner.args:
159
+ nm = self._call_name(a)
160
+ if nm == "ForeignKey" and a.args:
161
+ c.fk = str_const(a.args[0]) or (dotted(a.args[0]) or "")
162
+ elif not c.type:
163
+ t = (dotted(a.func) if isinstance(a, ast.Call) else dotted(a)) or ""
164
+ if t and t.split(".")[-1][:1].isupper() and not str_const(a):
165
+ c.type = t.split(".")[-1]
166
+ if str_const(kwarg(inner, "foreign_key")):
167
+ c.fk = str_const(kwarg(inner, "foreign_key"))
168
+ sa_col = kwarg(inner, "sa_column")
169
+ if isinstance(sa_col, ast.Call):
170
+ sub = self._column(attr, sa_col)
171
+ c.name, c.fk, c.type = sub.name, sub.fk or c.fk, sub.type or c.type
172
+ c.pk, c.index, c.unique = sub.pk, sub.index, sub.unique
173
+ for key in ("primary_key", "index", "unique"):
174
+ ok, v = const(kwarg(inner, key))
175
+ if ok and v:
176
+ setattr(c, "pk" if key == "primary_key" else key, True)
177
+ if not c.type:
178
+ c.type = ann_type(ann)
179
+ return c
180
+
181
+ def _relationship(self, attr: str, call: ast.Call, owner: SATable, cls: Cls | None) -> SARel:
182
+ target = kwarg(call, "argument") or (call.args[0] if call.args else None)
183
+ if isinstance(target, ast.Lambda):
184
+ target = target.body
185
+ tname = str_const(target) or dotted(target) if target is not None else None
186
+ sec = kwarg(call, "secondary") or kwarg(call, "link_model")
187
+ fk = kwarg(call, "foreign_keys")
188
+ hint = ""
189
+ if fk is not None:
190
+ el = fk.elts[0] if isinstance(fk, (ast.List, ast.Tuple)) and fk.elts else fk
191
+ hint = (str_const(el) or dotted(el) or "").strip("[]").split(",")[0].split(".")[-1].strip()
192
+ ok, ul = const(kwarg(call, "uselist"))
193
+ lazy = str_const(kwarg(call, "lazy")) or "select"
194
+ sk = kwarg(call, "sa_relationship_kwargs")
195
+ if isinstance(sk, ast.Dict):
196
+ for k, v in zip(sk.keys, sk.values):
197
+ if str_const(k) == "lazy" and str_const(v):
198
+ lazy = str_const(v)
199
+ return SARel(attr, tname, str_const(sec) or dotted(sec) if sec is not None else None, lazy, ul if ok else None, hint, owner, call.lineno)
200
+
201
+ def _from_class(self, cls: Cls) -> SATable | None:
202
+ p = self.project
203
+ if id(cls) in self.by_cls:
204
+ return self.by_cls[id(cls)]
205
+ mro = p.mro(cls)
206
+ ext = [e.split(".")[-1] for e in p.external_bases(cls)]
207
+ tname = None
208
+ table_call = None
209
+ for c in mro:
210
+ if "__tablename__" in c.assigns:
211
+ tname = str_const(c.assigns["__tablename__"])
212
+ if tname is None:
213
+ d = dotted(c.assigns["__tablename__"])
214
+ got = p.resolve(c.mod, d) if d else None
215
+ tname = str_const(got[2]) if got is not None and got[0] == "value" else None
216
+ break
217
+ if "__table__" in c.assigns and isinstance(c.assigns["__table__"], ast.Call):
218
+ table_call = c.assigns["__table__"]
219
+ tname = str_const(table_call.args[0]) if table_call.args else None
220
+ break
221
+ is_sqlmodel = False
222
+ if tname is None:
223
+ # SQLModel `class Hero(SQLModel, table=True)`, Flask-SQLAlchemy `class User(db.Model)`: the class name
224
+ for c in mro[:1]:
225
+ ok, v = const(next((k.value for k in c.node.keywords if k.arg == "table"), None))
226
+ if ok and v:
227
+ tname, is_sqlmodel = c.name.lower(), True
228
+ if tname is None and "Model" in ext and any(dotted(b) in ("db.Model", "Model") for b in cls.base_exprs) \
229
+ and any("sqlalchemy" in (p.external(cls.mod, (dotted(b) or "").split(".")[0]) or "") or dotted(b) == "db.Model"
230
+ for b in cls.base_exprs) and "__abstract__" not in cls.assigns:
231
+ tname = _snake(cls.name)
232
+ if not tname:
233
+ return None
234
+ ok, abstract = const(cls.assigns.get("__abstract__"))
235
+ if ok and abstract:
236
+ return None
237
+ existing = self.by_name.get(tname)
238
+ if existing is not None and existing.cls is not None and existing.cls is not cls and cls in [x for x in p.mro(cls)] \
239
+ and existing.cls in mro:
240
+ # single-table inheritance: the subclass maps to the parent's table
241
+ self.by_cls[id(cls)] = existing
242
+ for c in mro:
243
+ self._class_columns(existing, c, only_new=True)
244
+ return existing
245
+ t = SATable(tname, f"{cls.mod.rel}:{cls.node.lineno}", cls)
246
+ self.by_cls[id(cls)] = t
247
+ if table_call is not None:
248
+ self._table_args(t, table_call.args[2:] if len(table_call.args) > 2 else table_call.args[1:], cls.mod)
249
+ for c in reversed(mro):
250
+ self._class_columns(t, c)
251
+ for c in mro:
252
+ args = c.assigns.get("__table_args__")
253
+ if args is not None:
254
+ self._table_args(t, args.elts if isinstance(args, (ast.Tuple, ast.List)) else [args], c.mod, t)
255
+ break
256
+ _ = is_sqlmodel
257
+ return t
258
+
259
+ def _class_columns(self, t: SATable, c: Cls, only_new: bool = False) -> None:
260
+ for st in c.node.body:
261
+ target = value = ann = None
262
+ if isinstance(st, ast.Assign) and len(st.targets) == 1 and isinstance(st.targets[0], ast.Name):
263
+ target, value = st.targets[0].id, st.value
264
+ elif isinstance(st, ast.AnnAssign) and isinstance(st.target, ast.Name):
265
+ target, value, ann = st.target.id, st.value, st.annotation
266
+ if target is None or target.startswith("__"):
267
+ continue
268
+ nm = self._call_name(value) if value is not None else ""
269
+ if nm in REL_CALLS:
270
+ t.rels[target] = self._relationship(target, value, t, c)
271
+ elif nm in COLUMN_CALLS:
272
+ if only_new and target in t.cols:
273
+ continue
274
+ t.cols[target] = self._column(target, value, ann)
275
+ elif nm == "synonym" and value.args and str_const(value.args[0]):
276
+ t.synonyms[target] = str_const(value.args[0])
277
+ elif nm in ("association_proxy", "hybrid_property", "query_expression", "composite"):
278
+ continue
279
+ elif ann is not None and value is None or (ann is not None and nm == ""):
280
+ a = src(ann)
281
+ if a.startswith(("Mapped[", "orm.Mapped[", "so.Mapped[")):
282
+ inner = a[a.index("[") + 1:]
283
+ if inner.lstrip("'\"").startswith(("list[", "List[", "set[", "Set[")) or (
284
+ inner.split("[")[0].split("|")[0].strip(" '\"]")[:1].isupper()
285
+ and inner.split("[")[0].split("|")[0].strip(" '\"]") in self.by_clsname):
286
+ continue # an annotated relationship without `relationship()`: no column
287
+ if target not in t.cols:
288
+ t.cols[target] = SACol(target, target, type=ann_type(ann))
289
+ elif c.node.keywords and any(k.arg == "table" for k in c.node.keywords) or (
290
+ "SQLModel" in [e.split(".")[-1] for e in self.project.external_bases(c)]):
291
+ if target not in t.cols and not a.startswith(("ClassVar", "list[", "List[", "Optional[\"", "Optional['")):
292
+ t.cols[target] = SACol(target, target, type=ann_type(ann))
293
+
294
+ def _table_args(self, t: SATable, args: list, mod: Mod, model: SATable | None = None) -> None:
295
+ for a in args:
296
+ nm = self._call_name(a)
297
+ if nm == "Column" and a.args and str_const(a.args[0]):
298
+ c = self._column(str_const(a.args[0]), a)
299
+ t.cols[c.attr] = c
300
+ elif nm in ("Index", "UniqueConstraint", "PrimaryKeyConstraint"):
301
+ items = a.args[1:] if nm == "Index" else a.args
302
+ cols = []
303
+ for x in items:
304
+ s = str_const(x) or (dotted(x) or "").split(".")[-1]
305
+ col = t.col(s) if s else None
306
+ cols.append(col.name if col is not None else (s if str_const(x) else ""))
307
+ cols = [c for c in cols if c]
308
+ if not cols:
309
+ continue
310
+ ok, uniq = const(kwarg(a, "unique"))
311
+ name = (str_const(a.args[0]) if nm == "Index" and a.args else str_const(kwarg(a, "name"))) or ""
312
+ entry = {"name": name, "columns": cols, "unique": nm != "Index" or bool(ok and uniq)}
313
+ if nm == "PrimaryKeyConstraint":
314
+ entry["primary"] = True
315
+ for cn in cols:
316
+ col = t.col(cn)
317
+ if col is not None:
318
+ col.pk = True
319
+ if any(k.arg and k.arg.endswith("_where") for k in a.keywords):
320
+ entry["partial"] = True
321
+ t.indexes.append(entry)
322
+ elif nm == "ForeignKeyConstraint" and len(a.args) >= 2:
323
+ locs = a.args[0].elts if isinstance(a.args[0], (ast.Tuple, ast.List)) else [a.args[0]]
324
+ rems = a.args[1].elts if isinstance(a.args[1], (ast.Tuple, ast.List)) else [a.args[1]]
325
+ for l, r in zip(locs, rems):
326
+ ls = str_const(l) or (dotted(l) or "").split(".")[-1]
327
+ col = t.col(ls) if ls else None
328
+ rs = str_const(r) or ""
329
+ if col is not None and rs and not col.fk:
330
+ col.fk = rs
331
+
332
+ def _build(self) -> None:
333
+ p = self.project
334
+ # Table("name", metadata, Column(...), ...) bound to a module variable
335
+ for mod in p.mods.values():
336
+ if "Table(" not in mod.text:
337
+ continue
338
+ for var, value in mod.assigns.items():
339
+ if isinstance(value, ast.Call) and self._call_name(value) == "Table" and value.args and str_const(value.args[0]):
340
+ ext = p.external(mod, dotted(value.func)) or ""
341
+ if not ext.startswith(("sqlalchemy", "sqlmodel", "flask_sqlalchemy")) and not (dotted(value.func) or "").startswith(("sa.", "db.", "sqlalchemy.")):
342
+ continue
343
+ t = SATable(str_const(value.args[0]), f"{mod.rel}:{value.lineno}")
344
+ t.source = "table"
345
+ self._table_args(t, value.args[1:], mod)
346
+ self.table_vars[(mod.rel, var)] = t
347
+ self.by_name.setdefault(t.name, t)
348
+ for mod in p.mods.values():
349
+ if "__tablename__" not in mod.text and "table=True" not in mod.text and "db.Model" not in mod.text and "__table__" not in mod.text:
350
+ continue
351
+ for cls in mod.classes.values():
352
+ self.by_clsname.setdefault(cls.name, [])
353
+ # two passes: classes by name first (annotated relationships look names up), then columns
354
+ cands = []
355
+ for mod in p.mods.values():
356
+ for cls in mod.classes.values():
357
+ if cls.name in self.by_clsname or any(k.arg == "table" for k in cls.node.keywords) or "__tablename__" in cls.assigns:
358
+ cands.append(cls)
359
+ for cls in cands:
360
+ t = self._from_class(cls)
361
+ if t is not None:
362
+ self.by_clsname.setdefault(cls.name, [])
363
+ if t not in self.by_clsname[cls.name]:
364
+ self.by_clsname[cls.name].append(t)
365
+ cur = self.by_name.get(t.name)
366
+ if cur is None or (cur.cls is not None and cur.cls.mod.is_test and not cls.mod.is_test) or cur.source == "table":
367
+ self.by_name[t.name] = t
368
+ # classes that inherit a mapped class without a table of their own: same table
369
+ for mod in p.mods.values():
370
+ for cls in mod.classes.values():
371
+ if id(cls) in self.by_cls:
372
+ continue
373
+ for base in p.mro(cls)[1:]:
374
+ if id(base) in self.by_cls:
375
+ ok, abstract = const(cls.assigns.get("__abstract__"))
376
+ if not (ok and abstract):
377
+ self.by_cls[id(cls)] = self.by_cls[id(base)]
378
+ self.by_clsname.setdefault(cls.name, []).append(self.by_cls[id(base)])
379
+ break
380
+ for t in list(self.by_cls.values()):
381
+ for c in t.cols.values():
382
+ if c.pk and not any(i.get("primary") for i in t.indexes):
383
+ pass
384
+ self._alembic()
385
+
386
+ def entity(self, mod: Mod, name: str) -> SATable | None:
387
+ cls = self.project.resolve_class(mod, name)
388
+ if cls is not None:
389
+ return self.by_cls.get(id(cls))
390
+ got = self.project.resolve(mod, name)
391
+ if got is not None and got[0] == "value":
392
+ head = name.split(".")[-1]
393
+ return self.table_vars.get((got[1].rel, head))
394
+ return None
395
+
396
+ def rel_target(self, rel: SARel) -> SATable | None:
397
+ if not rel.target:
398
+ return None
399
+ name = rel.target.split(".")[-1]
400
+ owner_cls = rel.owner.cls if rel.owner is not None else None
401
+ if owner_cls is not None:
402
+ cls = self.project.resolve_class(owner_cls.mod, rel.target)
403
+ if cls is not None and id(cls) in self.by_cls:
404
+ return self.by_cls[id(cls)]
405
+ found = self.by_clsname.get(name, [])
406
+ uniq = list(dict.fromkeys(found))
407
+ if len(uniq) == 1:
408
+ return uniq[0]
409
+ apps = [t for t in uniq if t.cls is not None and not t.cls.mod.is_test]
410
+ return apps[0] if len(apps) == 1 else None
411
+
412
+ def rel_join(self, rel: SARel) -> tuple[SATable, list[tuple[str, str]], str] | None:
413
+ """(target, [(owner column, target column)], direction) for a relationship, from the foreign keys."""
414
+ owner, target = rel.owner, self.rel_target(rel)
415
+ if owner is None or target is None or rel.secondary:
416
+ return None
417
+ def fks(a: SATable, b: SATable):
418
+ out = []
419
+ for c in a.cols.values():
420
+ if c.fk and c.fk.split(".")[-2:-1] == [b.name]:
421
+ if rel.fk_hint and rel.fk_hint not in (c.attr, c.name):
422
+ continue
423
+ out.append((c.name, c.fk.split(".")[-1]))
424
+ return out
425
+ m2o = fks(owner, target)
426
+ o2m = fks(target, owner)
427
+ if owner is target and m2o:
428
+ # self-referential: a list is the one-to-many side
429
+ many = rel.uselist is not False and not rel.fk_hint and False
430
+ return (target, [(b, a) for a, b in m2o], "o2m") if many else (target, m2o, "m2o")
431
+ if m2o and (not o2m or rel.uselist is False or rel.fk_hint):
432
+ return target, m2o, "m2o"
433
+ if o2m:
434
+ return target, [(b, a) for a, b in o2m], "o2m"
435
+ return None
436
+
437
+ def secondary_join(self, rel: SARel):
438
+ """(target, association table, [(assoc column, owner column)], [(assoc column, target column)]) for a many-to-many."""
439
+ owner, target = rel.owner, self.rel_target(rel)
440
+ if owner is None or target is None or not rel.secondary:
441
+ return None
442
+ name = rel.secondary.split(".")[-1]
443
+ sec = self.by_name.get(name) or next((t for (_, var), t in self.table_vars.items() if var == name), None)
444
+ if sec is None:
445
+ found = list(dict.fromkeys(self.by_clsname.get(name, [])))
446
+ sec = found[0] if len(found) == 1 else None
447
+ if sec is None:
448
+ return None
449
+ own = [(c.name, c.fk.split(".")[-1]) for c in sec.cols.values() if c.fk and c.fk.split(".")[-2:-1] == [owner.name]]
450
+ tgt = [(c.name, c.fk.split(".")[-1]) for c in sec.cols.values() if c.fk and c.fk.split(".")[-2:-1] == [target.name]]
451
+ if owner is target and len(own) >= 2:
452
+ own, tgt = own[:1], own[1:2]
453
+ return (target, sec, own, tgt) if own and tgt else None
454
+
455
+ # -- Alembic ----------------------------------------------------------------------------------------------
456
+ def _alembic(self) -> None:
457
+ mods = [m for m in self.project.mods.values() if "op." in m.text and "upgrade" in m.funcs
458
+ and ("alembic" in m.text or "/versions/" in m.rel or "migrations/" in m.rel)]
459
+ tables: dict[str, SATable] = {}
460
+
461
+ def name_of(node, mod):
462
+ s = str_const(node)
463
+ if s is None and isinstance(node, ast.Name) and node.id in mod.assigns:
464
+ s = str_const(mod.assigns[node.id])
465
+ return s
466
+
467
+ for mod in sorted(mods, key=lambda m: m.rel):
468
+ up = mod.funcs["upgrade"]
469
+ batch: dict[str, str] = {}
470
+ for node in ast.walk(up):
471
+ if isinstance(node, (ast.With, ast.AsyncWith)):
472
+ for item in node.items:
473
+ ce = item.context_expr
474
+ if isinstance(ce, ast.Call) and (dotted(ce.func) or "").endswith("batch_alter_table") and ce.args \
475
+ and isinstance(item.optional_vars, ast.Name):
476
+ nm = name_of(ce.args[0], mod)
477
+ if nm:
478
+ batch[item.optional_vars.id] = nm
479
+ for node in ast.walk(up):
480
+ if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):
481
+ continue
482
+ recv, meth = dotted(node.func.value) or "", node.func.attr
483
+ bt = batch.get(recv)
484
+ if recv != "op" and bt is None:
485
+ continue
486
+ where = f"{mod.rel}:{node.lineno}"
487
+ args = list(node.args)
488
+ if meth == "create_table" and args:
489
+ nm = name_of(args[0], mod)
490
+ if nm:
491
+ t = SATable(nm, where)
492
+ t.source = "alembic"
493
+ self._table_args(t, args[1:], mod)
494
+ tables[nm] = t
495
+ elif meth == "add_column":
496
+ nm = bt or (name_of(args[0], mod) if args else None)
497
+ col = args[0] if bt else (args[1] if len(args) > 1 else None)
498
+ if nm and isinstance(col, ast.Call) and col.args and str_const(col.args[0]):
499
+ t = tables.get(nm)
500
+ if t is None:
501
+ t = tables[nm] = SATable(nm, where)
502
+ t.source = "alembic-partial"
503
+ c = self._column(str_const(col.args[0]), col)
504
+ t.cols[c.attr] = c
505
+ elif meth == "create_index" and args:
506
+ iname = name_of(args[0], mod) or ""
507
+ nm = bt or (name_of(args[1], mod) if len(args) > 1 else None) or name_of(kwarg(node, "table_name"), mod) if (bt or len(args) > 1 or kwarg(node, "table_name")) else None
508
+ cols_node = args[1] if bt and len(args) > 1 else (args[2] if len(args) > 2 else kwarg(node, "columns"))
509
+ ok, cols = const(cols_node)
510
+ if nm and ok and isinstance(cols, list) and all(isinstance(c, str) for c in cols):
511
+ t = tables.get(nm)
512
+ if t is None:
513
+ t = tables[nm] = SATable(nm, where)
514
+ t.source = "alembic-partial"
515
+ oku, uniq = const(kwarg(node, "unique"))
516
+ t.indexes = [i for i in t.indexes if i["name"] != iname or not iname]
517
+ t.indexes.append({"name": iname, "columns": cols, "unique": bool(oku and uniq)})
518
+ elif meth == "drop_table" and args:
519
+ tables.pop(name_of(args[0], mod) or "", None)
520
+ elif meth == "drop_column":
521
+ nm = bt or (name_of(args[0], mod) if args else None)
522
+ cn = name_of(args[0] if bt else (args[1] if len(args) > 1 else None), mod) if args else None
523
+ if nm in tables and cn:
524
+ tables[nm].cols.pop(cn, None)
525
+ elif meth == "drop_index" and args:
526
+ iname = name_of(args[0], mod)
527
+ for t in tables.values():
528
+ t.indexes = [i for i in t.indexes if i["name"] != iname]
529
+ elif meth == "rename_table" and len(args) >= 2:
530
+ a, b = name_of(args[0], mod), name_of(args[1], mod)
531
+ if a in tables and b:
532
+ tables[b] = tables.pop(a)
533
+ tables[b].name = b
534
+ self.alembic = tables
535
+
536
+ def tables(self) -> list:
537
+ out = []
538
+ seen: set[str] = set()
539
+ models = {}
540
+ for t in list(self.by_cls.values()) + list(self.table_vars.values()):
541
+ if t.name not in models or (t.cls is not None and models[t.name].cls is None):
542
+ models[t.name] = t
543
+ for name, t in models.items():
544
+ mig = self.alembic.get(name)
545
+ idx = list(t.indexes)
546
+ for c in t.cols.values():
547
+ if c.pk and not any(i.get("primary") for i in idx):
548
+ idx.insert(0, {"name": "", "columns": [x.name for x in t.pks()], "unique": True, "primary": True})
549
+ for c in t.cols.values():
550
+ if c.unique and not c.pk:
551
+ idx.append({"name": "", "columns": [c.name], "unique": True})
552
+ elif c.index and not c.pk:
553
+ idx.append({"name": "", "columns": [c.name], "unique": False})
554
+ if mig is not None:
555
+ have = {(i["name"], tuple(i["columns"])) for i in idx}
556
+ names = {i["name"] for i in idx if i["name"]}
557
+ idx += [i for i in mig.indexes if (i["name"], tuple(i["columns"])) not in have and i["name"] not in names]
558
+ o = OrmTable(name=name, defined_at=[t.where] + ([mig.where] if mig is not None else []), name_basis="orm")
559
+ o.columns = [{"name": c.name, "type": c.type} for c in t.cols.values()]
560
+ o.indexes = idx
561
+ o.primary_key = ", ".join(c.name for c in t.pks())
562
+ o.orm = {"library": "sqlalchemy", "model": t.cls.qual if t.cls is not None else "Table()"}
563
+ out.append(o)
564
+ seen.add(name)
565
+ for name, t in self.alembic.items():
566
+ if name in seen or not t.cols:
567
+ continue
568
+ o = OrmTable(name=name, defined_at=[t.where], name_basis="orm")
569
+ o.columns = [{"name": c.name, "type": c.type} for c in t.cols.values()]
570
+ idx = list(t.indexes)
571
+ if t.pks() and not any(i.get("primary") for i in idx):
572
+ idx.insert(0, {"name": "", "columns": [x.name for x in t.pks()], "unique": True, "primary": True})
573
+ o.indexes = idx
574
+ o.primary_key = ", ".join(c.name for c in t.pks())
575
+ o.orm = {"library": "sqlalchemy", "model": "Alembic migration" + (" (columns added only)" if t.source == "alembic-partial" else "")}
576
+ out.append(o)
577
+ return out
578
+
579
+
580
+ # ---- values -----------------------------------------------------------------------------------------------------
581
+ class Ent:
582
+ """A mapped class or Table used in an expression, possibly aliased."""
583
+ __slots__ = ("table", "alias")
584
+
585
+ def __init__(self, table: SATable, alias: str = ""):
586
+ self.table, self.alias = table, alias
587
+
588
+ @property
589
+ def ref(self) -> str:
590
+ return self.alias or self.table.name
591
+
592
+ @property
593
+ def from_sql(self) -> str:
594
+ text = getattr(self.table, "from_text", "") # a subquery or CTE standing where a table would
595
+ if text:
596
+ return text
597
+ return f"{self.table.name} {self.alias}" if self.alias else self.table.name
598
+
599
+
600
+ class Ex:
601
+ """An SQL expression: its text, the tables it names, whether it aggregates."""
602
+ __slots__ = ("sql", "froms", "agg", "label", "ent")
603
+
604
+ def __init__(self, sql: str, froms: tuple = (), agg: bool = False, label: str = "", ent: Ent | None = None):
605
+ self.sql, self.froms, self.agg, self.label, self.ent = sql, froms, agg, label, ent
606
+
607
+
608
+ class RelV:
609
+ __slots__ = ("ent", "rel")
610
+
611
+ def __init__(self, ent: Ent, rel: SARel):
612
+ self.ent, self.rel = ent, rel
613
+
614
+
615
+ class Sel:
616
+ """A SELECT under construction (2.0 `select()` or a 1.x `Query`)."""
617
+ __slots__ = ("ops", "roots", "conf", "notes", "state", "query", "kind", "table")
618
+
619
+ def __init__(self, ops: tuple = (), roots: frozenset = frozenset(), conf: int = HIGH, notes: tuple = (), query: bool = False,
620
+ kind: str = "select", table: SATable | None = None):
621
+ self.ops, self.roots, self.conf, self.notes, self.query, self.kind, self.table = ops, roots, conf, notes, query, kind, table
622
+ self.state = {"emitted": False}
623
+
624
+ def add(self, op: Op, conf: int | None = None, note: str = "", roots: frozenset = frozenset()) -> "Sel":
625
+ return Sel(self.ops + (op,), self.roots | roots, max(self.conf, conf if conf is not None else HIGH),
626
+ self.notes + ((note,) if note and note not in self.notes else ()), self.query, self.kind, self.table)
627
+
628
+
629
+ class Sub:
630
+ """A subquery / CTE / alias of a statement: `sub.c.x` is a column of it."""
631
+ __slots__ = ("sel", "name", "scalar", "cte", "pseudo")
632
+
633
+ def __init__(self, sel: Sel, name: str, scalar: bool = False, cte: bool = False):
634
+ self.sel, self.name, self.scalar, self.cte = sel, name, scalar, cte
635
+ self.pseudo = None # the subquery as a FROM source, made when one of its columns is used
636
+
637
+
638
+ class InstV:
639
+ __slots__ = ("table", "origin", "per_iter", "name", "conf")
640
+
641
+ def __init__(self, table: SATable, origin: Sel | None = None, per_iter: int = 0, name: str = "", conf: int = HIGH):
642
+ self.table, self.origin, self.per_iter, self.name, self.conf = table, origin, per_iter, name, conf
643
+
644
+
645
+ class ResV:
646
+ """The result of an execution: iterating it yields rows (instances when one entity was selected)."""
647
+ __slots__ = ("elem", "sel")
648
+
649
+ def __init__(self, elem, sel=None):
650
+ self.elem, self.sel = elem, sel
651
+
652
+
653
+ class TupV:
654
+ """A tuple with a statement in it: `(statement, total)` from a pagination helper."""
655
+ __slots__ = ("items",)
656
+
657
+ def __init__(self, items: list):
658
+ self.items = items
659
+
660
+
661
+ class NS:
662
+ """`func`, `sa`, `sqlalchemy`, `orm`: a namespace whose attributes are SQLAlchemy names."""
663
+ __slots__ = ("kind",)
664
+
665
+ def __init__(self, kind: str):
666
+ self.kind = kind
667
+
668
+
669
+ class Ctx:
670
+ def __init__(self, root: Path, project: Project):
671
+ self.project = project
672
+ self.index = SAIndex(project)
673
+ self.stats = Stats("sqlalchemy")
674
+ self.out = Emitter(self.stats)
675
+ self.seen_roots: dict[int, str] = {}
676
+ self.done_roots: set[int] = set()
677
+ self.root_reason: dict[int, str] = {}
678
+ self.counted: set[int] = set()
679
+ self.cache: dict = {}
680
+ self.stack: list[int] = []
681
+ self.lazy = 0
682
+ self._ext: dict[tuple[str, str], str] = {}
683
+ self.anon = 0
684
+
685
+ def ext(self, mod: Mod, name: str) -> str:
686
+ key = (mod.rel, name)
687
+ got = self._ext.get(key)
688
+ if got is None:
689
+ got = self.project.external(mod, name) or ""
690
+ self._ext[key] = got
691
+ return got
692
+
693
+ def run(self) -> None:
694
+ for mod in self.project.mods.values():
695
+ t = mod.text
696
+ if not ("sqlalchemy" in t or "sqlmodel" in t or ".query(" in t or "session" in t or "Session" in t):
697
+ continue
698
+ self._scope(mod, None, mod.tree.body, "", None)
699
+ for nid, where in self.seen_roots.items():
700
+ if nid in self.done_roots:
701
+ self.stats.translated += 1
702
+ else:
703
+ self.stats.miss(self.root_reason.get(nid, "statement built here; no place where it is executed was found in the function"), where)
704
+ self.stats.extra["lazy_load_sites"] = self.lazy
705
+ self.stats.extra["models"] = len({id(t) for t in self.index.by_cls.values()})
706
+ self.stats.extra["tables_from_alembic_only"] = len([n for n in self.index.alembic if n not in self.index.by_name])
707
+
708
+ def _scope(self, mod: Mod, cls: Cls | None, body: list, symbol: str, func, outer_env: dict | None = None) -> None:
709
+ w = SAWalker(self, mod, cls, symbol, func=func, env=dict(outer_env or {}))
710
+ try:
711
+ w.run(body)
712
+ except RecursionError:
713
+ if os.environ.get("CODECOP_ORM_DEBUG") and os.environ["CODECOP_ORM_DEBUG"] in mod.rel:
714
+ raise
715
+ self.stats.miss("internal: expression too deep", f"{mod.rel}:{getattr(func, 'lineno', 1)}")
716
+ except Exception as e:
717
+ if os.environ.get("CODECOP_ORM_DEBUG") and os.environ["CODECOP_ORM_DEBUG"] in mod.rel:
718
+ raise
719
+ self.stats.miss(f"internal error ({type(e).__name__})", f"{mod.rel}:{getattr(func, 'lineno', 1)}")
720
+ for kind, node, owner in w.nested:
721
+ sym = (symbol + "." if symbol else "") + node.name
722
+ if kind == "func":
723
+ self._scope(mod, owner, node.body, sym, node, w.env if func is not None else None)
724
+ else:
725
+ self._scope(mod, owner, node.body, sym, None)
726
+
727
+
728
+ class SAWalker:
729
+ def __init__(self, cx: Ctx, mod: Mod, cls: Cls | None, symbol: str, *, func=None, env: dict | None = None, emit: bool = True,
730
+ depth: int = 0, preset: dict | None = None):
731
+ self.cx, self.mod, self.cls, self.symbol, self.func = cx, mod, cls, symbol, func
732
+ self.env: dict = env if env is not None else {}
733
+ self.emit, self.depth = emit, depth
734
+ self.loop = 0
735
+ self.returns: list = []
736
+ self.nested: list = []
737
+ self.lazy_seen: set = set()
738
+ self.class_level = func is None and cls is not None
739
+ if func is not None:
740
+ self._params(func, preset or {})
741
+
742
+ # ---- parameters and annotations --------------------------------------------------------------------------
743
+ def _params(self, func, preset: dict) -> None:
744
+ args = func.args
745
+ params = list(args.posonlyargs) + list(args.args) + list(args.kwonlyargs)
746
+ own = self.cx.index.by_cls.get(id(self.cls)) if self.cls is not None else None
747
+ for i, a in enumerate(params):
748
+ v = None
749
+ if i == 0 and own is not None and self.cls.methods.get(func.name) is func:
750
+ decos = {(dotted(d) or "").split(".")[-1] for d in func.decorator_list}
751
+ if a.arg == "cls" or "classmethod" in decos:
752
+ v = Ent(own)
753
+ elif a.arg == "self":
754
+ v = InstV(own, name="self")
755
+ if v is None and a.annotation is not None:
756
+ v = self.ann(a.annotation)
757
+ if isinstance(v, InstV):
758
+ v.name = a.arg
759
+ if v is not None:
760
+ self.env[a.arg] = v
761
+ else:
762
+ self.env.pop(a.arg, None)
763
+ for k, v in preset.items():
764
+ if v is not None:
765
+ self.env[k] = v
766
+
767
+ def ann(self, node: ast.AST | None, depth: int = 0):
768
+ if node is None or depth > 4:
769
+ return None
770
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
771
+ try:
772
+ node = ast.parse(node.value, mode="eval").body
773
+ except SyntaxError:
774
+ return None
775
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.BitOr):
776
+ return self.ann(node.left, depth + 1) or self.ann(node.right, depth + 1)
777
+ if isinstance(node, ast.Subscript):
778
+ head = (dotted(node.value) or "").split(".")[-1]
779
+ inner = node.slice.elts[0] if isinstance(node.slice, ast.Tuple) and node.slice.elts else node.slice
780
+ if head in ("Optional", "Annotated", "Final"):
781
+ return self.ann(inner, depth + 1)
782
+ if head in ("list", "List", "Sequence", "Iterable", "Collection", "Iterator", "set", "Set", "tuple", "Tuple", "ScalarResult"):
783
+ v = self.ann(inner, depth + 1)
784
+ return ResV(v) if isinstance(v, InstV) else None
785
+ if head in ("type", "Type"):
786
+ v = self.ann(inner, depth + 1)
787
+ return Ent(v.table) if isinstance(v, InstV) else None
788
+ return None
789
+ nm = dotted(node)
790
+ if not nm:
791
+ return None
792
+ t = self.cx.index.entity(self.mod, nm)
793
+ if t is not None and t.cls is not None:
794
+ return InstV(t, conf=MEDIUM)
795
+ return None
796
+
797
+ # ---- statements ---------------------------------------------------------------------------------------------
798
+ def run(self, body: list) -> None:
799
+ for st in body:
800
+ self.stmt(st)
801
+
802
+ def _branch(self, body: list) -> dict:
803
+ saved = self.env
804
+ self.env = dict(saved)
805
+ try:
806
+ self.run(body)
807
+ return self.env
808
+ finally:
809
+ self.env = saved
810
+
811
+ @staticmethod
812
+ def _terminates(body: list) -> bool:
813
+ return bool(body) and isinstance(body[-1], (ast.Return, ast.Raise, ast.Continue, ast.Break))
814
+
815
+ def _merge(self, a: dict, b: dict) -> dict:
816
+ out = {}
817
+ for name in set(a) | set(b):
818
+ va, vb = a.get(name), b.get(name)
819
+ if va is vb:
820
+ if va is not None:
821
+ out[name] = va
822
+ continue
823
+ if isinstance(va, Sel) and isinstance(vb, Sel) and va.kind == vb.kind and va.table is vb.table:
824
+ k = 0
825
+ while k < len(va.ops) and k < len(vb.ops) and va.ops[k] is vb.ops[k]:
826
+ k += 1
827
+ if k == 0:
828
+ continue
829
+ ops = va.ops[:k] + tuple(o.opt() for o in va.ops[k:]) + tuple(o.opt() for o in vb.ops[k:])
830
+ m = Sel(ops, va.roots | vb.roots, max(va.conf, vb.conf, MEDIUM), va.notes + tuple(n for n in vb.notes if n not in va.notes),
831
+ va.query, va.kind, va.table)
832
+ if va.state["emitted"] and vb.state["emitted"]:
833
+ m.state["emitted"] = True
834
+ out[name] = m
835
+ continue
836
+ if isinstance(va, InstV) and isinstance(vb, InstV) and va.table is vb.table:
837
+ out[name] = va
838
+ continue
839
+ if va is None or vb is None:
840
+ keep = va if va is not None else vb
841
+ if isinstance(keep, (Ent, InstV, ResV, Sub, NS, RelV)):
842
+ out[name] = keep
843
+ elif isinstance(keep, Sel):
844
+ out[name] = keep
845
+ return out
846
+
847
+ def stmt(self, st: ast.stmt) -> None:
848
+ t = type(st)
849
+ if t is ast.Expr:
850
+ self.ev(st.value)
851
+ elif t is ast.Assign:
852
+ v = self.ev(st.value)
853
+ for target in st.targets:
854
+ self.bind(target, v, st.value)
855
+ elif t is ast.AnnAssign:
856
+ if st.value is not None:
857
+ v = self.ev(st.value)
858
+ self.bind(st.target, v if v is not None else self.ann(st.annotation), st.value)
859
+ elif t is ast.AugAssign:
860
+ self.use(st.value)
861
+ if isinstance(st.target, ast.Name):
862
+ self.env.pop(st.target.id, None)
863
+ elif t is ast.Return:
864
+ if st.value is not None:
865
+ v = self.ev(st.value)
866
+ self.returns.append(v)
867
+ self.consume(st.value, v, "returned")
868
+ for x in ([v] if isinstance(v, (Sel, Sub)) else (v.items if isinstance(v, TupV) else [])):
869
+ x = x.sel if isinstance(x, Sub) else x
870
+ if isinstance(x, Sel) and not x.query:
871
+ for r in x.roots:
872
+ self.cx.root_reason.setdefault(r, "statement returned to the caller: it is executed in a function we could not connect it to")
873
+ elif t is ast.If:
874
+ self.use(st.test)
875
+ pre = self.env
876
+ a = self._branch(st.body)
877
+ b = self._branch(st.orelse) if st.orelse else pre
878
+ if self._terminates(st.body):
879
+ self.env = dict(b)
880
+ elif st.orelse and self._terminates(st.orelse):
881
+ self.env = dict(a)
882
+ else:
883
+ self.env = self._merge(a, b)
884
+ elif t in (ast.For, ast.AsyncFor):
885
+ it = self.ev(st.iter)
886
+ elem = self.iterate(st.iter, it)
887
+ pre = self.env
888
+ self.env = dict(pre)
889
+ self.loop += 1
890
+ try:
891
+ self.bind(st.target, elem, None)
892
+ self.run(st.body)
893
+ finally:
894
+ self.loop -= 1
895
+ self.env = self._merge(self.env, pre)
896
+ self.run(st.orelse)
897
+ elif t is ast.While:
898
+ pre = self.env
899
+ self.env = dict(pre)
900
+ self.loop += 1
901
+ try:
902
+ self.use(st.test)
903
+ self.run(st.body)
904
+ finally:
905
+ self.loop -= 1
906
+ self.env = self._merge(self.env, pre)
907
+ elif t in (ast.With, ast.AsyncWith):
908
+ for item in st.items:
909
+ self.ev(item.context_expr)
910
+ if item.optional_vars is not None:
911
+ self.bind(item.optional_vars, None, None)
912
+ self.run(st.body)
913
+ elif t is ast.Try or t.__name__ == "TryStar":
914
+ self.run(st.body)
915
+ merged = self.env
916
+ for h in st.handlers:
917
+ if not self._terminates(h.body):
918
+ merged = self._merge(merged, self._branch(h.body))
919
+ self.env = dict(merged)
920
+ self.run(st.orelse)
921
+ self.run(st.finalbody)
922
+ elif t in (ast.FunctionDef, ast.AsyncFunctionDef):
923
+ self.nested.append(("func", st, self.cls if self.class_level else None))
924
+ elif t is ast.ClassDef:
925
+ owner = (self.cls.inner.get(st.name) if self.class_level else None) or \
926
+ (self.mod.classes.get(st.name) if self.func is None and self.cls is None else None)
927
+ if owner is None or owner.node is not st:
928
+ owner = Cls(self.mod, st)
929
+ self.nested.append(("class", st, owner))
930
+ elif t.__name__ == "Match":
931
+ self.use(st.subject)
932
+ merged = self.env
933
+ for case in st.cases:
934
+ merged = self._merge(merged, self._branch(case.body))
935
+ self.env = merged
936
+ elif t in (ast.Raise, ast.Assert, ast.Delete):
937
+ for child in ast.iter_child_nodes(st):
938
+ if isinstance(child, ast.expr):
939
+ self.use(child)
940
+
941
+ def bind(self, target: ast.AST, v, value_node) -> None:
942
+ if isinstance(target, ast.Name):
943
+ if isinstance(v, (Sel, Ent, Ex, RelV, Sub, InstV, ResV, NS, TupV)):
944
+ if isinstance(v, InstV) and not v.name:
945
+ v.name = target.id
946
+ self.env[target.id] = v
947
+ else:
948
+ self.env.pop(target.id, None)
949
+ elif isinstance(target, (ast.Tuple, ast.List)):
950
+ items = v.items if isinstance(v, TupV) else None
951
+ for i, el in enumerate(target.elts):
952
+ self.bind(el.value if isinstance(el, ast.Starred) else el, items[i] if items is not None and i < len(items) else None, None)
953
+ elif isinstance(target, (ast.Attribute, ast.Subscript)):
954
+ self.ev(target.value)
955
+
956
+ def use(self, node: ast.AST | None, how: str = ""):
957
+ if node is None:
958
+ return None
959
+ v = self.ev(node)
960
+ self.consume(node, v, how)
961
+ return v
962
+
963
+ def consume(self, node: ast.AST, v, how: str = "") -> None:
964
+ """A 1.x Query that is iterated, returned or handed on runs; a 2.0 statement is only a value until executed."""
965
+ if isinstance(v, Sel) and v.query and v.kind == "select":
966
+ note = ""
967
+ conf = None
968
+ if how == "returned":
969
+ note, conf = "Query returned to the caller, which may refine it before it runs", MEDIUM
970
+ elif how.startswith("passed"):
971
+ note, conf = f"Query {how}, which may refine it before it runs", MEDIUM
972
+ self.execute(node, v.add(Op("note"), conf, note) if note else v, share=v)
973
+ elif isinstance(v, Sel) and how.startswith("passed") and v.kind == "select" and not v.state["emitted"]:
974
+ # a statement handed to a helper that runs it (pagination, a repository `fetch(stmt)`)
975
+ self.execute(node, v.add(Op("note"), MEDIUM, f"statement {how}, which runs it and may add filters, ordering or paging"), share=v)
976
+
977
+ def iterate(self, node: ast.AST, v):
978
+ if isinstance(v, Sel) and v.query:
979
+ self.execute(node, v, share=v)
980
+ ent = self.single_entity(v)
981
+ return InstV(ent.table, origin=v, per_iter=self.loop + 1) if ent is not None else None
982
+ if isinstance(v, ResV):
983
+ e = v.elem
984
+ if isinstance(e, InstV):
985
+ return InstV(e.table, origin=e.origin, per_iter=self.loop + 1, conf=e.conf)
986
+ return None
987
+
988
+ # ---- expressions (Python level) ----------------------------------------------------------------------------
989
+ def ev(self, node: ast.AST | None):
990
+ if node is None:
991
+ return None
992
+ t = type(node)
993
+ if t is ast.Name:
994
+ if node.id in self.env:
995
+ return self.env[node.id]
996
+ return self.name_value(node.id)
997
+ if t is ast.Attribute:
998
+ return self.ev_attr(node)
999
+ if t is ast.Call:
1000
+ return self.ev_call(node)
1001
+ if t is ast.Constant:
1002
+ return None
1003
+ if t is ast.Await:
1004
+ return self.ev(node.value)
1005
+ if t is ast.Compare or (t is ast.BinOp and isinstance(node.op, (ast.BitAnd, ast.BitOr, ast.Add, ast.Sub, ast.Mult, ast.Div))) \
1006
+ or (t is ast.UnaryOp and isinstance(node.op, (ast.Invert, ast.USub))):
1007
+ return self.sx(node)
1008
+ if t is ast.Subscript:
1009
+ base = self.ev(node.value)
1010
+ if isinstance(base, Sel) and base.query and isinstance(node.slice, ast.Slice):
1011
+ lo = self.pv(node.slice.lower) if node.slice.lower is not None else None
1012
+ hi = self.pv(node.slice.upper) if node.slice.upper is not None else None
1013
+ return base.add(Op("slice", (lo, hi)))
1014
+ if isinstance(base, Ex) and base.sql.endswith(".c") is False and isinstance(base, Ex):
1015
+ return None
1016
+ self.use(node.slice)
1017
+ if isinstance(base, ResV):
1018
+ return base if isinstance(node.slice, ast.Slice) else base.elem
1019
+ return None
1020
+ if t in (ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp):
1021
+ saved = self.env
1022
+ self.env = dict(saved)
1023
+ n = 0
1024
+ try:
1025
+ for gen in node.generators:
1026
+ elem = self.iterate(gen.iter, self.ev(gen.iter))
1027
+ self.loop += 1
1028
+ n += 1
1029
+ self.bind(gen.target, elem, None)
1030
+ for c in gen.ifs:
1031
+ self.use(c)
1032
+ if t is ast.DictComp:
1033
+ self.use(node.key)
1034
+ self.use(node.value)
1035
+ else:
1036
+ self.use(node.elt)
1037
+ finally:
1038
+ self.loop -= n
1039
+ self.env = saved
1040
+ return None
1041
+ if t is ast.IfExp:
1042
+ self.use(node.test)
1043
+ a, b = self.ev(node.body), self.ev(node.orelse)
1044
+ return a if a is not None else b
1045
+ if t is ast.NamedExpr:
1046
+ v = self.ev(node.value)
1047
+ self.bind(node.target, v, None)
1048
+ return v
1049
+ if t is ast.Starred:
1050
+ return self.ev(node.value)
1051
+ if t is ast.Lambda:
1052
+ self.use(node.body)
1053
+ return None
1054
+ if t is ast.Tuple:
1055
+ vals = [self.ev(e) for e in node.elts]
1056
+ if any(isinstance(v, (Sel, Sub)) for v in vals):
1057
+ return TupV(vals)
1058
+ for e, v in zip(node.elts, vals):
1059
+ self.consume(e, v)
1060
+ return None
1061
+ for child in ast.iter_child_nodes(node):
1062
+ if isinstance(child, ast.expr):
1063
+ self.use(child)
1064
+ elif isinstance(child, ast.keyword):
1065
+ self.use(child.value)
1066
+ elif isinstance(child, ast.FormattedValue):
1067
+ self.use(child.value)
1068
+ return None
1069
+
1070
+ def name_value(self, name: str):
1071
+ cx = self.cx
1072
+ t = cx.index.entity(self.mod, name)
1073
+ if t is not None:
1074
+ return Ent(t)
1075
+ ext = cx.ext(self.mod, name)
1076
+ if ext.startswith(("sqlalchemy", "sqlmodel", "flask_sqlalchemy")):
1077
+ last = ext.split(".")[-1]
1078
+ if last == "func":
1079
+ return NS("func")
1080
+ if ext in ("sqlalchemy", "sqlalchemy.orm", "sqlalchemy.sql", "sqlmodel", "sqlalchemy.sql.expression",
1081
+ "sqlalchemy.dialects.postgresql", "sqlalchemy.dialects.mysql", "sqlalchemy.dialects.sqlite", "sqlalchemy.sql.functions"):
1082
+ return NS("sa")
1083
+ return None
1084
+
1085
+ def sa_name(self, node: ast.AST) -> str:
1086
+ """The SQLAlchemy function a callee names (`select`, `sa.select`, `orm.joinedload`), or ""."""
1087
+ if isinstance(node, ast.Name):
1088
+ if node.id in self.env:
1089
+ return ""
1090
+ ext = self.cx.ext(self.mod, node.id)
1091
+ return ext.split(".")[-1] if ext.startswith(("sqlalchemy", "sqlmodel")) else ""
1092
+ if isinstance(node, ast.Attribute):
1093
+ base = self.ev(node.value) if isinstance(node.value, ast.Name) else None
1094
+ if isinstance(base, NS) and base.kind == "sa":
1095
+ return node.attr
1096
+ return ""
1097
+
1098
+ def ev_attr(self, node: ast.Attribute):
1099
+ attr = node.attr
1100
+ base = self.ev(node.value)
1101
+ if isinstance(base, Ent):
1102
+ t = base.table
1103
+ if attr in ("c", "columns", "__table__"):
1104
+ return base
1105
+ if attr in t.rels:
1106
+ return RelV(base, t.rels[attr])
1107
+ c = t.col(attr)
1108
+ if c is not None:
1109
+ return Ex(f"{base.ref}.{c.name}", ((t, base.alias),))
1110
+ return None
1111
+ if isinstance(base, Sub):
1112
+ if attr in ("c", "columns"):
1113
+ return base
1114
+ if base.pseudo is None:
1115
+ inner = self.build(base.sel)[0]
1116
+ t = SATable(base.name, "")
1117
+ t.from_text = base.name if base.cte else f"({inner}) AS {base.name}"
1118
+ t.cte_text = f"{base.name} AS ({inner})" if base.cte else ""
1119
+ base.pseudo = t
1120
+ return Ex(f"{base.name}.{attr}", ((base.pseudo, ""),))
1121
+ if isinstance(base, NS):
1122
+ if base.kind == "sa" and attr == "func":
1123
+ return NS("func")
1124
+ if base.kind == "sa" and attr in ("orm", "sql", "expression", "dialects", "postgresql", "mysql", "sqlite", "functions"):
1125
+ return NS("sa")
1126
+ return None
1127
+ if isinstance(base, InstV):
1128
+ t = base.table
1129
+ if attr in t.rels and isinstance(node.ctx, ast.Load):
1130
+ return self.lazy(node, base, t.rels[attr])
1131
+ return None
1132
+ if isinstance(base, Ex) and attr in ("c",):
1133
+ return base
1134
+ if base is None and attr[:1].isupper():
1135
+ full = dotted(node)
1136
+ if full and full.split(".")[0] not in self.env:
1137
+ t = self.cx.index.entity(self.mod, full)
1138
+ if t is not None:
1139
+ return Ent(t)
1140
+ return None
1141
+
1142
+ # ---- SQL expressions ----------------------------------------------------------------------------------------
1143
+ def pv(self, node: ast.AST | None) -> str:
1144
+ """A Python value used inside SQL: a literal, or a run-time part."""
1145
+ ok, v = const(node)
1146
+ if ok and not isinstance(v, list):
1147
+ s = sql_literal(v)
1148
+ if s is not None:
1149
+ return s
1150
+ return marker(src(node)) if node is not None else "NULL"
1151
+
1152
+ def sx(self, node: ast.AST) -> Ex | None:
1153
+ """An AST expression as SQL when it is a SQLAlchemy expression; None when it is plain Python."""
1154
+ t = type(node)
1155
+ if t is ast.Compare and len(node.ops) == 1:
1156
+ l, r = self.sxv(node.left), self.sxv(node.comparators[0])
1157
+ if l is None and r is None:
1158
+ self.use(node.left)
1159
+ self.use(node.comparators[0])
1160
+ return None
1161
+ ls = l.sql if l is not None else self.pv(node.left)
1162
+ rs = r.sql if r is not None else self.pv(node.comparators[0])
1163
+ op = type(node.ops[0])
1164
+ froms = (l.froms if l else ()) + (r.froms if r else ())
1165
+ agg = bool((l and l.agg) or (r and r.agg))
1166
+ if op in (ast.Eq, ast.Is):
1167
+ return Ex(f"{ls} IS NULL" if rs == "NULL" else f"{ls} = {rs}", froms, agg)
1168
+ if op in (ast.NotEq, ast.IsNot):
1169
+ return Ex(f"{ls} IS NOT NULL" if rs == "NULL" else f"{ls} <> {rs}", froms, agg)
1170
+ sym = {ast.Lt: "<", ast.LtE: "<=", ast.Gt: ">", ast.GtE: ">="}.get(op)
1171
+ if sym:
1172
+ return Ex(f"{ls} {sym} {rs}", froms, agg)
1173
+ return None
1174
+ if t is ast.BinOp:
1175
+ l, r = self.sxv(node.left), self.sxv(node.right)
1176
+ if l is None and r is None:
1177
+ return None
1178
+ ls = l.sql if l is not None else self.pv(node.left)
1179
+ rs = r.sql if r is not None else self.pv(node.right)
1180
+ froms = (l.froms if l else ()) + (r.froms if r else ())
1181
+ agg = bool((l and l.agg) or (r and r.agg))
1182
+ if isinstance(node.op, ast.BitAnd):
1183
+ return Ex(f"({ls} AND {rs})", froms, agg)
1184
+ if isinstance(node.op, ast.BitOr):
1185
+ return Ex(f"({ls} OR {rs})", froms, agg)
1186
+ sym = {ast.Add: "+", ast.Sub: "-", ast.Mult: "*", ast.Div: "/"}.get(type(node.op))
1187
+ return Ex(f"({ls} {sym} {rs})", froms, agg) if sym else None
1188
+ if t is ast.UnaryOp:
1189
+ v = self.sxv(node.operand)
1190
+ if v is None:
1191
+ return None
1192
+ return Ex(f"NOT ({v.sql})" if isinstance(node.op, ast.Invert) else f"-{v.sql}", v.froms, v.agg)
1193
+ if isinstance(node, (ast.Compare, ast.BinOp, ast.UnaryOp)):
1194
+ for child in ast.iter_child_nodes(node): # `a < b < c`, `not x`: plain Python
1195
+ if isinstance(child, ast.expr):
1196
+ self.use(child)
1197
+ return None
1198
+ return self.sxv(node)
1199
+
1200
+ def sxv(self, node: ast.AST) -> Ex | None:
1201
+ """Like sx, but also evaluates names, attributes and calls to an expression."""
1202
+ if isinstance(node, (ast.Compare, ast.BinOp, ast.UnaryOp)):
1203
+ return self.sx(node)
1204
+ v = self.ev(node)
1205
+ return self.as_ex(v)
1206
+
1207
+ def as_ex(self, v) -> Ex | None:
1208
+ if isinstance(v, Ex):
1209
+ return v
1210
+ if isinstance(v, Sub):
1211
+ if v.scalar:
1212
+ return Ex("(" + self.build(v.sel)[0] + ")", ())
1213
+ return Ex(v.name, ())
1214
+ if isinstance(v, Sel) and v.kind == "select":
1215
+ self.absorb(v)
1216
+ return Ex("(" + self.build(v)[0] + ")", ())
1217
+ if isinstance(v, Sel) and v.kind == "exists":
1218
+ self.absorb(v)
1219
+ inner = Sel(v.ops, v.roots, v.conf, v.notes, v.query, "select", v.table)
1220
+ return Ex("EXISTS (" + self.build(inner)[0] + ")", ())
1221
+ return None
1222
+
1223
+ def arg_sql(self, node: ast.AST) -> tuple[str, tuple, bool]:
1224
+ """An argument of an SQL function or operator: an expression when it is one, else a literal or run-time part."""
1225
+ if isinstance(node, ast.Starred):
1226
+ self.use(node.value)
1227
+ return marker(src(node)), (), False
1228
+ v = self.sxv(node)
1229
+ if v is not None:
1230
+ return v.sql, v.froms, v.agg
1231
+ return self.pv(node), (), False
1232
+
1233
+ def absorb(self, sel: Sel) -> None:
1234
+ for r in sel.roots:
1235
+ self.cx.done_roots.add(r) if self.emit and False else None
1236
+ self._absorbed = getattr(self, "_absorbed", frozenset()) | sel.roots
1237
+
1238
+ _absorbed: frozenset = frozenset()
1239
+
1240
+ # ---- calls -----------------------------------------------------------------------------------------------------
1241
+ def root(self, call: ast.Call) -> frozenset:
1242
+ nid = id(call)
1243
+ if nid not in self.cx.seen_roots:
1244
+ self.cx.seen_roots[nid] = f"{self.mod.rel}:{call.lineno}"
1245
+ self.cx.stats.seen += 1
1246
+ return frozenset([nid])
1247
+
1248
+ def cols_of(self, v) -> list[Ex] | None:
1249
+ if isinstance(v, Ent):
1250
+ t = v.table
1251
+ if not t.cols:
1252
+ return [Ex(f"{v.ref}.*", ((t, v.alias),), ent=v)]
1253
+ return [Ex(f"{v.ref}.{c.name}", ((t, v.alias),), ent=v) for c in t.cols.values()]
1254
+ if isinstance(v, Sub):
1255
+ return [Ex(f"{v.name}.*", ())]
1256
+ e = self.as_ex(v)
1257
+ return [e] if e is not None else None
1258
+
1259
+ def select_args(self, call: ast.Call) -> tuple[list, int, str]:
1260
+ cols, conf, note = [], HIGH, ""
1261
+ args = list(call.args)
1262
+ if len(args) == 1 and isinstance(args[0], (ast.List, ast.Tuple)):
1263
+ args = list(args[0].elts) # 1.x `select([a, b])`
1264
+ for a in args:
1265
+ if isinstance(a, ast.Starred):
1266
+ self.use(a.value)
1267
+ cols.append(Ex(marker(src(a)), ()))
1268
+ conf = MEDIUM
1269
+ continue
1270
+ v = self.sxv(a) if isinstance(a, (ast.Compare, ast.BinOp, ast.UnaryOp)) else self.ev(a)
1271
+ got = self.cols_of(v)
1272
+ if got is None:
1273
+ cols.append(Ex(marker(src(a)), ()))
1274
+ conf, note = MEDIUM, "a selected column could not be resolved and is shown as a run-time part"
1275
+ else:
1276
+ cols.extend(got)
1277
+ return cols, conf, note
1278
+
1279
+ def ev_call(self, call: ast.Call):
1280
+ fn = call.func
1281
+ cx = self.cx
1282
+ name = self.sa_name(fn)
1283
+ if name:
1284
+ return self.sa_call(call, name)
1285
+ if isinstance(fn, ast.Attribute):
1286
+ method = fn.attr
1287
+ recv = self.ev(fn.value)
1288
+ if isinstance(recv, NS) and recv.kind == "func":
1289
+ return self.func_call(call, method)
1290
+ if isinstance(recv, NS):
1291
+ return self.sa_call(call, method)
1292
+ if isinstance(recv, Sel):
1293
+ return self.sel_call(call, recv, method)
1294
+ if isinstance(recv, Ex):
1295
+ return self.ex_call(call, recv, method)
1296
+ if isinstance(recv, RelV):
1297
+ return self.rel_call(call, recv, method)
1298
+ if isinstance(recv, Ent):
1299
+ return self.ent_call(call, recv, method)
1300
+ if isinstance(recv, Sub):
1301
+ if method in ("alias",):
1302
+ return recv
1303
+ self.args_use(call)
1304
+ return None
1305
+ if isinstance(recv, ResV):
1306
+ self.args_use(call)
1307
+ if method in ("first", "one", "one_or_none", "scalar_one", "scalar_one_or_none", "scalar", "fetchone"):
1308
+ e = recv.elem
1309
+ return InstV(e.table, origin=e.origin, per_iter=self.loop, conf=e.conf) if isinstance(e, InstV) else None
1310
+ return recv if method in RESULT else None
1311
+ if isinstance(recv, InstV):
1312
+ self.args_use(call)
1313
+ return None
1314
+ # an untyped receiver: a session, a connection, a repository
1315
+ if method in EXEC and call.args:
1316
+ return self.exec_call(call, method)
1317
+ if method == "query" and (call.args or True):
1318
+ return self.query_call(call)
1319
+ if method in ("get", "get_one") and len(call.args) >= 2:
1320
+ ent = self.ev(call.args[0])
1321
+ if isinstance(ent, Ent) and ent.table.pks():
1322
+ return self.session_get(call, ent)
1323
+ if method in ("add", "add_all", "merge", "delete", "refresh", "bulk_save_objects", "bulk_insert_mappings",
1324
+ "bulk_update_mappings") and call.args:
1325
+ got = self.session_write(call, method)
1326
+ if got is not NotImplemented:
1327
+ return got
1328
+ return self.args_use(call, f"passed to {method}()")
1329
+ if isinstance(fn, ast.Name):
1330
+ nm = fn.id
1331
+ v = self.env.get(nm)
1332
+ if isinstance(v, Ent) or (v is None and nm not in self.env and cx.index.entity(self.mod, nm) is not None):
1333
+ ent = v if isinstance(v, Ent) else Ent(cx.index.entity(self.mod, nm))
1334
+ self.args_use(call)
1335
+ return InstV(ent.table, per_iter=self.loop) if ent.table.cls is not None else None
1336
+ if nm in ("list", "tuple", "set", "sorted", "iter", "reversed") and call.args:
1337
+ first = self.ev(call.args[0])
1338
+ if isinstance(first, Sel) and first.query:
1339
+ self.execute(call.args[0], first, share=first)
1340
+ ent = self.single_entity(first)
1341
+ return ResV(InstV(ent.table, origin=first) if ent is not None else None)
1342
+ return first if isinstance(first, ResV) else None
1343
+ if nm not in self.env:
1344
+ got = cx.project.resolve(self.mod, nm)
1345
+ if got is not None and got[0] == "func":
1346
+ return self.call_function(call, got[1], got[2])
1347
+ return self.args_use(call, f"passed to {nm}()")
1348
+ self.use(fn)
1349
+ self.args_use(call)
1350
+ return None
1351
+
1352
+ def args_use(self, call: ast.Call, how: str = ""):
1353
+ """Evaluate a call's arguments. A 2.0 statement handed to code we cannot read is either run there (a session
1354
+ or connection goes with it, or the receiver is one) or refined and handed back: then the result is the
1355
+ statement with what was added as a run-time part."""
1356
+ vals = [(a, self.ev(a)) for a in call.args] + [(k.value, self.ev(k.value)) for k in call.keywords]
1357
+ stmts = [(n, v) for n, v in vals if isinstance(v, Sel) and v.kind == "select" and not v.query]
1358
+ refined = None
1359
+ if how.startswith("passed") and len(stmts) == 1 and not _has_session(call):
1360
+ callee = how[len("passed to "):]
1361
+ refined = stmts[0][1].add(Op("where", [Ex(marker(f"what {callee} adds"), ())]), MEDIUM,
1362
+ f"refined by {callee}, which we could not read: what it adds is a run-time part")
1363
+ refined.state = stmts[0][1].state
1364
+ for n, v in vals:
1365
+ if refined is not None and v is stmts[0][1]:
1366
+ continue
1367
+ self.consume(n, v, how)
1368
+ return refined
1369
+
1370
+ def call_function(self, call: ast.Call, mod: Mod, fn_def, cls: Cls | None = None):
1371
+ """A helper of the project that builds and returns a statement: read once for what it returns."""
1372
+ cx = self.cx
1373
+ pos = [self.ev(a) for a in call.args]
1374
+ kws = {k.arg: self.ev(k.value) for k in call.keywords if k.arg}
1375
+ typed = any(isinstance(v, (Sel, Ent, Sub)) for v in pos + list(kws.values()))
1376
+ if self.depth >= SETTINGS["orm_helper_depth"] or id(fn_def) in cx.stack:
1377
+ got = None
1378
+ else:
1379
+ key = id(fn_def)
1380
+ if not typed and key in cx.cache:
1381
+ got = cx.cache[key]
1382
+ else:
1383
+ names = [a.arg for a in list(fn_def.args.posonlyargs) + list(fn_def.args.args)]
1384
+ if cls is not None and names and names[0] in ("self", "cls"):
1385
+ names = names[1:]
1386
+ preset = {names[i]: v for i, v in enumerate(pos) if i < len(names) and v is not None}
1387
+ preset.update({k: v for k, v in kws.items() if v is not None})
1388
+ cx.stack.append(id(fn_def))
1389
+ try:
1390
+ w = SAWalker(cx, mod, cls, "", func=fn_def, emit=False, depth=self.depth + 1, preset=preset)
1391
+ try:
1392
+ w.run(fn_def.body)
1393
+ except RecursionError:
1394
+ pass
1395
+ vals = [v for v in w.returns if v is not None]
1396
+ got = vals[0] if len(vals) == 1 and len(w.returns) == 1 else None
1397
+ if got is None and vals and all(isinstance(v, TupV) for v in vals):
1398
+ got = vals[0]
1399
+ if got is None and vals and all(isinstance(v, Sel) for v in vals):
1400
+ first = vals[0]
1401
+ got = Sel(first.ops, frozenset().union(*[v.roots for v in vals]), max(first.conf, MEDIUM),
1402
+ first.notes + ("built by a helper with several return paths: the first is shown",), first.query, first.kind, first.table)
1403
+ finally:
1404
+ cx.stack.pop()
1405
+ if not typed:
1406
+ cx.cache[key] = got
1407
+ absorbed = isinstance(got, (Sel, Sub, TupV))
1408
+ for node, v in list(zip(call.args, pos)) + [(k.value, kws.get(k.arg)) for k in call.keywords if k.arg]:
1409
+ if isinstance(v, Sel) and not absorbed:
1410
+ self.consume(node, v, f"passed to {fn_def.name}()")
1411
+ if isinstance(got, Sel):
1412
+ got = Sel(got.ops, got.roots, got.conf, got.notes, got.query, got.kind, got.table)
1413
+ elif isinstance(got, TupV):
1414
+ got = TupV([Sel(x.ops, x.roots, x.conf, x.notes, x.query, x.kind, x.table) if isinstance(x, Sel) else x for x in got.items])
1415
+ if got is None and not absorbed:
1416
+ passed = [v for v in pos + list(kws.values()) if isinstance(v, Sel) and v.kind == "select" and not v.query]
1417
+ if len(passed) == 1 and not _has_session(call):
1418
+ return passed[0] # consumed above with the note that the helper may refine it
1419
+ if got is None and fn_def.returns is not None:
1420
+ got = SAWalker(cx, mod, None, "", emit=False).ann(fn_def.returns)
1421
+ if isinstance(got, InstV):
1422
+ got.per_iter = self.loop
1423
+ return got
1424
+
1425
+ # -- constructs -------------------------------------------------------------------------------------------
1426
+ def sa_call(self, call: ast.Call, name: str):
1427
+ args = call.args
1428
+ if name == "select":
1429
+ cols, conf, note = self.select_args(call)
1430
+ return Sel((Op("cols", cols),), self.root(call) | self._take(), conf, (note,) if note else ())
1431
+ if name in ("insert", "update", "delete") and args:
1432
+ ent = self.ev(args[0])
1433
+ if isinstance(ent, Ent):
1434
+ return Sel((), self.root(call), HIGH, (), False, name, ent.table)
1435
+ if self.emit:
1436
+ self.root(call)
1437
+ self.cx.root_reason.setdefault(id(call), f"{name}() of a table that is not a model or Table() found in the repository")
1438
+ return None
1439
+ if name in ("and_", "or_"):
1440
+ parts = [self.arg_sql(a) for a in args]
1441
+ parts = [p for p in parts if p[0]]
1442
+ if not parts:
1443
+ return Ex("TRUE" if name == "and_" else "FALSE", ())
1444
+ joiner = " AND " if name == "and_" else " OR "
1445
+ return Ex("(" + joiner.join(p[0] for p in parts) + ")", sum((p[1] for p in parts), ()), any(p[2] for p in parts))
1446
+ if name == "not_" and args:
1447
+ s, f, a = self.arg_sql(args[0])
1448
+ return Ex(f"NOT ({s})", f, a)
1449
+ if name in ("desc", "asc", "nullslast", "nullsfirst", "nulls_last", "nulls_first") and args:
1450
+ s, f, a = self.arg_sql(args[0])
1451
+ suffix = {"desc": " DESC", "asc": " ASC", "nullslast": " NULLS LAST", "nulls_last": " NULLS LAST",
1452
+ "nullsfirst": " NULLS FIRST", "nulls_first": " NULLS FIRST"}[name]
1453
+ return Ex(s + suffix, f, a)
1454
+ if name == "distinct" and args:
1455
+ s, f, a = self.arg_sql(args[0])
1456
+ return Ex(f"DISTINCT {s}", f, a)
1457
+ if name == "text" and args:
1458
+ s = str_const(args[0])
1459
+ return Ex(s if s is not None else marker(src(args[0])), ())
1460
+ if name in ("literal", "bindparam") and args:
1461
+ return Ex(self.pv(args[0]) if name == "literal" else marker(str_const(args[0]) or src(args[0])), ())
1462
+ if name in ("literal_column", "column") and args and str_const(args[0]):
1463
+ return Ex(str_const(args[0]), ())
1464
+ if name in ("null", "true", "false"):
1465
+ return Ex(name.upper(), ())
1466
+ if name == "tuple_":
1467
+ parts = [self.arg_sql(a) for a in args]
1468
+ return Ex("(" + ", ".join(p[0] for p in parts) + ")", sum((p[1] for p in parts), ()))
1469
+ if name == "exists":
1470
+ if args:
1471
+ v = self.ev(args[0])
1472
+ if isinstance(v, Sel):
1473
+ self.absorb(v)
1474
+ return Ex("EXISTS (" + self.build(v)[0] + ")", ())
1475
+ parts = [self.arg_sql(a) for a in args]
1476
+ sel = Sel((Op("cols", [Ex(p[0], p[1]) for p in parts]),), self.root(call), HIGH, ())
1477
+ sel.kind = "exists"
1478
+ return sel
1479
+ sel = Sel((Op("cols", [Ex("1", ())]),), self.root(call), HIGH, ())
1480
+ sel.kind = "exists"
1481
+ return sel
1482
+ if name == "cast" and len(args) >= 2:
1483
+ s, f, a = self.arg_sql(args[0])
1484
+ tn = TYPES.get(((dotted(args[1].func) if isinstance(args[1], ast.Call) else dotted(args[1])) or "").split(".")[-1])
1485
+ return Ex(f"CAST({s} AS {tn})" if tn else s, f, a)
1486
+ if name == "case":
1487
+ whens = []
1488
+ froms: tuple = ()
1489
+ for a in args:
1490
+ items = a.elts if isinstance(a, (ast.Tuple, ast.List)) else None
1491
+ if items and len(items) == 2 and not isinstance(items[0], (ast.Tuple, ast.List)):
1492
+ c, v = self.arg_sql(items[0]), self.arg_sql(items[1])
1493
+ whens.append(f"WHEN {c[0]} THEN {v[0]}")
1494
+ froms += c[1] + v[1]
1495
+ elif items:
1496
+ for pair in items:
1497
+ if isinstance(pair, (ast.Tuple, ast.List)) and len(pair.elts) == 2:
1498
+ c, v = self.arg_sql(pair.elts[0]), self.arg_sql(pair.elts[1])
1499
+ whens.append(f"WHEN {c[0]} THEN {v[0]}")
1500
+ froms += c[1] + v[1]
1501
+ if not whens:
1502
+ self.args_use(call)
1503
+ return Ex(marker(src(call)), ())
1504
+ el = kwarg(call, "else_")
1505
+ tail = f" ELSE {self.arg_sql(el)[0]}" if el is not None else ""
1506
+ return Ex("CASE " + " ".join(whens) + tail + " END", froms)
1507
+ if name == "aliased" and args:
1508
+ v = self.ev(args[0])
1509
+ if isinstance(v, Ent):
1510
+ nm = str_const(kwarg(call, "name")) or (str_const(args[1]) if len(args) > 1 else None)
1511
+ if not nm:
1512
+ self.cx.anon += 1
1513
+ nm = f"{v.table.name}_{1 + sum(1 for x in self.env.values() if isinstance(x, Ent) and x.table is v.table and x.alias)}"
1514
+ return Ent(v.table, nm)
1515
+ if isinstance(v, Sub):
1516
+ return v
1517
+ return None
1518
+ if name in EAGER or name in OTHER_LOADS:
1519
+ return self.load_option(call, name)
1520
+ if name == "extract" and len(args) >= 2 and str_const(args[0]):
1521
+ s, f, a = self.arg_sql(args[1])
1522
+ return Ex(f"EXTRACT({str_const(args[0]).upper()} FROM {s})", f, a)
1523
+ if name in ("union", "union_all", "intersect", "except_") and args:
1524
+ v = self.ev(args[0])
1525
+ for a in args[1:]:
1526
+ o = self.ev(a)
1527
+ if isinstance(o, Sel):
1528
+ self.absorb(o)
1529
+ if isinstance(v, Sel):
1530
+ return v.add(Op("setop", name), MEDIUM, f"{name}(): only the first statement is shown", roots=self._take())
1531
+ return None
1532
+ if name in ("table", "Table") and args and str_const(args[0]):
1533
+ # a lightweight table written in place (migrations: `sa.table("task_instance", sa.column("id"), ...)`)
1534
+ t = SATable(str_const(args[0]), f"{self.mod.rel}:{call.lineno}")
1535
+ for a in args[1:]:
1536
+ if isinstance(a, ast.Call) and (dotted(a.func) or "").split(".")[-1] in ("column", "Column") and a.args and str_const(a.args[0]):
1537
+ t.cols[str_const(a.args[0])] = SACol(str_const(a.args[0]), str_const(a.args[0]))
1538
+ return Ent(t)
1539
+ if name in ("Session", "AsyncSession", "sessionmaker", "create_engine", "create_async_engine", "MetaData", "Table", "Column",
1540
+ "Index", "ForeignKey", "relationship", "mapped_column", "inspect", "object_session", "event"):
1541
+ self.args_use(call)
1542
+ return None
1543
+ if name == "func":
1544
+ return NS("func")
1545
+ self.args_use(call)
1546
+ return None
1547
+
1548
+ def _take(self) -> frozenset:
1549
+ got = self._absorbed
1550
+ self._absorbed = frozenset()
1551
+ return got
1552
+
1553
+ def func_call(self, call: ast.Call, name: str) -> Ex:
1554
+ parts = [self.arg_sql(a) for a in call.args]
1555
+ froms = sum((p[1] for p in parts), ())
1556
+ agg = name.lower() in ("count", "sum", "avg", "min", "max", "array_agg", "string_agg", "group_concat", "json_agg", "jsonb_agg",
1557
+ "bool_or", "bool_and", "every", "percentile_cont", "percentile_disc", "stddev", "variance")
1558
+ if name.lower() == "count" and not parts:
1559
+ return Ex("COUNT(*)", (), True)
1560
+ if name.lower() == "now":
1561
+ return Ex("CURRENT_TIMESTAMP", ())
1562
+ return Ex(f"{name.upper()}({', '.join(p[0] for p in parts)})", froms, agg or any(p[2] for p in parts))
1563
+
1564
+ def ex_call(self, call: ast.Call, e: Ex, m: str):
1565
+ args = call.args
1566
+ one = (lambda: self.arg_sql(args[0])) if args else None
1567
+ if m == "label" and args:
1568
+ return Ex(e.sql, e.froms, e.agg, str_const(args[0]) or "", e.ent)
1569
+ if m in ("desc", "asc", "nulls_last", "nulls_first", "nullslast", "nullsfirst"):
1570
+ return Ex(e.sql + {"desc": " DESC", "asc": " ASC"}.get(m, " NULLS LAST" if "last" in m else " NULLS FIRST"), e.froms, e.agg)
1571
+ if m in ("in_", "not_in", "notin_") and args:
1572
+ neg = "NOT " if m != "in_" else ""
1573
+ a = args[0]
1574
+ ok, v = const(a)
1575
+ if ok and isinstance(v, list) and all(sql_literal(x) is not None for x in v):
1576
+ return Ex(f"{e.sql} {neg}IN ({', '.join(sql_literal(x) for x in v) or 'NULL'})", e.froms, e.agg)
1577
+ val = self.ev(a)
1578
+ if isinstance(val, Sub):
1579
+ return Ex(f"{e.sql} {neg}IN (SELECT * FROM {val.name})" if val.cte else f"{e.sql} {neg}IN ({self.build(val.sel)[0]})", e.froms, e.agg)
1580
+ if isinstance(val, Sel):
1581
+ self.absorb(val)
1582
+ return Ex(f"{e.sql} {neg}IN ({self.build(val)[0]})", e.froms, e.agg)
1583
+ return Ex(f"{e.sql} {neg}IN ({marker(src(a))})", e.froms, e.agg)
1584
+ if m in ("is_", "is_not", "isnot") and args:
1585
+ s = self.arg_sql(args[0])[0]
1586
+ return Ex(f"{e.sql} IS {'NOT ' if m != 'is_' else ''}{s}", e.froms, e.agg)
1587
+ if m in ("like", "not_like", "notlike") and args:
1588
+ return Ex(f"{e.sql} {'NOT ' if m != 'like' else ''}LIKE {one()[0]}", e.froms, e.agg)
1589
+ if m in ("ilike", "not_ilike", "notilike") and args:
1590
+ return Ex(f"LOWER({e.sql}) {'NOT ' if m != 'ilike' else ''}LIKE LOWER({one()[0]})", e.froms, e.agg)
1591
+ if m in ("contains", "startswith", "endswith", "icontains", "istartswith", "iendswith") and args:
1592
+ v = one()[0]
1593
+ base = m.lstrip("i") if m[0] == "i" else m
1594
+ pat = {"contains": f"'%' || {v} || '%'", "startswith": f"{v} || '%'", "endswith": f"'%' || {v}"}[base]
1595
+ return Ex(f"LOWER({e.sql}) LIKE LOWER({pat})" if m[0] == "i" else f"{e.sql} LIKE {pat}", e.froms, e.agg)
1596
+ if m == "between" and len(args) >= 2:
1597
+ return Ex(f"{e.sql} BETWEEN {self.arg_sql(args[0])[0]} AND {self.arg_sql(args[1])[0]}", e.froms, e.agg)
1598
+ if m in ("is_distinct_from", "isnot_distinct_from", "is_not_distinct_from") and args:
1599
+ return Ex(f"{e.sql} IS {'NOT ' if 'not' in m else ''}DISTINCT FROM {one()[0]}", e.froms, e.agg)
1600
+ if m == "cast" and args:
1601
+ tn = TYPES.get(((dotted(args[0].func) if isinstance(args[0], ast.Call) else dotted(args[0])) or "").split(".")[-1])
1602
+ return Ex(f"CAST({e.sql} AS {tn})" if tn else e.sql, e.froms, e.agg)
1603
+ if m in ("distinct",):
1604
+ return Ex(f"DISTINCT {e.sql}", e.froms, e.agg)
1605
+ if m in ("self_group", "scalar_subquery", "as_scalar", "collate", "astext", "as_string", "as_integer", "as_boolean", "as_float",
1606
+ "expression", "element", "prefix_with"):
1607
+ return e
1608
+ if m == "filter" and args: # func.count(x).filter(cond)
1609
+ c = self.arg_sql(args[0])
1610
+ return Ex(f"{e.sql} FILTER (WHERE {c[0]})", e.froms + c[1], e.agg)
1611
+ if m == "over":
1612
+ self.args_use(call)
1613
+ parts = []
1614
+ pb, ob = kwarg(call, "partition_by"), kwarg(call, "order_by")
1615
+ for kw_, node in (("PARTITION BY", pb), ("ORDER BY", ob)):
1616
+ if node is not None:
1617
+ items = node.elts if isinstance(node, (ast.List, ast.Tuple)) else [node]
1618
+ parts.append(kw_ + " " + ", ".join(self.arg_sql(i)[0] for i in items))
1619
+ return Ex(f"{e.sql} OVER ({' '.join(parts)})", e.froms, False)
1620
+ if m in ("op", "bool_op") and args and str_const(args[0]):
1621
+ return Ex(e.sql + " " + str_const(args[0]), e.froms, e.agg) # the next call supplies the right side
1622
+ if m in ("any_", "all_"):
1623
+ return Ex(f"{m[:-1].upper()}({e.sql})", e.froms, e.agg)
1624
+ if m in ("__eq__", "__ne__") and args:
1625
+ return Ex(f"{e.sql} {'=' if m == '__eq__' else '<>'} {one()[0]}", e.froms, e.agg)
1626
+ self.args_use(call)
1627
+ return Ex(marker(src(call)), e.froms, e.agg)
1628
+
1629
+ def rel_call(self, call: ast.Call, rv: RelV, m: str):
1630
+ """`Parent.children.any(cond)` / `Child.parent.has(cond)`: an EXISTS on the related table."""
1631
+ if m in ("any", "has"):
1632
+ j = self.cx.index.rel_join(rv.rel)
1633
+ crit = [self.arg_sql(a)[0] for a in call.args]
1634
+ for k in call.keywords:
1635
+ if k.arg and j is not None and j[0].col(k.arg) is not None:
1636
+ crit.append(f"{j[0].name}.{j[0].col(k.arg).name} = {self.pv(k.value)}")
1637
+ if j is None:
1638
+ return Ex("EXISTS (" + marker(src(call)) + ")", ((rv.ent.table, rv.ent.alias),))
1639
+ target, pairs, _ = j
1640
+ on = [f"{rv.ent.ref}.{a} = {target.name}.{b}" for a, b in pairs]
1641
+ return Ex(f"EXISTS (SELECT 1 FROM {target.name} WHERE {' AND '.join(on + crit)})", ((rv.ent.table, rv.ent.alias),))
1642
+ if m in ("of_type", "and_"):
1643
+ return rv
1644
+ self.args_use(call)
1645
+ return None
1646
+
1647
+ def ent_call(self, call: ast.Call, ent: Ent, m: str):
1648
+ """Core `table.select() / insert() / update() / delete()`, `Model.query` style helpers, `alias()`."""
1649
+ if m == "select":
1650
+ sel = Sel((Op("cols", self.cols_of(ent)),), self.root(call))
1651
+ for a in call.args:
1652
+ c = self.arg_sql(a)
1653
+ sel = sel.add(Op("where", [Ex(c[0], c[1])]))
1654
+ return sel
1655
+ if m in ("insert", "update", "delete"):
1656
+ return Sel((), self.root(call), HIGH, (), False, m, ent.table)
1657
+ if m == "alias":
1658
+ return Ent(ent.table, str_const(call.args[0]) if call.args and str_const(call.args[0]) else f"{ent.table.name}_1")
1659
+ if m in ("join", "outerjoin") and call.args:
1660
+ self.args_use(call)
1661
+ return ent
1662
+ if ent.table.cls is not None:
1663
+ found = self.cx.project.find_method(ent.table.cls, m)
1664
+ if found is not None:
1665
+ return self.call_function(call, found[0].mod, found[1], found[0])
1666
+ self.args_use(call)
1667
+ return None
1668
+
1669
+ def load_option(self, call: ast.Call, name: str):
1670
+ items = []
1671
+ for a in call.args:
1672
+ v = self.ev(a)
1673
+ if isinstance(v, RelV):
1674
+ items.append(v)
1675
+ for k in call.keywords:
1676
+ self.use(k.value)
1677
+ return ("load", name, items)
1678
+
1679
+ # -- chained methods on a statement ------------------------------------------------------------------------
1680
+ def conds(self, call: ast.Call) -> list[Ex]:
1681
+ out = []
1682
+ for a in call.args:
1683
+ if isinstance(a, ast.Starred):
1684
+ self.use(a.value)
1685
+ out.append(Ex(marker(src(a)), ()))
1686
+ continue
1687
+ s, f, agg = self.arg_sql(a)
1688
+ out.append(Ex(s, f, agg))
1689
+ return out
1690
+
1691
+ def primary(self, sel: Sel) -> Ent | None:
1692
+ """The entity filter_by() and relationship joins refer to: the last joined entity, else the first selected."""
1693
+ last = None
1694
+ for op in sel.ops:
1695
+ if op.kind == "join" and isinstance(op.data[1], Ent):
1696
+ last = op.data[1]
1697
+ if last is not None:
1698
+ return last
1699
+ return self.first_entity(sel)
1700
+
1701
+ def first_entity(self, sel: Sel) -> Ent | None:
1702
+ if sel.table is not None:
1703
+ return Ent(sel.table)
1704
+ for op in sel.ops:
1705
+ if op.kind == "cols":
1706
+ for c in op.data:
1707
+ if c.ent is not None:
1708
+ return c.ent
1709
+ for c in op.data:
1710
+ if c.froms:
1711
+ return Ent(c.froms[0][0], c.froms[0][1])
1712
+ if op.kind == "from" and isinstance(op.data, Ent):
1713
+ return op.data
1714
+ return None
1715
+
1716
+ def single_entity(self, sel: Sel) -> Ent | None:
1717
+ ents = []
1718
+ for op in sel.ops:
1719
+ if op.kind == "cols":
1720
+ ents = []
1721
+ for c in op.data:
1722
+ if c.ent is None:
1723
+ return None
1724
+ if c.ent.table not in [e.table for e in ents]:
1725
+ ents.append(c.ent)
1726
+ return ents[0] if len(ents) == 1 and ents[0].table.cls is not None else None
1727
+
1728
+ def sel_call(self, call: ast.Call, sel: Sel, m: str):
1729
+ args = call.args
1730
+ if sel.kind in ("insert", "update", "delete"):
1731
+ return self.dml_call(call, sel, m)
1732
+ if m in ("where", "filter", "having", "where_all"):
1733
+ c = self.conds(call)
1734
+ return sel.add(Op("having" if m == "having" else "where", c, line=call.lineno), roots=self._take()) if c else sel
1735
+ if m == "filter_by":
1736
+ ent = self.primary(sel)
1737
+ out = []
1738
+ conf = None
1739
+ for k in call.keywords:
1740
+ if k.arg is None:
1741
+ out.append(Ex(marker("**" + src(k.value)), ()))
1742
+ continue
1743
+ col = ent.table.col(k.arg) if ent is not None else None
1744
+ if col is None:
1745
+ out.append(Ex(marker(f"{k.arg} = {src(k.value)}"), ()))
1746
+ conf = MEDIUM
1747
+ else:
1748
+ v = self.pv(k.value)
1749
+ out.append(Ex(f"{ent.ref}.{col.name} IS NULL" if v == "NULL" else f"{ent.ref}.{col.name} = {v}", ((ent.table, ent.alias),)))
1750
+ return sel.add(Op("where", out), conf) if out else sel
1751
+ if m in ("join", "outerjoin", "join_from", "outerjoin_from"):
1752
+ jargs = list(args)
1753
+ left = None
1754
+ if m.endswith("_from") and jargs:
1755
+ left = self.ev(jargs.pop(0))
1756
+ if not jargs:
1757
+ return sel
1758
+ target = self.ev(jargs[0])
1759
+ on = None
1760
+ on_node = jargs[1] if len(jargs) > 1 else kwarg(call, "onclause")
1761
+ if on_node is not None:
1762
+ s = self.arg_sql(on_node)
1763
+ on = s[0]
1764
+ if isinstance(self.ev(on_node), RelV):
1765
+ on = None
1766
+ target_rel = self.ev(on_node)
1767
+ return sel.add(Op("join", (self._outer(call, m), target if isinstance(target, Ent) else target_rel, None, target_rel)))
1768
+ ok, isouter = const(kwarg(call, "isouter"))
1769
+ ok2, full = const(kwarg(call, "full"))
1770
+ kind = "FULL OUTER JOIN" if ok2 and full else ("LEFT OUTER JOIN" if m.startswith("outer") or (ok and isouter) else "JOIN")
1771
+ if isinstance(target, (Ent, RelV, Sub)):
1772
+ _ = left
1773
+ return sel.add(Op("join", (kind, target, on, target if isinstance(target, RelV) else None), line=call.lineno), roots=self._take())
1774
+ return sel.add(Op("join", (kind, None, marker(src(jargs[0])), None)), MEDIUM, "a join target could not be resolved and is shown as a run-time part")
1775
+ if m == "select_from" and args:
1776
+ v = self.ev(args[0])
1777
+ if isinstance(v, (Ent, Sub)):
1778
+ return sel.add(Op("from", v))
1779
+ return sel.add(Op("from", marker(src(args[0]))), MEDIUM)
1780
+ if m in ("order_by", "group_by"):
1781
+ if m == "order_by" and len(args) == 1 and isinstance(args[0], ast.Constant) and args[0].value is None:
1782
+ return sel.add(Op("order", None))
1783
+ items = []
1784
+ for a in args:
1785
+ if isinstance(a, ast.Starred):
1786
+ self.use(a.value)
1787
+ items.append(marker(src(a)))
1788
+ continue
1789
+ s = str_const(a)
1790
+ if s is not None:
1791
+ ent = self.primary(sel)
1792
+ col = ent.table.col(s.split()[0]) if ent is not None else None
1793
+ items.append((f"{ent.ref}.{col.name}" + s[len(s.split()[0]):]) if col is not None else s)
1794
+ continue
1795
+ v = self.ev(a) if not isinstance(a, (ast.Compare, ast.BinOp, ast.UnaryOp)) else self.sx(a)
1796
+ if isinstance(v, Ent):
1797
+ items.extend(f"{v.ref}.{c.name}" for c in v.table.pks()) if m == "group_by" else items.append(marker(src(a)))
1798
+ continue
1799
+ e = self.as_ex(v)
1800
+ items.append(e.sql if e is not None else marker(src(a)))
1801
+ return sel.add(Op("order" if m == "order_by" else "group", items, line=call.lineno))
1802
+ if m in ("limit", "offset") and args:
1803
+ return sel.add(Op(m, self.pv(args[0])))
1804
+ if m == "slice" and len(args) >= 2:
1805
+ return sel.add(Op("slice", (self.pv(args[0]), self.pv(args[1]))))
1806
+ if m == "distinct":
1807
+ on = [self.arg_sql(a)[0] for a in args]
1808
+ return sel.add(Op("distinct", on))
1809
+ if m == "options":
1810
+ loads = []
1811
+ for a in args:
1812
+ v = self.ev(a)
1813
+ if isinstance(v, tuple) and v and v[0] == "load":
1814
+ loads.append(v)
1815
+ return sel.add(Op("options", loads)) if loads else sel
1816
+ if m in ("with_only_columns", "with_entities", "add_columns"):
1817
+ cols, conf, note = self.select_args(call)
1818
+ return sel.add(Op("addcols" if m == "add_columns" else "cols", cols), conf, note)
1819
+ if m == "with_for_update":
1820
+ ok, skip = const(kwarg(call, "skip_locked"))
1821
+ ok2, nowait = const(kwarg(call, "nowait"))
1822
+ return sel.add(Op("lock", " FOR UPDATE" + (" SKIP LOCKED" if ok and skip else "") + (" NOWAIT" if ok2 and nowait else "")))
1823
+ if m in ("subquery", "cte", "alias", "lateral"):
1824
+ nm = (str_const(args[0]) if args else None) or str_const(kwarg(call, "name"))
1825
+ if not nm:
1826
+ nm = "anon_1"
1827
+ self.absorb(sel)
1828
+ return Sub(sel, nm, cte=m == "cte")
1829
+ if m in ("scalar_subquery", "as_scalar", "label") and not (sel.query and m == "label" and False):
1830
+ self.absorb(sel)
1831
+ return Sub(sel, "anon_1", scalar=True)
1832
+ if m == "exists":
1833
+ if sel.query and not args:
1834
+ self.absorb(sel)
1835
+ return Ex("EXISTS (" + self.build(sel)[0] + ")", ())
1836
+ self.absorb(sel)
1837
+ return Ex("EXISTS (" + self.build(sel)[0] + ")", ())
1838
+ if m == "correlate" or m == "correlate_except":
1839
+ self.args_use(call)
1840
+ return sel
1841
+ if m in ("union", "union_all", "intersect", "except_"):
1842
+ for a in args:
1843
+ o = self.ev(a)
1844
+ if isinstance(o, Sel):
1845
+ self.absorb(o)
1846
+ return sel.add(Op("setop", m), MEDIUM, f"{m}(): only the first statement is shown", roots=self._take())
1847
+ if sel.query:
1848
+ got = self.query_terminal(call, sel, m)
1849
+ if got is not NotImplemented:
1850
+ return got
1851
+ if m in SEL_METHODS:
1852
+ self.args_use(call)
1853
+ return sel
1854
+ self.args_use(call)
1855
+ for r in sel.roots:
1856
+ self.cx.root_reason.setdefault(r, "a method we do not know was called on the statement")
1857
+ return None
1858
+
1859
+ @staticmethod
1860
+ def _outer(call: ast.Call, m: str) -> str:
1861
+ ok, isouter = const(kwarg(call, "isouter"))
1862
+ return "LEFT OUTER JOIN" if m.startswith("outer") or (ok and isouter) else "JOIN"
1863
+
1864
+ def dml_call(self, call: ast.Call, sel: Sel, m: str):
1865
+ if m in ("where", "filter"):
1866
+ c = self.conds(call)
1867
+ return sel.add(Op("where", c), roots=self._take()) if c else sel
1868
+ if m == "filter_by":
1869
+ out = []
1870
+ for k in call.keywords:
1871
+ col = sel.table.col(k.arg) if k.arg else None
1872
+ out.append(Ex(f"{sel.table.name}.{col.name} = {self.pv(k.value)}" if col is not None else marker(f"{k.arg} = {src(k.value)}"), ()))
1873
+ return sel.add(Op("where", out))
1874
+ if m == "values":
1875
+ pairs = []
1876
+ conf = None
1877
+ for k in call.keywords:
1878
+ if k.arg is None:
1879
+ pairs.append((marker("**" + src(k.value)), ""))
1880
+ conf = MEDIUM
1881
+ continue
1882
+ col = sel.table.col(k.arg)
1883
+ pairs.append((col.name if col is not None else k.arg, self.arg_sql(k.value)[0]))
1884
+ for a in call.args:
1885
+ if isinstance(a, ast.Dict):
1886
+ for kk, vv in zip(a.keys, a.values):
1887
+ nm = str_const(kk) if kk is not None else None
1888
+ if nm is None and kk is not None:
1889
+ e = self.as_ex(self.ev(kk))
1890
+ nm = e.sql.split(".")[-1] if e is not None else None
1891
+ if nm is None:
1892
+ pairs.append((marker(src(kk) if kk is not None else "**"), ""))
1893
+ conf = MEDIUM
1894
+ else:
1895
+ col = sel.table.col(nm)
1896
+ pairs.append((col.name if col is not None else nm, self.arg_sql(vv)[0]))
1897
+ else:
1898
+ self.use(a)
1899
+ pairs.append((marker(src(a)), ""))
1900
+ conf = MEDIUM
1901
+ return sel.add(Op("values", pairs), conf)
1902
+ if m == "returning":
1903
+ parts = [self.arg_sql(a)[0] if not isinstance(self.ev(a), Ent) else f"{sel.table.name}.*" for a in call.args]
1904
+ return sel.add(Op("returning", parts))
1905
+ if m in ("on_conflict_do_update", "on_conflict_do_nothing", "on_duplicate_key_update"):
1906
+ self.args_use(call)
1907
+ return sel.add(Op("conflict", m))
1908
+ if m == "from_select":
1909
+ self.args_use(call)
1910
+ return sel.add(Op("values", [(marker("columns of a SELECT"), "")]), MEDIUM)
1911
+ if m in SEL_METHODS:
1912
+ self.args_use(call)
1913
+ return sel
1914
+ self.args_use(call)
1915
+ return sel
1916
+
1917
+ # -- executions -----------------------------------------------------------------------------------------------
1918
+ def exec_call(self, call: ast.Call, method: str):
1919
+ arg = call.args[0]
1920
+ v = self.ev(arg)
1921
+ for a in call.args[1:]:
1922
+ self.use(a)
1923
+ for k in call.keywords:
1924
+ self.use(k.value)
1925
+ if isinstance(v, Sub):
1926
+ v = v.sel
1927
+ if isinstance(v, Sel):
1928
+ if v.kind == "exists":
1929
+ v = Sel(v.ops, v.roots, v.conf, v.notes, v.query, "select", v.table)
1930
+ self.execute(call, v, share=v, params=len(call.args) > 1)
1931
+ ent = self.single_entity(v) if v.kind == "select" else None
1932
+ elem = InstV(ent.table, origin=v) if ent is not None else None
1933
+ if method in ("scalar",):
1934
+ return InstV(ent.table, origin=v, per_iter=self.loop) if ent is not None else None
1935
+ return ResV(elem, v)
1936
+ if isinstance(v, Ex):
1937
+ return None
1938
+ cx = self.cx
1939
+ if not self.emit:
1940
+ return None
1941
+ looks_text = isinstance(arg, (ast.Constant, ast.JoinedStr)) or (isinstance(arg, ast.Call) and (dotted(arg.func) or "").split(".")[-1]
1942
+ in ("text", "format", "join", "DDL", "CreateTable", "DropTable"))
1943
+ if not looks_text and isinstance(arg, (ast.Name, ast.Call, ast.Attribute)) and ("sqlalchemy" in self.mod.text or "sqlmodel" in self.mod.text) \
1944
+ and id(call) not in cx.counted and not re.search(r"sql|query_str|text|raw|ddl", src(arg), re.I):
1945
+ cx.counted.add(id(call))
1946
+ cx.stats.seen += 1
1947
+ cx.stats.miss("execute() of a statement built outside the function (a parameter, an attribute or another module's helper)",
1948
+ f"{self.mod.rel}:{call.lineno}")
1949
+ return None
1950
+
1951
+ def query_call(self, call: ast.Call):
1952
+ """`session.query(...)`: only when its arguments are mapped things."""
1953
+ if not call.args:
1954
+ return None
1955
+ vals = []
1956
+ for a in call.args:
1957
+ v = self.sxv(a) if isinstance(a, (ast.Compare, ast.BinOp, ast.UnaryOp)) else self.ev(a)
1958
+ vals.append(v)
1959
+ if not any(isinstance(v, (Ent, Ex, Sub)) for v in vals):
1960
+ cx = self.cx
1961
+ if self.emit and ("sqlalchemy" in self.mod.text or "sqlmodel" in self.mod.text) and id(call) not in cx.counted \
1962
+ and re.search(r"session|db\b|\bs\b", src(call.func), re.I):
1963
+ cx.counted.add(id(call))
1964
+ cx.stats.seen += 1
1965
+ cx.stats.miss("query() of something that is not a model or column found in the repository", f"{self.mod.rel}:{call.lineno}")
1966
+ return None
1967
+ cols = []
1968
+ conf = HIGH
1969
+ for a, v in zip(call.args, vals):
1970
+ got = self.cols_of(v)
1971
+ if got is None:
1972
+ cols.append(Ex(marker(src(a)), ()))
1973
+ conf = MEDIUM
1974
+ else:
1975
+ cols.extend(got)
1976
+ return Sel((Op("cols", cols),), self.root(call) | self._take(), conf, (), True)
1977
+
1978
+ def query_terminal(self, call: ast.Call, sel: Sel, m: str):
1979
+ args = call.args
1980
+ ent = self.single_entity(sel)
1981
+ inst = (lambda: InstV(ent.table, origin=sel, per_iter=self.loop)) if ent is not None else (lambda: None)
1982
+ if m in ("all", "fetchall"):
1983
+ self.execute(call, sel, share=sel)
1984
+ return ResV(InstV(ent.table, origin=sel) if ent is not None else None, sel)
1985
+ if m in ("first", "one", "one_or_none", "scalar", "scalar_one", "scalar_one_or_none"):
1986
+ q = sel.add(Op("limit", "1")) if m == "first" else sel
1987
+ self.execute(call, q, operation=m)
1988
+ return inst()
1989
+ if m == "count":
1990
+ sql, notes, conf = self.build(sel)
1991
+ self.site(call, sel, f"SELECT COUNT(*) AS count_1 FROM ({sql}) AS anon_1", "count", conf, notes)
1992
+ return None
1993
+ if m == "get" and args and ent is not None and ent.table.pks():
1994
+ pk = ent.table.pks()[0]
1995
+ q = sel.add(Op("where", [Ex(f"{ent.ref}.{pk.name} = {self.pv(args[0])}", ())]))
1996
+ self.execute(call, q, operation="get")
1997
+ return inst()
1998
+ if m in ("delete", "update") and ent is not None or (m in ("delete", "update") and self.first_entity(sel) is not None):
1999
+ e = ent or self.first_entity(sel)
2000
+ d = Sel(tuple(o for o in sel.ops if o.kind == "where"), sel.roots, sel.conf, sel.notes, False, m, e.table)
2001
+ if m == "update" and args:
2002
+ fake = ast.Call(func=call.func, args=[args[0]], keywords=[])
2003
+ ast.copy_location(fake, call)
2004
+ d = self.dml_call(fake, d, "values")
2005
+ self.execute(call, d)
2006
+ return None
2007
+ if m == "exists":
2008
+ return NotImplemented
2009
+ if m in ("yield_per", "populate_existing", "enable_eagerloads", "execution_options", "autoflush", "params"):
2010
+ self.args_use(call)
2011
+ return sel
2012
+ if m == "paginate":
2013
+ self.args_use(call)
2014
+ q = sel.add(Op("limit", marker("per_page"))).add(Op("offset", marker("(page - 1) * per_page")))
2015
+ self.execute(call, q, operation="select")
2016
+ return ResV(InstV(ent.table, origin=sel) if ent is not None else None, sel)
2017
+ return NotImplemented
2018
+
2019
+ def session_get(self, call: ast.Call, ent: Ent):
2020
+ t = ent.table
2021
+ pks = t.pks()
2022
+ sel = Sel((Op("cols", self.cols_of(ent)),), self.root(call))
2023
+ ok, v = const(call.args[1])
2024
+ if len(pks) == 1:
2025
+ sel = sel.add(Op("where", [Ex(f"{ent.ref}.{pks[0].name} = {self.pv(call.args[1])}", ())]))
2026
+ else:
2027
+ items = call.args[1].elts if isinstance(call.args[1], (ast.Tuple, ast.List)) and len(call.args[1].elts) == len(pks) else None
2028
+ sel = sel.add(Op("where", [Ex(f"{ent.ref}.{p.name} = " + (self.pv(items[i]) if items else marker(f"{src(call.args[1])}[{i}]")), ())
2029
+ for i, p in enumerate(pks)]))
2030
+ for k in call.keywords:
2031
+ if k.arg == "options":
2032
+ loads = []
2033
+ for a in (k.value.elts if isinstance(k.value, (ast.List, ast.Tuple)) else []):
2034
+ lv = self.ev(a)
2035
+ if isinstance(lv, tuple) and lv and lv[0] == "load":
2036
+ loads.append(lv)
2037
+ if loads:
2038
+ sel = sel.add(Op("options", loads))
2039
+ self.execute(call, sel, operation="get", extra_notes=["session.get(): no statement is sent when the object is already in the session"])
2040
+ return InstV(t, origin=sel, per_iter=self.loop)
2041
+
2042
+ def session_write(self, call: ast.Call, method: str):
2043
+ cx = self.cx
2044
+ arg = call.args[0]
2045
+ v = self.ev(arg)
2046
+ if method in ("bulk_insert_mappings", "bulk_update_mappings") and isinstance(v, Ent):
2047
+ t = v.table
2048
+ for a in call.args[1:]:
2049
+ self.use(a)
2050
+ if method == "bulk_insert_mappings":
2051
+ sql = f"INSERT INTO {t.name} ({marker('keys of each mapping')}) VALUES ({marker('one row per mapping')})"
2052
+ else:
2053
+ pk = " AND ".join(f"{t.name}.{p.name} = {marker(p.name)}" for p in t.pks()) or marker("primary key")
2054
+ sql = f"UPDATE {t.name} SET {marker('column')} = {marker('value')} WHERE {pk}"
2055
+ self.raw(call, t, sql, "insert" if "insert" in method else "update", MEDIUM, [f"{method}(): one statement per batch"])
2056
+ return None
2057
+ table = v.table if isinstance(v, InstV) else None
2058
+ if table is None and isinstance(v, ResV) and isinstance(v.elem, InstV):
2059
+ table = v.elem.table
2060
+ if table is None and isinstance(arg, (ast.List, ast.Tuple)) and arg.elts:
2061
+ first = self.ev(arg.elts[0])
2062
+ table = first.table if isinstance(first, InstV) else None
2063
+ if table is None:
2064
+ return NotImplemented
2065
+ who = unmark(v.name) if isinstance(v, InstV) and v.name else table.name
2066
+ if method in ("add", "add_all", "bulk_save_objects"):
2067
+ cols = [c.name for c in table.cols.values()]
2068
+ if not cols:
2069
+ return None
2070
+ sql = f"INSERT INTO {table.name} ({', '.join(cols)}) VALUES ({', '.join(marker(f'{who}.{c}') for c in cols)})"
2071
+ note = "INSERT sent at the next flush; an UPDATE instead when the object is already persistent"
2072
+ if isinstance(v, InstV) and v.origin is not None:
2073
+ return None # an object loaded from the database: add() is a no-op until it changes
2074
+ self.raw(call, table, sql, "insert", MEDIUM, [f"session.{method}(): {note}"])
2075
+ return None
2076
+ pk = " AND ".join(f"{table.name}.{p.name} = {marker(f'{who}.{p.name}')}" for p in table.pks())
2077
+ if not pk:
2078
+ return None
2079
+ if method == "delete":
2080
+ self.raw(call, table, f"DELETE FROM {table.name} WHERE {pk}", "delete", MEDIUM, ["session.delete(): DELETE sent at the next flush"])
2081
+ elif method in ("refresh", "merge"):
2082
+ cols = ", ".join(f"{table.name}.{c.name}" for c in table.cols.values())
2083
+ note = "session.refresh()" if method == "refresh" else "session.merge(): the lookup by primary key; an INSERT or UPDATE follows at flush"
2084
+ self.raw(call, table, f"SELECT {cols} FROM {table.name} WHERE {pk}", "get", MEDIUM, [note])
2085
+ _ = cx
2086
+ return None
2087
+
2088
+ # -- lazy loads -----------------------------------------------------------------------------------------------
2089
+ def _covered(self, inst: InstV, rel: SARel) -> bool:
2090
+ if rel.lazy in ("joined", "selectin", "subquery", "immediate", "raise", "raise_on_sql", "noload", "dynamic", "write_only") \
2091
+ or rel.lazy is False:
2092
+ return True
2093
+ o = inst.origin
2094
+ if o is None:
2095
+ return False
2096
+ for op in o.ops:
2097
+ if op.kind == "options":
2098
+ for _, name, items in op.data:
2099
+ if name in EAGER and any(r.rel is rel or (r.rel.attr == rel.attr and r.ent.table is rel.owner) for r in items):
2100
+ return True
2101
+ return False
2102
+
2103
+ def lazy(self, node: ast.Attribute, inst: InstV, rel: SARel):
2104
+ cx = self.cx
2105
+ target = cx.index.rel_target(rel)
2106
+ child = InstV(target, origin=None, per_iter=inst.per_iter, name=(inst.name + "." if inst.name else "") + rel.attr,
2107
+ conf=max(inst.conf, MEDIUM)) if target is not None else None
2108
+ j = cx.index.rel_join(rel)
2109
+ many = j is not None and j[2] == "o2m"
2110
+ out = ResV(child) if many and child is not None else child
2111
+ if not SETTINGS["orm_lazy_loads"] or not self.emit or not (inst.per_iter and self.loop >= inst.per_iter):
2112
+ return out
2113
+ if self._covered(inst, rel) or j is None or inst.name == "self":
2114
+ return out
2115
+ key = (inst.name.split(".")[0], rel.attr, id(inst.table))
2116
+ if key in self.lazy_seen:
2117
+ return out
2118
+ self.lazy_seen.add(key)
2119
+ tgt, pairs, direction = j
2120
+ who = unmark(inst.name or inst.table.name)
2121
+ cols = ", ".join(f"{tgt.name}.{c.name}" for c in tgt.cols.values()) or f"{tgt.name}.*"
2122
+ where = " AND ".join(f"{tgt.name}.{b} = {marker(f'{who}.{a}')}" for a, b in pairs)
2123
+ if inst.origin is not None:
2124
+ conf, why = MEDIUM, (f"lazy load of relationship `{rel.attr}` for each row: the statement iterated here has no "
2125
+ "joinedload/selectinload for it and the relationship is declared lazy")
2126
+ else:
2127
+ conf, why = LOW, (f"lazy load of relationship `{rel.attr}`; assumed: the instances were loaded without an eager option for it "
2128
+ "(they were loaded outside this function)")
2129
+ if direction == "m2o":
2130
+ why += "; no statement is sent for a row whose related object is already in the session"
2131
+ self.raw(node, tgt, f"SELECT {cols} FROM {tgt.name} WHERE {where}", "lazy_load", conf, [why], in_loop=True)
2132
+ cx.lazy += 1
2133
+ return out
2134
+
2135
+ # ---- building SQL ------------------------------------------------------------------------------------------
2136
+ def build(self, sel: Sel) -> tuple[str, list[str], int]:
2137
+ notes = [n for n in sel.notes if n]
2138
+ conf = sel.conf
2139
+ cx = self.cx
2140
+ if sel.kind in ("insert", "update", "delete"):
2141
+ return self.build_dml(sel, notes, conf)
2142
+ cols: list[Ex] = []
2143
+ froms: list = [] # Ent | Sub | str
2144
+ joins: list[tuple] = []
2145
+ where: list[str] = []
2146
+ having: list[str] = []
2147
+ order: list[str] | None = None
2148
+ group: list[str] = []
2149
+ limit = offset = None
2150
+ distinct = None
2151
+ lock = ""
2152
+ where_froms: list = []
2153
+ loads: list = []
2154
+ conditional: list[str] = []
2155
+ for op in sel.ops:
2156
+ k, d = op.kind, op.data
2157
+ if op.optional and k not in ("where", "having", "note"):
2158
+ conditional.append(k)
2159
+ if k == "cols":
2160
+ cols = list(d)
2161
+ elif k == "addcols":
2162
+ cols += list(d)
2163
+ elif k in ("where", "having"):
2164
+ for e in d:
2165
+ text = marker("optional: " + unmark(e.sql)) if op.optional else e.sql
2166
+ (having if k == "having" else where).append(text)
2167
+ where_froms += list(e.froms)
2168
+ if op.optional:
2169
+ conditional.append("filter")
2170
+ elif k == "from":
2171
+ froms.append(d)
2172
+ elif k == "join":
2173
+ kind, target, on, rel = d
2174
+ joins.append((kind, target, on, rel, op.optional))
2175
+ elif k == "order":
2176
+ order = list(d) if d is not None else None
2177
+ if op.optional and d:
2178
+ order = [marker("optional: " + ", ".join(unmark(x) for x in d))]
2179
+ elif k == "group":
2180
+ group += list(d)
2181
+ elif k == "limit":
2182
+ limit = d
2183
+ elif k == "offset":
2184
+ offset = d
2185
+ elif k == "slice":
2186
+ lo, hi = d
2187
+ offset = lo if lo not in (None, "0") else offset
2188
+ limit = hi if lo in (None, "0") or hi is None else (str(int(hi) - int(lo)) if hi.isdigit() and lo.isdigit() else marker(f"{unmark(hi)} - {unmark(lo)}"))
2189
+ elif k == "distinct":
2190
+ distinct = d
2191
+ elif k == "lock":
2192
+ lock = d
2193
+ elif k == "options":
2194
+ loads += d
2195
+ # FROM: the explicit select_from, else the tables the selected columns name, minus join targets
2196
+ joined = set()
2197
+ join_sql = []
2198
+ base: list = list(froms)
2199
+ col_tables = []
2200
+ for c in cols:
2201
+ for f in c.froms:
2202
+ if f not in col_tables:
2203
+ col_tables.append(f)
2204
+ left_ent = None
2205
+ if base:
2206
+ left_ent = base[0] if isinstance(base[0], Ent) else None
2207
+ elif col_tables:
2208
+ left_ent = Ent(col_tables[0][0], col_tables[0][1])
2209
+ prev: Ent | None = left_ent
2210
+ for kind, target, on, rel, optional in joins:
2211
+ tsql = None
2212
+ tent = None
2213
+ if isinstance(target, RelV):
2214
+ rel = target
2215
+ tt = cx.index.rel_target(target.rel)
2216
+ tent = Ent(tt) if tt is not None else None
2217
+ elif isinstance(target, Ent):
2218
+ tent = target
2219
+ elif isinstance(target, Sub):
2220
+ tsql = (target.name if target.cte else f"({self.build(target.sel)[0]}) AS {target.name}")
2221
+ if tent is not None:
2222
+ tsql = tent.from_sql
2223
+ joined.add((tent.table, tent.alias))
2224
+ if tsql is None:
2225
+ tsql = marker("join target")
2226
+ conf = max(conf, MEDIUM)
2227
+ if on is None:
2228
+ on = self.join_on(prev, left_ent, tent, rel, [Ent(t, a) for t, a in col_tables] + [x for x in base if isinstance(x, Ent)]
2229
+ + [Ent(t, a) for t, a in joined])
2230
+ if on is None:
2231
+ on = marker("join condition")
2232
+ conf = max(conf, MEDIUM)
2233
+ notes.append("a join condition could not be derived from the foreign keys and is shown as a run-time part")
2234
+ join_sql.append(f" {kind} {tsql} ON {on}")
2235
+ if optional:
2236
+ notes.append("a join is applied only on some run-time condition")
2237
+ conf = max(conf, MEDIUM)
2238
+ if tent is not None:
2239
+ prev = tent
2240
+ from_parts = []
2241
+ if base:
2242
+ for b in base:
2243
+ from_parts.append(b.from_sql if isinstance(b, Ent) else (b if isinstance(b, str) else
2244
+ (b.name if b.cte else f"({self.build(b.sel)[0]}) AS {b.name}")))
2245
+ else:
2246
+ for t, a in col_tables:
2247
+ if (t, a) not in joined:
2248
+ from_parts.append(Ent(t, a).from_sql)
2249
+ named = {(b.table, b.alias) for b in base if isinstance(b, Ent)} | joined | {f for f in col_tables}
2250
+ for f in where_froms:
2251
+ if f not in named and not base:
2252
+ named.add(f)
2253
+ from_parts.append(Ent(f[0], f[1]).from_sql)
2254
+ # eager loads in the same statement
2255
+ extra_cols: list[str] = []
2256
+ for _, name, items in loads:
2257
+ if name != "joinedload":
2258
+ continue
2259
+ for rv in items:
2260
+ j = cx.index.rel_join(rv.rel)
2261
+ if j is None:
2262
+ notes.append(f"joinedload({rv.rel.attr}): the join could not be derived")
2263
+ conf = max(conf, MEDIUM)
2264
+ continue
2265
+ tgt, pairs, _ = j
2266
+ alias = f"{tgt.name}_1"
2267
+ join_sql.append(f" LEFT OUTER JOIN {tgt.name} {alias} ON " + " AND ".join(f"{rv.ent.ref}.{a} = {alias}.{b}" for a, b in pairs))
2268
+ extra_cols += [f"{alias}.{c.name}" for c in tgt.cols.values()]
2269
+ col_sql = []
2270
+ for c in cols:
2271
+ col_sql.append(f"{c.sql} AS {c.label}" if c.label else c.sql)
2272
+ col_sql += extra_cols
2273
+ head = "SELECT "
2274
+ if distinct is not None:
2275
+ head += "DISTINCT " + (f"ON ({', '.join(distinct)}) " if distinct else "")
2276
+ sql = head + (", ".join(col_sql) or "1")
2277
+ if from_parts:
2278
+ sql += " FROM " + ", ".join(from_parts)
2279
+ sql += "".join(join_sql)
2280
+ if where:
2281
+ sql += " WHERE " + " AND ".join(where)
2282
+ if group:
2283
+ sql += " GROUP BY " + ", ".join(group)
2284
+ if having:
2285
+ sql += " HAVING " + " AND ".join(having)
2286
+ if order:
2287
+ sql += " ORDER BY " + ", ".join(order)
2288
+ if limit is not None:
2289
+ sql += f" LIMIT {limit}"
2290
+ if offset is not None:
2291
+ sql += f" OFFSET {offset}"
2292
+ sql += lock
2293
+ if sel.kind == "exists":
2294
+ sql = f"SELECT EXISTS ({sql})"
2295
+ ctes = list(dict.fromkeys(t.cte_text for t, _ in named if getattr(t, "cte_text", "")))
2296
+ for _, target, _, _, _ in joins:
2297
+ if isinstance(target, Sub) and target.cte:
2298
+ text = f"{target.name} AS ({self.build(target.sel)[0]})"
2299
+ if text not in ctes:
2300
+ ctes.append(text)
2301
+ if ctes:
2302
+ sql = "WITH " + ", ".join(ctes) + " " + sql
2303
+ if conditional:
2304
+ conf = max(conf, MEDIUM)
2305
+ notes.append("applied only on some run-time condition: " + ", ".join(dict.fromkeys(conditional)))
2306
+ return sql, notes, conf
2307
+
2308
+ def join_on(self, prev: Ent | None, left: Ent | None, target: Ent | None, rel, known: list) -> str | None:
2309
+ cx = self.cx
2310
+ if isinstance(rel, RelV):
2311
+ j = cx.index.rel_join(rel.rel)
2312
+ if j is not None:
2313
+ tgt, pairs, _ = j
2314
+ ref = target.ref if target is not None else tgt.name
2315
+ return " AND ".join(f"{rel.ent.ref}.{a} = {ref}.{b}" for a, b in pairs)
2316
+ sec = rel.rel.secondary
2317
+ return None if not sec else None
2318
+ if target is None:
2319
+ return None
2320
+ cands = []
2321
+ for e in ([prev] if prev is not None else []) + ([left] if left is not None else []) + known:
2322
+ if e is not None and e not in cands and not (e.table is target.table and e.alias == target.alias):
2323
+ cands.append(e)
2324
+ for e in cands:
2325
+ for c in e.table.cols.values():
2326
+ if c.fk and c.fk.split(".")[-2:-1] == [target.table.name]:
2327
+ return f"{e.ref}.{c.name} = {target.ref}.{c.fk.split('.')[-1]}"
2328
+ for c in target.table.cols.values():
2329
+ if c.fk and c.fk.split(".")[-2:-1] == [e.table.name]:
2330
+ return f"{target.ref}.{c.name} = {e.ref}.{c.fk.split('.')[-1]}"
2331
+ return None
2332
+
2333
+ def build_dml(self, sel: Sel, notes: list, conf: int) -> tuple[str, list[str], int]:
2334
+ t = sel.table
2335
+ where, values, returning, conflict = [], [], [], ""
2336
+ for op in sel.ops:
2337
+ if op.kind == "where":
2338
+ where += [marker("optional: " + unmark(e.sql)) if op.optional else e.sql for e in op.data]
2339
+ elif op.kind == "values":
2340
+ values += op.data
2341
+ elif op.kind == "returning":
2342
+ returning += op.data
2343
+ elif op.kind == "conflict":
2344
+ conflict = op.data
2345
+ if sel.kind == "insert":
2346
+ if values:
2347
+ cols = ", ".join(c for c, _ in values)
2348
+ vals = ", ".join(v if v else marker("value") for _, v in values)
2349
+ else:
2350
+ cols = ", ".join(c.name for c in t.cols.values()) or marker("columns")
2351
+ vals = marker("parameters passed to execute()")
2352
+ notes.append("insert() without values(): the columns come from the parameters at execution; the table's columns are shown")
2353
+ conf = max(conf, MEDIUM)
2354
+ sql = f"INSERT INTO {t.name} ({cols}) VALUES ({vals})"
2355
+ if conflict:
2356
+ sql += " ON CONFLICT " + marker(conflict) if "conflict" in conflict else " ON DUPLICATE KEY UPDATE " + marker("assignments")
2357
+ elif sel.kind == "update":
2358
+ sets = ", ".join(f"{c} = {v}" if v else f"{c} = {marker('value')}" for c, v in values) or \
2359
+ f"{marker('column')} = {marker('parameters passed to execute()')}"
2360
+ sql = f"UPDATE {t.name} SET {sets}"
2361
+ if where:
2362
+ sql += " WHERE " + " AND ".join(where)
2363
+ else:
2364
+ sql = f"DELETE FROM {t.name}"
2365
+ if where:
2366
+ sql += " WHERE " + " AND ".join(where)
2367
+ if returning:
2368
+ sql += " RETURNING " + ", ".join(returning)
2369
+ return sql, notes, conf
2370
+
2371
+ # ---- emission --------------------------------------------------------------------------------------------------
2372
+ def execute(self, node: ast.AST, sel: Sel, share: Sel | None = None, operation: str = "", params: bool = False,
2373
+ extra_notes: list | None = None) -> None:
2374
+ holder = share or sel
2375
+ if holder.state["emitted"] and self.emit:
2376
+ return
2377
+ if self.emit:
2378
+ holder.state["emitted"] = True
2379
+ sql, notes, conf = self.build(sel)
2380
+ if sel.kind in ("select", "exists") and not _TABLE_NAMED.search(sql):
2381
+ # nothing in the statement names a table we know: not emitted
2382
+ for r in sel.roots:
2383
+ self.cx.root_reason.setdefault(r, "the selected entity is not a model or Table() found in the repository")
2384
+ return
2385
+ op = operation or {"select": "select", "exists": "exists"}.get(sel.kind, sel.kind)
2386
+ self.site(node, sel, sql, op, conf, notes + (extra_notes or []))
2387
+ if sel.kind != "select" or not self.emit:
2388
+ return
2389
+ # one more statement per selectinload / subqueryload relation; relationships declared eager too
2390
+ loads = []
2391
+ for o in sel.ops:
2392
+ if o.kind == "options":
2393
+ for _, name, items in o.data:
2394
+ if name in ("selectinload", "subqueryload", "immediateload"):
2395
+ loads += [(name, rv.rel, o.optional) for rv in items]
2396
+ ent = self.single_entity(sel)
2397
+ if ent is not None:
2398
+ named = {id(r) for _, r, _ in loads}
2399
+ for rel in ent.table.rels.values():
2400
+ if rel.lazy in ("selectin", "subquery", "immediate") and id(rel) not in named:
2401
+ loads.append((rel.lazy + " (declared on the relationship)", rel, False))
2402
+ for name, rel, optional in loads:
2403
+ j = self.cx.index.rel_join(rel)
2404
+ if j is None:
2405
+ sj = self.cx.index.secondary_join(rel)
2406
+ if sj is None:
2407
+ self.cx.stats.miss("eager-load relationship whose join could not be derived (no foreign key found)",
2408
+ f"{self.mod.rel}:{node.lineno}")
2409
+ continue
2410
+ tgt, sec, own_pairs, tgt_pairs = sj
2411
+ cols = ", ".join(f"{tgt.name}.{c.name}" for c in tgt.cols.values()) or f"{tgt.name}.*"
2412
+ on = " AND ".join(f"{sec.name}.{a} = {tgt.name}.{b}" for a, b in tgt_pairs)
2413
+ cond = " AND ".join(f"{sec.name}.{a} IN ({marker(f'{rel.owner.name}.{b} of the rows above')})" for a, b in own_pairs)
2414
+ note = f"{name}({rel.attr}): one IN query per relationship through the association table, after the main statement"
2415
+ self.cx.out.emit(self.mod, node, self.symbol, f"SELECT {cols} FROM {tgt.name} JOIN {sec.name} ON {on} WHERE {cond}",
2416
+ sink=_sink(node), in_loop=self.loop > 0, model=tgt.name, operation="eager_load",
2417
+ confidence=CONF[max(conf, MEDIUM if optional else conf)], notes=note)
2418
+ continue
2419
+ tgt, pairs, direction = j
2420
+ cols = ", ".join(f"{tgt.name}.{c.name}" for c in tgt.cols.values()) or f"{tgt.name}.*"
2421
+ owner = rel.owner.name
2422
+ cond = " AND ".join(f"{tgt.name}.{b} IN ({marker(f'{owner}.{a} of the rows above')})" for a, b in pairs)
2423
+ note = f"{name}({rel.attr}): one IN query per relationship, after the main statement"
2424
+ if optional:
2425
+ note += "; applied only on some run-time condition"
2426
+ self.cx.out.emit(self.mod, node, self.symbol, f"SELECT {cols} FROM {tgt.name} WHERE {cond}", sink=_sink(node), in_loop=self.loop > 0,
2427
+ model=tgt.name, operation="eager_load", confidence=CONF[max(conf, MEDIUM if optional else conf)], notes=note)
2428
+
2429
+ def site(self, node: ast.AST, sel: Sel, sql: str, operation: str, conf: int, notes: list) -> None:
2430
+ cx = self.cx
2431
+ if not self.emit:
2432
+ return
2433
+ for r in sel.roots | self._take():
2434
+ cx.done_roots.add(r)
2435
+ ent = self.first_entity(sel)
2436
+ cx.out.emit(self.mod, node, self.symbol, sql, sink=_sink(node), in_loop=self.loop > 0, model=ent.table.name if ent is not None else "",
2437
+ operation=operation, confidence=CONF[conf], notes="; ".join(dict.fromkeys(n for n in notes if n)))
2438
+
2439
+ def raw(self, node: ast.AST, table: SATable, sql: str, operation: str, conf: int, notes: list, in_loop: bool | None = None) -> None:
2440
+ cx = self.cx
2441
+ if not self.emit:
2442
+ return
2443
+ if id(node) not in cx.counted:
2444
+ cx.counted.add(id(node))
2445
+ cx.stats.seen += 1
2446
+ cx.stats.translated += 1
2447
+ cx.out.emit(self.mod, node, self.symbol, sql, sink=_sink(node), in_loop=self.loop > 0 if in_loop is None else in_loop,
2448
+ model=table.name, operation=operation, confidence=CONF[conf], notes="; ".join(notes))
2449
+
2450
+
2451
+ def _sink(node: ast.AST) -> str:
2452
+ return src(node.func) if isinstance(node, ast.Call) else src(node)
2453
+
2454
+
2455
+ # a statement is emitted only when a table is named after FROM or JOIN (a run-time part there names nothing)
2456
+ _TABLE_NAMED = re.compile(r"\b(?:FROM|JOIN)\s+\(?\s*(?!SELECT\b)[A-Za-z_][\w.]*")
2457
+ _SESSIONISH = re.compile(r"session|conn|\bdb\b|engine|\bbind\b|cursor|\btx\b|transaction", re.I)
2458
+
2459
+
2460
+ def _has_session(call: ast.Call) -> bool:
2461
+ """True when a call is given, or made on, something that can run a statement."""
2462
+ recv = src(call.func.value) if isinstance(call.func, ast.Attribute) else ""
2463
+ if _SESSIONISH.search(recv):
2464
+ return True
2465
+ return any(_SESSIONISH.search(src(a)) for a in call.args if isinstance(a, (ast.Name, ast.Attribute))) or \
2466
+ any(k.arg and _SESSIONISH.search(k.arg) for k in call.keywords)
2467
+
2468
+
2469
+ def run(root: Path, project: Project):
2470
+ cx = Ctx(root, project)
2471
+ tables = cx.index.tables()
2472
+ if not cx.index.by_cls and not cx.index.table_vars:
2473
+ return [], cx.stats, tables
2474
+ cx.run()
2475
+ return cx.out.sites, cx.stats, tables