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,2772 @@
1
+ """Django ORM calls as SQL sites.
2
+
3
+ Each function body is walked once, in order, keeping what every local name is known to be: a model class, a
4
+ manager, a queryset (model plus the chained operations), a model instance (and the queryset it came from), or
5
+ unknown. A site is emitted where Django sends a statement:
6
+
7
+ - a terminal call (`get`, `first`, `count`, `exists`, `aggregate`, `create`, `update`, `delete`, `bulk_create` ...),
8
+ - a queryset that is iterated, measured, returned, stored or handed to other code (the SELECT, once per queryset),
9
+ - one statement per `prefetch_related` relation, at the same place,
10
+ - lazy relation access on the rows of a loop (the N+1 shape), with the confidence it deserves.
11
+
12
+ Chains built over several statements are followed; an operation applied only on some branch becomes a
13
+ «run-time part». Whatever cannot be decided is not emitted and is counted with its reason.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import ast
19
+ import builtins
20
+ import os
21
+ import re
22
+ from pathlib import Path
23
+
24
+ from .orm_django_models import BUILTIN_PATHS, DjangoIndex, Manager, Model
25
+ from .orm_django_sql import CONF, HIGH, LOW, MEDIUM, QS, Build, Op, Unresolved, merge_qs
26
+ from .orm_py import SETTINGS, Cls, Emitter, Mod, Project, Stats, const, dotted, kwarg, marker, sql_literal, src, str_const, unmark
27
+
28
+ AGGREGATES = {"Count": "COUNT", "Sum": "SUM", "Avg": "AVG", "Min": "MIN", "Max": "MAX", "StdDev": "STDDEV", "Variance": "VARIANCE",
29
+ "ArrayAgg": "ARRAY_AGG", "StringAgg": "STRING_AGG", "JSONBAgg": "JSONB_AGG", "BoolOr": "BOOL_OR",
30
+ "BoolAnd": "BOOL_AND", "BitOr": "BIT_OR", "BitAnd": "BIT_AND"}
31
+ FUNCS = {"Coalesce": "COALESCE", "Greatest": "GREATEST", "Least": "LEAST", "Concat": "CONCAT", "Lower": "LOWER", "Upper": "UPPER",
32
+ "Length": "LENGTH", "Abs": "ABS", "Round": "ROUND", "Trim": "TRIM", "LTrim": "LTRIM", "RTrim": "RTRIM", "Ceil": "CEIL",
33
+ "Floor": "FLOOR", "Sqrt": "SQRT", "Substr": "SUBSTRING", "Replace": "REPLACE", "Left": "LEFT", "Right": "RIGHT",
34
+ "NullIf": "NULLIF", "MD5": "MD5", "Reverse": "REVERSE", "StrIndex": "STRPOS", "Power": "POWER", "Mod": "MOD"}
35
+ TRUNCS = {"TruncYear": "year", "TruncQuarter": "quarter", "TruncMonth": "month", "TruncWeek": "week", "TruncDay": "day",
36
+ "TruncDate": "day", "TruncHour": "hour", "TruncMinute": "minute", "TruncSecond": "second"}
37
+ EXTRACT_FUNCS = {"ExtractYear": "YEAR", "ExtractMonth": "MONTH", "ExtractDay": "DAY", "ExtractHour": "HOUR", "ExtractMinute": "MINUTE",
38
+ "ExtractSecond": "SECOND", "ExtractWeek": "WEEK", "ExtractWeekDay": "DOW", "ExtractQuarter": "QUARTER",
39
+ "ExtractIsoYear": "ISOYEAR"}
40
+ CAST_TYPES = {"IntegerField": "INTEGER", "BigIntegerField": "BIGINT", "SmallIntegerField": "SMALLINT", "FloatField": "DOUBLE PRECISION",
41
+ "CharField": "VARCHAR", "TextField": "TEXT", "DateField": "DATE", "DateTimeField": "TIMESTAMP", "BooleanField": "BOOLEAN",
42
+ "DecimalField": "DECIMAL", "UUIDField": "UUID", "JSONField": "JSONB"}
43
+ EXPR_NAMES = set(AGGREGATES) | set(FUNCS) | set(TRUNCS) | set(EXTRACT_FUNCS) | {
44
+ "F", "Value", "OuterRef", "Subquery", "Exists", "Case", "When", "ExpressionWrapper", "RawSQL", "Func", "Cast", "Now", "Trunc",
45
+ "Extract", "Window", "Q"}
46
+ QS_PASS = {"all", "_clone", "_chain", "using", "db_manager", "get_queryset", "select_for_update", "prefetch_related", "select_related",
47
+ "filter", "exclude", "order_by", "distinct", "values", "values_list", "only", "defer", "annotate", "alias", "reverse", "none",
48
+ "extra", "union", "intersection", "difference", "complex_filter", "dates", "datetimes", "iterator", "aiterator", "with_cte",
49
+ "nocache", "no_cache", "cache", "with_tree_fields", "order_siblings_by"}
50
+ TERMINALS = {"get", "first", "last", "earliest", "latest", "count", "exists", "aggregate", "create", "get_or_create", "update_or_create",
51
+ "update", "delete", "bulk_create", "bulk_update", "in_bulk", "contains", "explain"}
52
+ # methods that only a Django queryset has: a call on a receiver of unknown type is counted as a call we could not type
53
+ DISTINCT = {"select_related", "prefetch_related", "values_list", "get_or_create", "update_or_create", "bulk_create", "bulk_update",
54
+ "select_for_update", "in_bulk"}
55
+ CONSUMERS = {"list", "tuple", "set", "frozenset", "sorted", "reversed", "iter", "tqdm", "enumerate", "deque", "chunked", "batched"}
56
+ # The form fields, filters and serializer fields that take a `queryset=` and run it to validate input
57
+ FIELD_CALLEE = re.compile(r"(?:Choice|Related|ContentType)(?:Field|Filter)$")
58
+ ROW_METHODS = ("get_","resolve_", "to_representation", "serialize", "transform")
59
+
60
+
61
+ # ---- values a name can hold -------------------------------------------------------------------------------------
62
+ class ModelRef:
63
+ __slots__ = ("model", "conf")
64
+
65
+ def __init__(self, model: Model, conf: int = HIGH):
66
+ self.model, self.conf = model, conf
67
+
68
+
69
+ class Mgr:
70
+ __slots__ = ("model", "mgr", "base", "plain")
71
+
72
+ def __init__(self, model: Model, mgr: Manager | None, base: QS, plain: bool = False):
73
+ self.model, self.mgr, self.base, self.plain = model, mgr, base, plain
74
+
75
+
76
+ class Inst:
77
+ __slots__ = ("model", "origin", "path", "per_iter", "row", "conf", "new", "name")
78
+
79
+ def __init__(self, model: Model, origin: QS | None = None, path: tuple = (), per_iter: int = 0, row: bool = False,
80
+ conf: int = HIGH, new: bool | None = None, name: str = ""):
81
+ self.model, self.origin, self.path, self.per_iter, self.row, self.conf, self.new, self.name = \
82
+ model, origin, path, per_iter, row, conf, new, name
83
+
84
+
85
+ class Seq:
86
+ __slots__ = ("elem",)
87
+
88
+ def __init__(self, elem):
89
+ self.elem = elem
90
+
91
+
92
+ class TupleV:
93
+ __slots__ = ("items",)
94
+
95
+ def __init__(self, items):
96
+ self.items = items
97
+
98
+
99
+ class QObj:
100
+ __slots__ = ("fn", "label", "roots")
101
+
102
+ def __init__(self, fn, label: str, roots: frozenset = frozenset()):
103
+ self.fn, self.label, self.roots = fn, label, roots
104
+
105
+
106
+ class XV:
107
+ __slots__ = ("fn", "roots")
108
+
109
+ def __init__(self, fn, roots: frozenset = frozenset()):
110
+ self.fn, self.roots = fn, roots
111
+
112
+
113
+ class PrefetchV:
114
+ __slots__ = ("path", "qs", "to_attr")
115
+
116
+ def __init__(self, path, qs, to_attr):
117
+ self.path, self.qs, self.to_attr = path, qs, to_attr
118
+
119
+
120
+ class SelfV:
121
+ """`self` inside a class that is not a model, manager or queryset (a view, a serializer, a service)."""
122
+ __slots__ = ("cls", "model")
123
+
124
+ def __init__(self, cls: Cls, model: Model | None):
125
+ self.cls, self.model = cls, model
126
+
127
+
128
+ class SuperV:
129
+ __slots__ = ("of",)
130
+
131
+ def __init__(self, of):
132
+ self.of = of
133
+
134
+
135
+ class Unk:
136
+ """A chain on a receiver of unknown type that was already counted."""
137
+ __slots__ = ()
138
+
139
+
140
+ UNK = Unk()
141
+
142
+
143
+ _DB_ENGINE = re.compile(r"django(?:\.contrib\.gis)?\.db\.backends\.(postgresql\w*|postgis|mysql|sqlite3|oracle)|"
144
+ r"[\"'](postgres(?:ql)?|mysql|mariadb|sqlite)(?:\+\w+)?://")
145
+
146
+
147
+ class Django:
148
+ def __init__(self, root: Path, project: Project):
149
+ self.project = project
150
+ self.index = DjangoIndex(project)
151
+ self.stats = Stats("django")
152
+ self.out = Emitter(self.stats)
153
+ self.seen_roots: dict[int, str] = {} # node id -> where
154
+ self.done_roots: set[int] = set()
155
+ self.root_reason: dict[int, str] = {}
156
+ self.counted_nodes: set[int] = set()
157
+ self._model_names: dict[tuple[str, str], ModelRef | None] = {}
158
+ self._ctx: dict[int, object] = {}
159
+ self._helper_cache: dict[tuple, object] = {}
160
+ self._ann_cache: dict[int, object] = {}
161
+ self._stack: list[int] = []
162
+ self.lazy = 0
163
+ self.prefetch_served = 0
164
+ self.engine = self._settings_engine()
165
+
166
+ def _settings_engine(self) -> str:
167
+ """The database engine the project's Django settings name (DATABASES ENGINE or a database URL), when they name
168
+ one server engine. The ORM's statements go there, whatever other stores the same file talks to."""
169
+ found: dict[str, int] = {}
170
+ for mod in self.project.mods.values():
171
+ if mod.is_test or not ("settings" in mod.rel or "/conf/" in mod.rel or mod.rel.endswith("conf.py")):
172
+ continue
173
+ for m in _DB_ENGINE.finditer(mod.text):
174
+ word = (m.group(1) or m.group(2)).lower()
175
+ eng = "postgres" if word.startswith(("postg", "psql", "psycopg")) else ("mysql" if word.startswith(("mysql", "maria")) else
176
+ ("sqlite" if word.startswith("sqlite") else "oracle"))
177
+ found[eng] = found.get(eng, 0) + 1
178
+ servers = {k: v for k, v in found.items() if k != "sqlite"} or found
179
+ if len(servers) == 1:
180
+ return next(iter(servers))
181
+ return ""
182
+
183
+ # ---- names -------------------------------------------------------------------------------------------------
184
+ def model_ref(self, mod: Mod, name: str) -> ModelRef | None:
185
+ key = (mod.rel, name)
186
+ if key in self._model_names:
187
+ return self._model_names[key]
188
+ out = None
189
+ p = self.project
190
+ got = p.resolve(mod, name)
191
+ hops = 0
192
+ while got is not None and got[0] == "value" and hops < 4:
193
+ v = got[2]
194
+ if isinstance(v, ast.Call) and (dotted(v.func) or "").endswith("get_user_model") and self.index.auth_user is not None:
195
+ out = ModelRef(self.index.auth_user)
196
+ break
197
+ inner = dotted(v)
198
+ if inner and inner.endswith(".through") and inner.count(".") >= 2:
199
+ owner = self.model_ref(got[1], inner.rsplit(".", 2)[0])
200
+ f = owner.model.fields.get(inner.rsplit(".", 2)[1]) if owner is not None else None
201
+ if f is None and owner is not None:
202
+ rel = owner.model.reverse.get(inner.rsplit(".", 2)[1])
203
+ f = rel.field if rel is not None and rel.kind == "rev_m2m" else None
204
+ t = (f.through or f.auto_through) if f is not None and f.kind == "m2m" else None
205
+ if t is not None and t.table:
206
+ out = ModelRef(t)
207
+ break
208
+ got = p.resolve(got[1], inner) if inner else None
209
+ hops += 1
210
+ if out is None and got is not None:
211
+ if got[0] == "class":
212
+ m = self.index.by_cls.get(id(got[1]))
213
+ if m is not None and m.table and not m.abstract:
214
+ out = ModelRef(m)
215
+ elif got[0] == "external" and got[1] in BUILTIN_PATHS:
216
+ app, nm = BUILTIN_PATHS[got[1]]
217
+ m = self.index.by_label.get((app, nm.lower()))
218
+ if m is not None:
219
+ out = ModelRef(m)
220
+ self._model_names[key] = out
221
+ return out
222
+
223
+ def guess_model(self, mod: Mod, name: str) -> tuple[ModelRef | None, str]:
224
+ """For a name followed by a manager: the model, or why not."""
225
+ ref = self.model_ref(mod, name)
226
+ if ref is not None:
227
+ return ref, ""
228
+ got = self.project.resolve(mod, name)
229
+ last = name.split(".")[-1]
230
+ if got is not None and got[0] == "class":
231
+ m = self.index.by_cls.get(id(got[1]))
232
+ if m is not None and m.abstract:
233
+ return None, "manager used on an abstract model"
234
+ if m is not None and not m.table:
235
+ return None, "model's table name is computed"
236
+ return None, "receiver is a class that is not a Django model"
237
+ if got is not None and got[0] == "external":
238
+ return None, "model defined outside the repository (" + got[1].split(".")[0] + ")"
239
+ if got is None and "." not in name and not last[:1].isupper():
240
+ return None, "receiver is a variable holding a model class"
241
+ cands = self.index.by_name.get(last, [])
242
+ if got is None and len(cands) == 1:
243
+ return ModelRef(cands[0], LOW), ""
244
+ if len(cands) > 1:
245
+ return None, "model name is ambiguous and its import could not be followed"
246
+ return None, "receiver is not a model found in the repository"
247
+
248
+ # ---- class context -----------------------------------------------------------------------------------------
249
+ def class_ctx(self, cls: Cls):
250
+ """What `self` is inside a class: ("model", Model) | ("manager", [Model], Manager) | ("queryset", [Model]) | ("other", Model|None)."""
251
+ got = self._ctx.get(id(cls))
252
+ if got is not None:
253
+ return got
254
+ ix, p = self.index, self.project
255
+ m = ix.by_cls.get(id(cls))
256
+ if m is not None:
257
+ got = ("model", m)
258
+ elif id(cls) in ix.manager_models:
259
+ pairs = ix.manager_models[id(cls)]
260
+ models = list(dict.fromkeys(mm for mm, _ in pairs))
261
+ got = ("manager", models, pairs[0][1])
262
+ elif id(cls) in ix.qs_models or any(e.split(".")[-1] in ("QuerySet", "Manager") for e in p.external_bases(cls)):
263
+ models = list(dict.fromkeys(ix.qs_models.get(id(cls), [])))
264
+ # `class OrderQueryset(models.QuerySet["Order"])` names its model
265
+ for b in cls.base_exprs:
266
+ if isinstance(b, ast.Subscript):
267
+ nm = str_const(b.slice) or dotted(b.slice)
268
+ ref = self.model_ref(cls.mod, nm) if nm else None
269
+ if ref is None and nm:
270
+ one = ix.unique(nm.split(".")[-1])
271
+ ref = ModelRef(one) if one is not None else None
272
+ if ref is not None:
273
+ models = [ref.model]
274
+ kind = "manager" if any(e.split(".")[-1].endswith("Manager") for e in p.external_bases(cls)) and id(cls) not in ix.qs_models else "queryset"
275
+ got = (kind, models, None) if kind == "manager" else ("queryset", models)
276
+ else:
277
+ model = None
278
+ # `@register(Model) class ModelSerializer(Serializer)`: a class decorator that names the model it serves
279
+ for d in cls.node.decorator_list:
280
+ if isinstance(d, ast.Call) and d.args and model is None:
281
+ nm = dotted(d.args[0])
282
+ ref = self.model_ref(cls.mod, nm) if nm else None
283
+ model = ref.model if ref is not None else None
284
+ for c in (p.mro(cls) if model is None else []):
285
+ meta = c.inner.get("Meta")
286
+ ref = None
287
+ if meta is not None and "model" in meta.assigns:
288
+ nm = dotted(meta.assigns["model"])
289
+ ref = self.model_ref(c.mod, nm) if nm else None
290
+ elif "model" in c.assigns:
291
+ nm = dotted(c.assigns["model"])
292
+ ref = self.model_ref(c.mod, nm) if nm else None
293
+ if ref is not None:
294
+ model = ref.model
295
+ break
296
+ got = ("other", model)
297
+ self._ctx[id(cls)] = got
298
+ return got
299
+
300
+ def run(self) -> None:
301
+ for mod in self.project.mods.values():
302
+ self.walk_module(mod)
303
+ for nid, where in self.seen_roots.items():
304
+ if nid in self.done_roots:
305
+ self.stats.translated += 1
306
+ else:
307
+ self.stats.miss(self.root_reason.get(nid, "queryset built here; no place where it runs was found in the function"), where)
308
+ self.stats.extra["lazy_load_sites"] = self.lazy
309
+ self.stats.extra["related_reads_served_by_prefetch"] = self.prefetch_served
310
+ self.stats.extra["models"] = len(self.index.models)
311
+ if self.index.skipped:
312
+ self.stats.extra["models_skipped"] = dict(self.index.skipped)
313
+
314
+ def walk_module(self, mod: Mod) -> None:
315
+ self._scope(mod, None, mod.tree.body, "", None)
316
+
317
+ def _scope(self, mod: Mod, cls: Cls | None, body: list, symbol: str, func, outer_env: dict | None = None) -> None:
318
+ """Walk one scope (module, class body or function), then the functions and classes defined in it."""
319
+ w = Walker(self, mod, cls, symbol, func=func, env=dict(outer_env or {}))
320
+ try:
321
+ w.run(body)
322
+ if func is None and cls is not None:
323
+ w.flush_class_level()
324
+ except RecursionError:
325
+ if os.environ.get("CODECOP_ORM_DEBUG") and os.environ["CODECOP_ORM_DEBUG"] in mod.rel:
326
+ raise
327
+ self.stats.miss("internal: expression too deep", f"{mod.rel}:{getattr(func, 'lineno', 1)}")
328
+ except Exception as e: # one function we cannot read must never stop discovery
329
+ if os.environ.get("CODECOP_ORM_DEBUG") and os.environ["CODECOP_ORM_DEBUG"] in mod.rel:
330
+ raise
331
+ self.stats.miss(f"internal error ({type(e).__name__})", f"{mod.rel}:{getattr(func, 'lineno', 1)}")
332
+ for kind, node, owner in w.nested:
333
+ if kind == "func":
334
+ sym = (symbol + "." if symbol else "") + node.name
335
+ self._scope(mod, owner, node.body, sym, node, w.env if func is not None else None)
336
+ else:
337
+ inner = owner
338
+ self._scope(mod, inner, node.body, (symbol + "." if symbol else "") + node.name, None)
339
+
340
+
341
+ class Walker:
342
+ def __init__(self, dj: Django, mod: Mod, cls: Cls | None, symbol: str, *, func=None, env: dict | None = None, emit: bool = True,
343
+ depth: int = 0, self_val=None, preset: dict | None = None):
344
+ self.dj, self.mod, self.cls, self.symbol, self.func = dj, mod, cls, symbol, func
345
+ self.env: dict = env if env is not None else {}
346
+ self.emit, self.depth = emit, depth
347
+ self.loop = 0
348
+ self.returns: list = []
349
+ self.nested: list = []
350
+ self.lazy_seen: set = set()
351
+ self.self_name = ""
352
+ self.self_val = self_val
353
+ self.captured: list | None = None # in a custom manager/queryset method read for a caller: the statements it sends
354
+ self.cond = 0 # depth of branches and loops the walk is inside
355
+ self.fwd = None # (vararg name, kwarg name, the caller's extra positional nodes, extra keywords, the caller's walker)
356
+ self.class_level = func is None and cls is not None
357
+ if func is not None:
358
+ self._params(func, preset or {})
359
+
360
+ # ---- parameters --------------------------------------------------------------------------------------------
361
+ def _params(self, func, preset: dict) -> None:
362
+ args = func.args
363
+ params = list(args.posonlyargs) + list(args.args)
364
+ decos = {(dotted(d) or dotted(getattr(d, "func", None)) or "").split(".")[-1] for d in func.decorator_list}
365
+ is_method = self.cls is not None and "staticmethod" not in decos and bool(params) and self.cls.methods.get(func.name) is func
366
+ ctx = self.dj.class_ctx(self.cls) if self.cls is not None else None
367
+ if is_method:
368
+ first = params[0].arg
369
+ self.self_name = first
370
+ if self.self_val is None:
371
+ self.self_val = self._self_value(ctx, "classmethod" in decos or first == "cls")
372
+ if self.self_val is not None:
373
+ self.env[first] = self.self_val
374
+ else:
375
+ self.env.pop(first, None)
376
+ params = params[1:]
377
+ cache = self.dj._ann_cache
378
+ for i, a in enumerate(params + list(args.kwonlyargs)):
379
+ v = None
380
+ if a.annotation is not None:
381
+ # what an annotation promises does not change: read it once, hand out a fresh value each time
382
+ key = id(a.annotation)
383
+ if key not in cache:
384
+ cache[key] = self.ann_value(a.annotation)
385
+ t = cache[key]
386
+ if isinstance(t, Inst):
387
+ v = Inst(t.model, conf=t.conf)
388
+ elif isinstance(t, QS):
389
+ v = t.with_()
390
+ else:
391
+ v = t
392
+ if v is None and is_method and ctx is not None and ctx[0] == "other" and ctx[1] is not None and i == 0:
393
+ # the row a serializer method, resolver or form works on
394
+ if a.arg in ("obj", "instance", "root", "item") and (func.name.startswith(ROW_METHODS) or a.arg in ("obj", "instance")):
395
+ v = Inst(ctx[1], row=func.name.startswith(ROW_METHODS), conf=MEDIUM, name=a.arg)
396
+ elif a.arg == "item_list" and func.name.startswith(ROW_METHODS):
397
+ v = Seq(Inst(ctx[1], conf=MEDIUM))
398
+ if isinstance(v, Inst):
399
+ v.name = a.arg
400
+ if is_method and func.name.startswith(ROW_METHODS) and self._serializer_like():
401
+ v.row = True # called once per row when a list is serialized
402
+ if v is not None:
403
+ self.env[a.arg] = v
404
+ else:
405
+ self.env.pop(a.arg, None)
406
+ for name, v in preset.items():
407
+ if v is not None:
408
+ self.env[name] = v
409
+ for a in ([args.vararg] if args.vararg else []) + ([args.kwarg] if args.kwarg else []):
410
+ self.env.pop(a.arg, None)
411
+
412
+ def _serializer_like(self) -> bool:
413
+ """A serializer, GraphQL type or resolver class: its row methods run once per row of a list."""
414
+ if self.cls is None:
415
+ return False
416
+ names = [c.name for c in self.dj.project.mro(self.cls)] + [e.split(".")[-1] for e in self.dj.project.external_bases(self.cls)]
417
+ return any(n.endswith(("Serializer", "ObjectType", "Resolver", "Schema")) for n in names)
418
+
419
+ def _self_value(self, ctx, is_cls: bool):
420
+ if ctx is None:
421
+ return None
422
+ if ctx[0] == "model":
423
+ if ctx[1].abstract or not ctx[1].table:
424
+ return None # an abstract model has no table of its own: nothing is said about it
425
+ return ModelRef(ctx[1]) if is_cls else Inst(ctx[1], name="self")
426
+ if ctx[0] == "manager":
427
+ models = ctx[1]
428
+ if len(models) == 1:
429
+ return Mgr(models[0], ctx[2], QS(models[0], qcls=ctx[2].qs_cls if ctx[2] else None), plain=True)
430
+ return None
431
+ if ctx[0] == "queryset":
432
+ models = ctx[1]
433
+ if len(models) == 1:
434
+ return QS(models[0], (Op("mark", "filters of the queryset this method is called on"),), conf=MEDIUM, qcls=self.cls)
435
+ return None
436
+ return SelfV(self.cls, ctx[1])
437
+
438
+ def ann_value(self, ann: ast.AST | None, depth: int = 0):
439
+ """The value a type annotation promises: Model -> an instance, QuerySet[Model] -> a queryset, list[Model] -> a sequence."""
440
+ if ann is None or depth > 4:
441
+ return None
442
+ if isinstance(ann, ast.Constant) and isinstance(ann.value, str):
443
+ try:
444
+ ann = ast.parse(ann.value, mode="eval").body
445
+ except SyntaxError:
446
+ return None
447
+ if isinstance(ann, ast.BinOp) and isinstance(ann.op, ast.BitOr):
448
+ return self.ann_value(ann.left, depth + 1) or self.ann_value(ann.right, depth + 1)
449
+ if isinstance(ann, ast.Subscript):
450
+ head = (dotted(ann.value) or "").split(".")[-1]
451
+ inner = ann.slice
452
+ first = inner.elts[0] if isinstance(inner, ast.Tuple) and inner.elts else inner
453
+ if head in ("Optional", "Annotated", "Final", "ClassVar", "Awaitable", "Coroutine"):
454
+ return self.ann_value(first, depth + 1)
455
+ if head in ("QuerySet", "Manager", "BaseManager", "RelatedManager", "ValuesQuerySet"):
456
+ if head == "ValuesQuerySet":
457
+ return None
458
+ v = self.ann_value(first, depth + 1)
459
+ if isinstance(v, Inst):
460
+ return QS(v.model, (Op("mark", "filters applied by the caller"),), conf=MEDIUM)
461
+ return None
462
+ if head in ("list", "List", "Sequence", "Iterable", "Collection", "Iterator", "set", "Set", "frozenset", "tuple", "Tuple",
463
+ "Generator", "AbstractSet", "MutableSequence", "FrozenSet"):
464
+ v = self.ann_value(first, depth + 1)
465
+ return Seq(v) if isinstance(v, Inst) else None
466
+ if head == "Union":
467
+ for e in (inner.elts if isinstance(inner, ast.Tuple) else [inner]):
468
+ v = self.ann_value(e, depth + 1)
469
+ if v is not None:
470
+ return v
471
+ return None
472
+ if head == "type" or head == "Type":
473
+ v = self.ann_value(first, depth + 1)
474
+ return ModelRef(v.model) if isinstance(v, Inst) else None
475
+ return None
476
+ nm = dotted(ann)
477
+ if not nm:
478
+ return None
479
+ ref = self.dj.model_ref(self.mod, nm)
480
+ if ref is not None:
481
+ return Inst(ref.model, conf=MEDIUM)
482
+ # a queryset class of one model
483
+ cls = self.dj.project.resolve_class(self.mod, nm)
484
+ if cls is not None:
485
+ ctx = self.dj.class_ctx(cls)
486
+ if ctx[0] == "queryset" and len(ctx[1]) == 1:
487
+ return QS(ctx[1][0], (Op("mark", "filters applied by the caller"),), conf=MEDIUM, qcls=cls)
488
+ return None
489
+
490
+ # ---- statements --------------------------------------------------------------------------------------------
491
+ def run(self, body: list) -> None:
492
+ for st in body:
493
+ self.stmt(st)
494
+
495
+ @staticmethod
496
+ def _terminates(body: list) -> bool:
497
+ return bool(body) and isinstance(body[-1], (ast.Return, ast.Raise, ast.Continue, ast.Break))
498
+
499
+ def _branch(self, body: list) -> dict:
500
+ saved = self.env
501
+ self.env = dict(saved)
502
+ self.cond += 1
503
+ try:
504
+ self.run(body)
505
+ return self.env
506
+ finally:
507
+ self.cond -= 1
508
+ self.env = saved
509
+
510
+ def _merge(self, a: dict, b: dict) -> dict:
511
+ out = {}
512
+ for name in set(a) | set(b):
513
+ va, vb = a.get(name), b.get(name)
514
+ if va is vb:
515
+ if va is not None:
516
+ out[name] = va
517
+ continue
518
+ if isinstance(va, QS) and isinstance(vb, QS):
519
+ m = merge_qs(va, vb)
520
+ if m is not None:
521
+ if m is not va and m is not vb and (va.state["emitted"] and vb.state["emitted"]):
522
+ m.state["emitted"] = True
523
+ out[name] = m
524
+ continue
525
+ if isinstance(va, Inst) and isinstance(vb, Inst) and va.model is vb.model:
526
+ out[name] = va if va.per_iter >= vb.per_iter else vb
527
+ continue
528
+ if isinstance(va, QObj) or isinstance(vb, QObj):
529
+ keep = va if isinstance(va, QObj) else vb
530
+ other = vb if keep is va else va
531
+ if other is None or isinstance(other, QObj):
532
+ out[name] = QObj(lambda b, n=name: marker(n), name)
533
+ continue
534
+ if va is None or vb is None:
535
+ keep = va if va is not None else vb
536
+ if isinstance(keep, QS):
537
+ keep = keep.with_(conf=MEDIUM)
538
+ keep.state = (va or vb).state
539
+ if isinstance(keep, (QS, Inst, ModelRef, Seq, Mgr)):
540
+ out[name] = keep
541
+ return out
542
+
543
+ def stmt(self, st: ast.stmt) -> None:
544
+ t = type(st)
545
+ if t is ast.Expr:
546
+ v = self.ev(st.value)
547
+ # a bare `qs` statement or `qs.filter(...)` alone runs nothing
548
+ if isinstance(st.value, (ast.Await, ast.Yield, ast.YieldFrom)):
549
+ pass
550
+ elif t is ast.Assign:
551
+ v = self.ev(st.value)
552
+ for target in st.targets:
553
+ self.bind(target, v, st.value)
554
+ elif t is ast.AnnAssign:
555
+ if st.value is not None:
556
+ v = self.ev(st.value)
557
+ if v is None:
558
+ v = self.ann_value(st.annotation)
559
+ self.bind(st.target, v, st.value)
560
+ elif isinstance(st.target, ast.Name):
561
+ v = self.ann_value(st.annotation)
562
+ if v is not None:
563
+ self.env[st.target.id] = v
564
+ elif t is ast.AugAssign:
565
+ cur = self.ev(st.target) if isinstance(st.target, ast.Name) else None
566
+ if isinstance(cur, QObj) and isinstance(st.op, (ast.BitOr, ast.BitAnd)):
567
+ other, roots = self._held(self.pfn, st.value)
568
+ joiner = " OR " if isinstance(st.op, ast.BitOr) else " AND "
569
+ self.env[st.target.id] = QObj(_combine([cur.fn, other], joiner), cur.label, cur.roots | roots)
570
+ elif isinstance(cur, QS) and isinstance(st.op, (ast.BitOr, ast.BitAnd)):
571
+ other = self.ev(st.value)
572
+ self.env[st.target.id] = _union(cur, other, isinstance(st.op, ast.BitOr)) if isinstance(other, QS) else \
573
+ cur.add(_COMBINED, conf=MEDIUM)
574
+ else:
575
+ self.use(st.value)
576
+ if isinstance(st.target, ast.Name):
577
+ self.env.pop(st.target.id, None)
578
+ elif t is ast.Return:
579
+ if st.value is not None:
580
+ v = self.ev(st.value)
581
+ self.returns.append(v)
582
+ self.consume(st.value, v, "returned")
583
+ else:
584
+ self.returns.append(None)
585
+ elif t is ast.If:
586
+ self.use(st.test)
587
+ pre = self.env
588
+ a = self._branch(st.body)
589
+ b = self._branch(st.orelse) if st.orelse else pre
590
+ if self._terminates(st.body):
591
+ self.env = dict(b)
592
+ elif st.orelse and self._terminates(st.orelse):
593
+ self.env = dict(a)
594
+ else:
595
+ self.env = self._merge(a, b)
596
+ elif t in (ast.For, ast.AsyncFor):
597
+ it = self.ev(st.iter)
598
+ elem = self.iterate(st.iter, it)
599
+ pre = self.env
600
+ self.env = dict(pre)
601
+ self.loop += 1
602
+ try:
603
+ self.bind(st.target, elem, None)
604
+ self.run(st.body)
605
+ finally:
606
+ self.loop -= 1
607
+ body_env = self.env
608
+ self.env = self._merge(body_env, pre)
609
+ if st.orelse:
610
+ self.run(st.orelse)
611
+ elif t is ast.While:
612
+ pre = self.env
613
+ self.env = dict(pre)
614
+ self.loop += 1
615
+ try:
616
+ self.use(st.test)
617
+ self.run(st.body)
618
+ finally:
619
+ self.loop -= 1
620
+ self.env = self._merge(self.env, pre)
621
+ if st.orelse:
622
+ self.run(st.orelse)
623
+ elif t in (ast.With, ast.AsyncWith):
624
+ for item in st.items:
625
+ v = self.ev(item.context_expr)
626
+ if item.optional_vars is not None:
627
+ self.bind(item.optional_vars, None, None)
628
+ self.run(st.body)
629
+ elif t is ast.Try or t.__name__ == "TryStar":
630
+ self.run(st.body)
631
+ after = self.env
632
+ merged = after
633
+ for h in st.handlers:
634
+ merged = self._merge(merged, self._branch(h.body)) if not self._terminates(h.body) else merged
635
+ self.env = dict(merged)
636
+ self.run(st.orelse)
637
+ self.run(st.finalbody)
638
+ elif t in (ast.FunctionDef, ast.AsyncFunctionDef):
639
+ for d in st.decorator_list:
640
+ self.use(d)
641
+ self.nested.append(("func", st, self.cls if self.class_level else None))
642
+ self.env.pop(st.name, None)
643
+ elif t is ast.ClassDef:
644
+ owner = None
645
+ if self.class_level:
646
+ owner = self.cls.inner.get(st.name)
647
+ elif self.func is None and self.cls is None:
648
+ owner = self.mod.classes.get(st.name)
649
+ if owner is not None and owner.node is not st:
650
+ owner = Cls(self.mod, st)
651
+ if owner is None:
652
+ owner = Cls(self.mod, st)
653
+ self.nested.append(("class", st, owner))
654
+ elif t is ast.Delete:
655
+ for target in st.targets:
656
+ if isinstance(target, ast.Name):
657
+ self.env.pop(target.id, None)
658
+ elif t.__name__ == "Match":
659
+ self.use(st.subject)
660
+ pre = self.env
661
+ merged = pre
662
+ for case in st.cases:
663
+ merged = self._merge(merged, self._branch(case.body))
664
+ self.env = merged
665
+ elif t in (ast.Raise, ast.Assert):
666
+ for child in ast.iter_child_nodes(st):
667
+ if isinstance(child, ast.expr):
668
+ self.use(child)
669
+ # import, global, pass, break, continue: nothing to do
670
+
671
+ def flush_class_level(self) -> None:
672
+ """A class attribute that holds a queryset (`queryset = Model.objects.all()`) is run by the framework."""
673
+ for name, v in list(self.env.items()):
674
+ if isinstance(v, QS) and not v.state["emitted"] and name in self.cls.assigns:
675
+ node = self.cls.assigns[name]
676
+ self.emit_select(node, v.with_(conf=MEDIUM, note="class-level queryset: run by the framework, or refined first by the "
677
+ "methods that use it"), share=v)
678
+
679
+ def bind(self, target: ast.AST, v, value_node) -> None:
680
+ if isinstance(target, ast.Name):
681
+ if isinstance(v, (QS, Inst, ModelRef, Mgr, Seq, QObj, XV, TupleV, PrefetchV, SelfV)):
682
+ if isinstance(v, Inst) and not v.name:
683
+ v.name = target.id
684
+ if isinstance(v, QS):
685
+ v.state.setdefault("loop", self.loop) # where the queryset object was made
686
+ self.env[target.id] = v
687
+ else:
688
+ self.env.pop(target.id, None)
689
+ elif isinstance(target, (ast.Tuple, ast.List)):
690
+ items = v.items if isinstance(v, TupleV) else None
691
+ if items is None and isinstance(v, QS) and value_node is not None:
692
+ self.consume(value_node, v, "unpacked")
693
+ for i, el in enumerate(target.elts):
694
+ 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)
695
+ elif isinstance(target, ast.Attribute):
696
+ self.ev(target.value)
697
+ if value_node is not None:
698
+ self.consume(value_node, v, "stored on an attribute")
699
+ elif isinstance(target, ast.Subscript):
700
+ self.use(target.value)
701
+ self.use(target.slice)
702
+ if value_node is not None:
703
+ self.consume(value_node, v, "stored in a container")
704
+
705
+ # ---- consumption -------------------------------------------------------------------------------------------
706
+ def use(self, node: ast.AST | None, how: str = "") -> object:
707
+ """Evaluate an expression whose value is used: a queryset used is a queryset run."""
708
+ if node is None:
709
+ return None
710
+ v = self.ev(node)
711
+ self.consume(node, v, how)
712
+ return v
713
+
714
+ def consume(self, node: ast.AST, v, how: str = "") -> None:
715
+ if isinstance(v, QS):
716
+ if how == "returned" and not self.emit:
717
+ return
718
+ if how == "returned":
719
+ ctx = self.dj.class_ctx(self.cls) if self.cls is not None and not v.roots else None
720
+ if ctx is not None and ctx[0] in ("manager", "queryset"):
721
+ return
722
+ self.emit_select(node, v.with_(conf=MEDIUM, note="queryset returned to the caller, which may refine it before it runs"), share=v)
723
+ elif how.startswith("passed"):
724
+ self.emit_select(node, v.with_(note=f"queryset {how}, which may refine it before it runs"), share=v)
725
+ else:
726
+ self.emit_select(node, v, share=v)
727
+ elif isinstance(v, TupleV):
728
+ for item in v.items:
729
+ if isinstance(item, QS):
730
+ self.consume(node, item, how)
731
+
732
+ def iterate(self, node: ast.AST, v):
733
+ """The element a loop over `v` binds, emitting the SELECT when `v` is a queryset."""
734
+ if isinstance(v, QS):
735
+ self.emit_select(node, v, share=v)
736
+ if v.has("values"):
737
+ return None
738
+ return Inst(v.model, origin=v, per_iter=self.loop + 1, conf=v.conf)
739
+ if isinstance(v, Seq):
740
+ e = v.elem
741
+ if isinstance(e, Inst):
742
+ return Inst(e.model, origin=e.origin, path=e.path, per_iter=self.loop + 1, row=e.row, conf=e.conf)
743
+ return e
744
+ return None
745
+
746
+ # ---- expressions -------------------------------------------------------------------------------------------
747
+ def ev(self, node: ast.AST | None):
748
+ if node is None:
749
+ return None
750
+ t = type(node)
751
+ if t is ast.Name:
752
+ if node.id in self.env:
753
+ return self.env[node.id]
754
+ return self.dj.model_ref(self.mod, node.id)
755
+ if t is ast.Attribute:
756
+ return self.ev_attr(node)
757
+ if t is ast.Call:
758
+ return self.ev_call(node)
759
+ if t is ast.Constant:
760
+ return None
761
+ if t is ast.Await:
762
+ return self.ev(node.value)
763
+ if t is ast.Subscript:
764
+ base = self.ev(node.value)
765
+ if isinstance(base, QS):
766
+ return self.subscript(node, base)
767
+ self.use(node.slice)
768
+ if isinstance(base, Seq):
769
+ return base if isinstance(node.slice, ast.Slice) else base.elem
770
+ if isinstance(base, TupleV):
771
+ ok, i = const(node.slice)
772
+ if ok and isinstance(i, int) and 0 <= i < len(base.items):
773
+ return base.items[i]
774
+ self.consume(node.value, base)
775
+ return None
776
+ if t in (ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp):
777
+ return self.comprehension(node)
778
+ if t is ast.IfExp:
779
+ self.use(node.test)
780
+ a, b = self.ev(node.body), self.ev(node.orelse)
781
+ if a is b:
782
+ return a
783
+ if isinstance(a, QS) and isinstance(b, QS):
784
+ m = merge_qs(a, b)
785
+ if m is not None:
786
+ return m
787
+ self.consume(node.body, a)
788
+ self.consume(node.orelse, b)
789
+ return None
790
+ if isinstance(a, QS) or isinstance(b, QS):
791
+ keep = a if isinstance(a, QS) else b
792
+ return keep.with_(conf=MEDIUM)
793
+ return a if a is not None else b
794
+ if t is ast.BoolOp:
795
+ vals = [self.ev(v) for v in node.values]
796
+ typed = [v for v in vals if isinstance(v, (QS, Inst, Seq))]
797
+ for n, v in zip(node.values[:-1], vals[:-1]):
798
+ self.consume(n, v) # `qs or default` tests the queryset: it runs
799
+ return typed[-1] if typed else None
800
+ if t is ast.BinOp:
801
+ if isinstance(node.op, (ast.BitOr, ast.BitAnd)):
802
+ if _is_q(node):
803
+ return self._q(node)
804
+ a, b = self.ev(node.left), self.ev(node.right)
805
+ if isinstance(a, QObj) or isinstance(b, QObj):
806
+ return self._q(node)
807
+ if isinstance(a, QS) and isinstance(b, QS):
808
+ return _union(a, b, isinstance(node.op, ast.BitOr))
809
+ self.consume(node.left, a)
810
+ self.consume(node.right, b)
811
+ return None
812
+ self.use(node.left)
813
+ self.use(node.right)
814
+ return None
815
+ if t is ast.UnaryOp:
816
+ if isinstance(node.op, ast.Invert) and _is_q(node):
817
+ return self._q(node)
818
+ v = self.use(node.operand)
819
+ return None
820
+ if t is ast.NamedExpr:
821
+ v = self.ev(node.value)
822
+ self.bind(node.target, v, None)
823
+ return v
824
+ if t is ast.Starred:
825
+ return self.ev(node.value)
826
+ if t is ast.Lambda:
827
+ saved = self.env
828
+ self.env = dict(saved)
829
+ for a in node.args.args:
830
+ self.env.pop(a.arg, None)
831
+ try:
832
+ self.use(node.body)
833
+ finally:
834
+ self.env = saved
835
+ return None
836
+ if t in (ast.Yield, ast.YieldFrom):
837
+ if node.value is not None:
838
+ self.use(node.value, "returned")
839
+ return None
840
+ if t in (ast.Tuple, ast.List, ast.Set):
841
+ vals = [self.ev(e) for e in node.elts]
842
+ if t is ast.Tuple and any(isinstance(v, (Inst, QS)) for v in vals):
843
+ return TupleV(vals)
844
+ for e, v in zip(node.elts, vals):
845
+ self.consume(e, v, "stored in a container")
846
+ insts = [v for v in vals if isinstance(v, Inst)]
847
+ return Seq(insts[0]) if insts and len(insts) == len(vals) else None
848
+ if t is ast.Dict:
849
+ for k in node.keys:
850
+ if k is not None:
851
+ self.use(k)
852
+ for v in node.values:
853
+ self.use(v, "stored in a container")
854
+ return None
855
+ for child in ast.iter_child_nodes(node):
856
+ if isinstance(child, ast.expr):
857
+ self.use(child)
858
+ elif isinstance(child, ast.keyword):
859
+ self.use(child.value)
860
+ elif isinstance(child, ast.comprehension):
861
+ self.use(child.iter)
862
+ elif isinstance(child, ast.FormattedValue):
863
+ self.use(child.value)
864
+ return None
865
+
866
+ def comprehension(self, node):
867
+ saved = self.env
868
+ self.env = dict(saved)
869
+ entered = 0
870
+ try:
871
+ for i, gen in enumerate(node.generators):
872
+ it = self.ev(gen.iter)
873
+ elem = self.iterate(gen.iter, it)
874
+ self.loop += 1
875
+ entered += 1
876
+ self.bind(gen.target, elem, None)
877
+ for cond in gen.ifs:
878
+ self.use(cond)
879
+ if isinstance(node, ast.DictComp):
880
+ self.use(node.key)
881
+ self.use(node.value)
882
+ return None
883
+ v = self.ev(node.elt)
884
+ self.consume(node.elt, v)
885
+ if isinstance(v, Inst):
886
+ return Seq(Inst(v.model, origin=v.origin, path=v.path, conf=v.conf))
887
+ return None
888
+ finally:
889
+ self.loop -= entered
890
+ self.env = saved
891
+
892
+ def subscript(self, node: ast.Subscript, qs: QS):
893
+ s = node.slice
894
+ if isinstance(s, ast.Slice):
895
+ if s.step is not None:
896
+ self.consume(node.value, qs)
897
+ return Seq(Inst(qs.model, origin=qs))
898
+ lo = self.plain_value(s.lower) if s.lower is not None else None
899
+ hi = self.plain_value(s.upper) if s.upper is not None else None
900
+ return qs.add(Op("slice", (lo, hi)))
901
+ idx = self.plain_value(s)
902
+ one = qs.add(Op("slice", (idx, _plus_one(idx))))
903
+ b, notes, conf = self.compile(one)
904
+ self.site(node, one, b.select(force_pk=False), "select", conf, notes)
905
+ return Inst(qs.model, origin=qs, per_iter=self.loop, conf=qs.conf)
906
+
907
+ def plain_value(self, node: ast.AST) -> str:
908
+ ok, v = const(node)
909
+ if ok and not isinstance(v, list):
910
+ s = sql_literal(v)
911
+ if s is not None:
912
+ return s
913
+ self.use(node)
914
+ return marker(src(node))
915
+
916
+ # ---- attributes --------------------------------------------------------------------------------------------
917
+ def ev_attr(self, node: ast.Attribute):
918
+ attr = node.attr
919
+ dj = self.dj
920
+ if attr == "through" and isinstance(node.value, ast.Attribute):
921
+ # `Model.m2m_field.through`: the model of the many-to-many table
922
+ owner = self.ev(node.value.value)
923
+ if isinstance(owner, ModelRef):
924
+ f = owner.model.fields.get(node.value.attr)
925
+ if f is None:
926
+ rel = owner.model.reverse.get(node.value.attr)
927
+ f = rel.field if rel is not None and rel.kind == "rev_m2m" else None
928
+ t = (f.through or f.auto_through) if f is not None and f.kind == "m2m" else None
929
+ return ModelRef(t, owner.conf) if t is not None and t.table else None
930
+ base = self.ev(node.value)
931
+ if isinstance(base, ModelRef):
932
+ m = base.model
933
+ if attr in m.managers:
934
+ return self.manager(node, m, m.managers[attr], base.conf)
935
+ if attr == "objects":
936
+ return self.manager(node, m, Manager("objects"), base.conf)
937
+ return None
938
+ if isinstance(base, Inst):
939
+ return self.inst_attr(node, base)
940
+ if isinstance(base, Mgr):
941
+ if attr == "model":
942
+ return ModelRef(base.model)
943
+ return None
944
+ if isinstance(base, QS):
945
+ if attr == "model":
946
+ return ModelRef(base.model)
947
+ if attr in ("query", "db", "ordered"):
948
+ return None
949
+ self.consume(node.value, base)
950
+ return None
951
+ if isinstance(base, SelfV):
952
+ return self.self_attr(node, base)
953
+ if isinstance(base, Seq) or isinstance(base, TupleV):
954
+ return None
955
+ if base is None:
956
+ if attr[:1].isupper():
957
+ # `models.Product`, `product_models.Product`: a model reached through a module
958
+ full = dotted(node)
959
+ if full and full.split(".")[0] not in self.env:
960
+ ref = dj.model_ref(self.mod, full)
961
+ if ref is not None:
962
+ return ref
963
+ if attr in ("objects", "_default_manager", "_base_manager"):
964
+ nm = dotted(node.value)
965
+ if nm:
966
+ if nm.split(".")[0] in self.env and "." not in nm:
967
+ return None
968
+ ref, why = dj.guess_model(self.mod, nm)
969
+ if ref is not None:
970
+ return self.manager(node, ref.model, ref.model.managers.get(attr) or Manager(attr), ref.conf)
971
+ if nm.split(".")[-1] in ("self", "cls") or nm.endswith((".model", "__class__", "model_class", "Meta.model")) \
972
+ or nm.split(".")[-1].islower():
973
+ why = "receiver is a variable holding a model class"
974
+ if id(node) not in dj.counted_nodes:
975
+ dj.counted_nodes.add(id(node))
976
+ dj.stats.seen += 1
977
+ dj.stats.miss(why, f"{self.mod.rel}:{node.lineno}")
978
+ return UNK
979
+ else:
980
+ inner = node.value
981
+ # apps.get_model("app", "Model").objects, get_user_model().objects, type(self).objects
982
+ ref = self.model_from_call(inner) if isinstance(inner, ast.Call) else None
983
+ if ref is not None:
984
+ return self.manager(node, ref.model, ref.model.managers.get(attr) or Manager(attr), ref.conf)
985
+ if id(node) not in dj.counted_nodes:
986
+ dj.counted_nodes.add(id(node))
987
+ dj.stats.seen += 1
988
+ dj.stats.miss("receiver is an expression holding a model class", f"{self.mod.rel}:{node.lineno}")
989
+ return UNK
990
+ if attr == "user":
991
+ nm = dotted(node.value) or ""
992
+ if nm.split(".")[-1] in ("request", "context", "_request") and dj.index.auth_user is not None:
993
+ return Inst(dj.index.auth_user, conf=LOW, name=nm + ".user")
994
+ return None
995
+
996
+ def model_from_call(self, call: ast.Call) -> ModelRef | None:
997
+ fn = dotted(call.func) or ""
998
+ last = fn.split(".")[-1]
999
+ ix = self.dj.index
1000
+ if last == "get_user_model" and ix.auth_user is not None:
1001
+ return ModelRef(ix.auth_user)
1002
+ if last == "get_model":
1003
+ parts = [str_const(a) for a in call.args]
1004
+ if len(parts) == 1 and parts[0] and "." in parts[0]:
1005
+ parts = parts[0].split(".")
1006
+ if len(parts) == 2 and all(parts):
1007
+ m = ix.by_label.get((parts[0].lower(), parts[1].lower()))
1008
+ return ModelRef(m, MEDIUM) if m is not None else None
1009
+ if last == "type" and len(call.args) == 1:
1010
+ v = self.ev(call.args[0])
1011
+ if isinstance(v, Inst):
1012
+ return ModelRef(v.model)
1013
+ return None
1014
+
1015
+ def manager(self, node: ast.AST, model: Model, mgr: Manager, conf: int) -> Mgr:
1016
+ dj = self.dj
1017
+ nid = id(node)
1018
+ if nid not in dj.seen_roots:
1019
+ dj.seen_roots[nid] = f"{self.mod.rel}:{node.lineno}"
1020
+ dj.stats.seen += 1
1021
+ base = QS(model, roots=frozenset([nid]), conf=conf, qcls=mgr.qs_cls, sink=src(node))
1022
+ if mgr.cls is not None:
1023
+ key = ("mgr", id(model), id(mgr.cls))
1024
+ cached = dj._helper_cache.get(key)
1025
+ if cached is None:
1026
+ cached = ((), HIGH, ())
1027
+ found = dj.project.find_method(mgr.cls, "get_queryset")
1028
+ if found is not None:
1029
+ got = self.call_def(found[0], found[1], Mgr(model, mgr, QS(model, qcls=mgr.qs_cls), plain=True), None, [], {})
1030
+ if isinstance(got, QS) and got.model is model:
1031
+ cached = (got.ops, got.conf, got.notes)
1032
+ elif _refines(found[1]):
1033
+ cached = ((Op("mark", f"filters of {found[0].name}.get_queryset()"),), MEDIUM, ())
1034
+ dj._helper_cache[key] = cached
1035
+ base = QS(model, cached[0], frozenset([nid]), max(conf, cached[1]), cached[2], None, src(node), mgr.qs_cls)
1036
+ return Mgr(model, mgr, base)
1037
+
1038
+ def self_attr(self, node: ast.Attribute, sv: SelfV):
1039
+ attr = node.attr
1040
+ p = self.dj.project
1041
+ if attr in ("instance", "object") and sv.model is not None:
1042
+ return Inst(sv.model, conf=MEDIUM, name="self." + attr)
1043
+ if attr == "model":
1044
+ found = p.find_attr(sv.cls, "model")
1045
+ nm = dotted(found[1]) if found else None
1046
+ ref = self.dj.model_ref(found[0].mod, nm) if nm else None
1047
+ return ref or (ModelRef(sv.model) if sv.model is not None else None)
1048
+ if attr == "queryset":
1049
+ return self.class_queryset(sv)
1050
+ found = p.find_attr(sv.cls, attr)
1051
+ if found is not None and isinstance(found[1], (ast.Call, ast.Attribute, ast.Name)) and self.depth < SETTINGS["orm_helper_depth"]:
1052
+ nm = dotted(found[1])
1053
+ if nm:
1054
+ ref = self.dj.model_ref(found[0].mod, nm)
1055
+ if ref is not None:
1056
+ return ref
1057
+ return None
1058
+
1059
+ def class_queryset(self, sv: SelfV):
1060
+ p = self.dj.project
1061
+ found = p.find_attr(sv.cls, "queryset")
1062
+ if found is not None:
1063
+ w = Walker(self.dj, found[0].mod, found[0], found[0].qual, emit=False, depth=self.depth + 1)
1064
+ v = w.ev(found[1])
1065
+ if isinstance(v, Mgr):
1066
+ v = v.base
1067
+ if isinstance(v, QS):
1068
+ return v.with_()
1069
+ found = p.find_attr(sv.cls, "model")
1070
+ if found is not None:
1071
+ nm = dotted(found[1])
1072
+ ref = self.dj.model_ref(found[0].mod, nm) if nm else None
1073
+ if ref is not None:
1074
+ return QS(ref.model, conf=MEDIUM)
1075
+ return None
1076
+
1077
+ def inst_attr(self, node: ast.Attribute, inst: Inst):
1078
+ attr = node.attr
1079
+ m = inst.model
1080
+ if attr in ("__class__", "_meta_model"):
1081
+ return ModelRef(m)
1082
+ if attr == "objects" or attr in m.managers and attr not in m.fields:
1083
+ return None
1084
+ f = m.fields.get(attr)
1085
+ if f is not None:
1086
+ if f.kind in ("fk", "o2o"):
1087
+ if f.target is None:
1088
+ return None
1089
+ child = Inst(f.target, origin=inst.origin, path=inst.path + (attr,), per_iter=inst.per_iter, row=inst.row,
1090
+ conf=max(inst.conf, MEDIUM if inst.origin is None else HIGH), name=(inst.name + "." if inst.name else "") + attr)
1091
+ if isinstance(node.ctx, ast.Load):
1092
+ self.lazy_fk(node, inst, f, child)
1093
+ return child
1094
+ if f.kind == "m2m" and f.target is not None and f.m2m_table and f.m2m_from:
1095
+ t = f.target
1096
+ pk = t.pk.column if t.pk else "id"
1097
+ who = unmark(inst.name or m.name.lower())
1098
+ fn = (lambda b, f=f, pk=pk, who=who: f"{b.join(('<m2m>',), f.m2m_table, f'{b.root}.{pk}', f.m2m_to, left=False)}.{f.m2m_from} = "
1099
+ + marker(f"{who}.pk"))
1100
+ base = QS(t, (Op("where", (fn, False, f"{attr} of {who}")),), conf=inst.conf)
1101
+ base.lazy = (inst, attr, 1)
1102
+ base.sink = src(node)
1103
+ return Mgr(t, t.managers.get("objects") or Manager("objects"), base)
1104
+ return None
1105
+ rel = m.reverse.get(attr)
1106
+ if rel is not None and rel.model.table:
1107
+ far = rel.model
1108
+ who = unmark(inst.name or m.name.lower())
1109
+ if rel.kind in ("rev_fk", "rev_o2o"):
1110
+ col = rel.field.column
1111
+ fn = lambda b, col=col, who=who: f"{b.root}.{col} = " + marker(f"{who}.pk")
1112
+ base = QS(far, (Op("where", (fn, False, f"{attr} of {who}")),), conf=inst.conf)
1113
+ base.lazy = (inst, attr, 1)
1114
+ base.sink = src(node)
1115
+ if rel.kind == "rev_o2o":
1116
+ child = Inst(far, origin=inst.origin, path=inst.path + (attr,), per_iter=inst.per_iter, row=inst.row, conf=max(inst.conf, MEDIUM),
1117
+ name=(inst.name + "." if inst.name else "") + attr)
1118
+ if isinstance(node.ctx, ast.Load):
1119
+ self.lazy_rel(node, inst, attr, base)
1120
+ return child
1121
+ return Mgr(far, far.managers.get("_default_manager") or Manager("objects"), base)
1122
+ f2 = rel.field
1123
+ if f2.m2m_table and f2.m2m_from and far.pk is not None:
1124
+ fn = (lambda b, f2=f2, far=far, who=who: f"{b.join(('<m2m>',), f2.m2m_table, f'{b.root}.{far.pk.column}', f2.m2m_from, left=False)}.{f2.m2m_to} = "
1125
+ + marker(f"{who}.pk"))
1126
+ base = QS(far, (Op("where", (fn, False, f"{attr} of {who}")),), conf=inst.conf)
1127
+ base.lazy = (inst, attr, 1)
1128
+ base.sink = src(node)
1129
+ return Mgr(far, far.managers.get("_default_manager") or Manager("objects"), base)
1130
+ return None
1131
+ if attr == "pk" or m.field_by_attname(attr) is not None:
1132
+ return None
1133
+ # a property or method of the model with a declared return type
1134
+ if m.cls is not None:
1135
+ found = self.dj.project.find_method(m.cls, attr)
1136
+ if found is not None and found[1].returns is not None and any(
1137
+ (dotted(d) or "").split(".")[-1] in ("property", "cached_property") for d in found[1].decorator_list):
1138
+ w = Walker(self.dj, found[0].mod, found[0], found[0].qual, emit=False, depth=self.depth + 1)
1139
+ v = w.ann_value(found[1].returns)
1140
+ if isinstance(v, Inst):
1141
+ v.per_iter, v.name = 0, (inst.name + "." if inst.name else "") + attr
1142
+ return v
1143
+ return None
1144
+
1145
+ # ---- lazy loads (the N+1 shape) ---------------------------------------------------------------------------
1146
+ def _covered(self, inst: Inst, path: tuple) -> bool:
1147
+ o = inst.origin
1148
+ if o is None:
1149
+ return False
1150
+ want = "__".join(path)
1151
+ for op in o.ops:
1152
+ if op.kind == "sr":
1153
+ if op.data is None:
1154
+ return True
1155
+ if any(p == want or p.startswith(want + "__") for p in op.data):
1156
+ return True
1157
+ elif op.kind == "pf":
1158
+ for spec in op.data:
1159
+ if spec.path and (spec.path == want or spec.path.startswith(want + "__")):
1160
+ return True
1161
+ elif op.kind in ("values",):
1162
+ return True
1163
+ return False
1164
+
1165
+ def _lazy_ok(self, inst: Inst) -> bool:
1166
+ if not SETTINGS["orm_lazy_loads"] or not self.emit:
1167
+ return False
1168
+ return bool(inst.row or (inst.per_iter and self.loop >= inst.per_iter))
1169
+
1170
+ def lazy_fk(self, node: ast.Attribute, inst: Inst, f, child: Inst) -> None:
1171
+ if not self._lazy_ok(inst) or inst.new:
1172
+ return
1173
+ path = inst.path + (f.name,)
1174
+ if self._covered(inst, path):
1175
+ return
1176
+ key = (inst.name.split(".")[0], path, inst.model.table)
1177
+ if key in self.lazy_seen:
1178
+ return
1179
+ self.lazy_seen.add(key)
1180
+ t = f.target
1181
+ if t is None or not t.table or t.pk is None:
1182
+ return
1183
+ b = Build(t)
1184
+ tcol = t.fields[f.to_field].column if f.to_field and f.to_field in t.fields else t.pk.column
1185
+ who = unmark(inst.name or inst.model.name.lower())
1186
+ sql = b.select(extra_where=[f"{b.root}.{tcol} = " + marker(f"{who}.{f.column}")], limit="21", order=False)
1187
+ if inst.origin is not None:
1188
+ conf = MEDIUM
1189
+ why = (f"lazy load of `{'.'.join(path)}` for each row: the queryset the rows were loaded with in this function has no "
1190
+ "select_related/prefetch_related for it")
1191
+ else:
1192
+ conf = LOW
1193
+ why = (f"lazy load of `{'.'.join(path)}`; assumed: the instance was loaded without select_related/prefetch_related for it "
1194
+ "(it was loaded outside this function)")
1195
+ if inst.row and not (inst.per_iter and self.loop >= inst.per_iter):
1196
+ why += "; runs once per row the serializer or resolver handles"
1197
+ if not f.null:
1198
+ pass
1199
+ self.raw_site(node, t, sql, "lazy_load", max(conf, inst.conf if inst.origin is None else conf), [why],
1200
+ in_loop=bool(inst.per_iter and self.loop >= inst.per_iter), sink=src(node))
1201
+ self.dj.lazy += 1
1202
+
1203
+ def lazy_rel(self, node: ast.Attribute, inst: Inst, attr: str, base: QS) -> None:
1204
+ if not self._lazy_ok(inst):
1205
+ return
1206
+ if self._covered(inst, inst.path + (attr,)):
1207
+ return
1208
+ key = (inst.name.split(".")[0], inst.path + (attr,), inst.model.table)
1209
+ if key in self.lazy_seen:
1210
+ return
1211
+ self.lazy_seen.add(key)
1212
+ b = Build(base.model).apply(base)
1213
+ conf = MEDIUM if inst.origin is not None else LOW
1214
+ why = f"lazy load of the reverse one-to-one `{attr}` for each row"
1215
+ self.raw_site(node, base.model, b.select(limit="21", order=False), "lazy_load", conf, [why],
1216
+ in_loop=bool(inst.per_iter and self.loop >= inst.per_iter), sink=src(node))
1217
+ self.dj.lazy += 1
1218
+
1219
+ # ---- calls -------------------------------------------------------------------------------------------------
1220
+ def args_use(self, call: ast.Call, how: str = "") -> None:
1221
+ for a in call.args:
1222
+ self.use(a, how)
1223
+ for k in call.keywords:
1224
+ if k.arg in ("queryset", "qs"):
1225
+ v = self.ev(k.value) # a queryset handed over as an option is not run here
1226
+ if isinstance(v, Mgr):
1227
+ v = v.base
1228
+ if isinstance(v, QS) and k.arg == "queryset" and self.field_validation(call, k.value, v):
1229
+ continue
1230
+ if isinstance(v, QS):
1231
+ for r in v.roots:
1232
+ self.dj.root_reason.setdefault(r, "queryset handed to a framework option (`queryset=`), which runs it elsewhere")
1233
+ else:
1234
+ self.use(k.value, how)
1235
+
1236
+ def field_validation(self, call: ast.Call, node: ast.AST, qs: QS) -> bool:
1237
+ """`queryset=X.objects...` handed to a model choice field or filter (Django forms ModelChoiceField /
1238
+ ModelMultipleChoiceField, django-filter ModelChoiceFilter / ModelMultipleChoiceFilter, DRF RelatedField and
1239
+ their subclasses): the field runs the queryset when it validates submitted values, `get(<key>=value)` for a
1240
+ single value and `filter(<key>__in=values)` for several, the key being `to_field_name` / `slug_field` or the
1241
+ primary key. That statement is the site. A field whose lookup is its own (content-type fields parse
1242
+ "app.model") gets a run-time predicate. False when the callee is not such a field."""
1243
+ name = (dotted(call.func) or "").split(".")[-1]
1244
+ if not FIELD_CALLEE.search(name):
1245
+ return False
1246
+ multiple = bool(re.search(r"Multiple", name))
1247
+ key = str_const(kwarg(call, "to_field_name")) or str_const(kwarg(call, "slug_field")) or "pk"
1248
+ notes = [f"queryset handed to {name}: run when the field validates submitted values"]
1249
+ if kwarg(call, "many") is not None and not multiple:
1250
+ # DRF `many=True`: a ManyRelatedField validates each value through the child field, one get() per value
1251
+ notes.append("many=True: one get() per submitted value")
1252
+ conf = MEDIUM
1253
+ if "ContentType" in name:
1254
+ label = f"lookup made by {name} from the submitted value"
1255
+ pred = (lambda b, label=label: marker(label))
1256
+ conf = LOW
1257
+ elif multiple:
1258
+ def pred(b, key=key):
1259
+ return b.lookup(key + "__in", lambda b2, op: "(" + marker("values submitted to the field") + ")")
1260
+ else:
1261
+ def pred(b, key=key):
1262
+ return b.lookup(key, lambda b2, op: marker("value submitted to the field"))
1263
+ q = qs.add(Op("where", (pred, False, f"{key} from {name}"), line=getattr(node, "lineno", 0)), conf=conf)
1264
+ b, notes0, conf0 = self.compile(q)
1265
+ if multiple:
1266
+ sql = b.select()
1267
+ op = "select"
1268
+ else:
1269
+ sql = b.select(limit="21" if b.hi is None else None, order=False)
1270
+ op = "get"
1271
+ notes, conf = self._finish(b, notes0 + notes, max(conf0, conf))
1272
+ self.site(node, q, sql, op, conf, notes)
1273
+ return True
1274
+
1275
+ def ev_call(self, call: ast.Call):
1276
+ fn = call.func
1277
+ dj = self.dj
1278
+ if call.args:
1279
+ # `SomeQuerySet(self.model, using=self._db)` / `self._queryset_class(self.model, ...)`: a queryset of that model
1280
+ callee = dotted(fn) or ""
1281
+ last = callee.split(".")[-1]
1282
+ if last.endswith(("QuerySet", "Queryset")) or last == "_queryset_class":
1283
+ first = self.ev(call.args[0])
1284
+ if isinstance(first, ModelRef) and first.model.table:
1285
+ sv = self.self_val
1286
+ base = sv.base if isinstance(sv, Mgr) else None
1287
+ qcls = dj.project.resolve_class(self.mod, callee) if last != "_queryset_class" else None
1288
+ return QS(first.model, roots=base.roots if base is not None else frozenset(), conf=first.conf,
1289
+ qcls=qcls or (base.qcls if base is not None else None), sink=base.sink if base is not None else "")
1290
+ if isinstance(fn, ast.Attribute):
1291
+ method = fn.attr
1292
+ # super().method(...)
1293
+ if isinstance(fn.value, ast.Call) and isinstance(fn.value.func, ast.Name) and fn.value.func.id == "super":
1294
+ return self.super_call(call, method)
1295
+ recv = self.ev(fn.value)
1296
+ if isinstance(recv, Mgr):
1297
+ return self.mgr_call(call, recv, method)
1298
+ if isinstance(recv, QS):
1299
+ return self.qs_call(call, recv, method)
1300
+ if isinstance(recv, Inst):
1301
+ return self.inst_call(call, recv, method)
1302
+ if isinstance(recv, ModelRef):
1303
+ return self.model_call(call, recv, method)
1304
+ if isinstance(recv, SelfV):
1305
+ return self.self_call(call, recv, method)
1306
+ if isinstance(recv, QObj):
1307
+ self.args_use(call)
1308
+ return recv
1309
+ if isinstance(recv, Seq):
1310
+ self.args_use(call)
1311
+ return recv.elem if method in ("pop", "popleft") else None
1312
+ if recv is UNK:
1313
+ self.args_use(call)
1314
+ return UNK
1315
+ # module.function(...)
1316
+ nm = dotted(fn)
1317
+ if nm and recv is None:
1318
+ last = nm.split(".")[-1]
1319
+ if last in ("get_object_or_404", "get_list_or_404", "aget_object_or_404", "aget_list_or_404"):
1320
+ return self.shortcut(call, last)
1321
+ if last == "get_model" or last == "get_user_model":
1322
+ ref = self.model_from_call(call)
1323
+ if ref is not None:
1324
+ return ref
1325
+ if last in EXPR_NAMES and last != "Q":
1326
+ return self._x(call)
1327
+ if last == "Q":
1328
+ return self._q(call)
1329
+ if last == "Prefetch":
1330
+ return self.prefetch_obj(call)
1331
+ got = dj.project.resolve(self.mod, nm)
1332
+ if got is not None and got[0] == "func":
1333
+ return self.call_function(call, got[1], None, got[2])
1334
+ if got is not None and got[0] == "class":
1335
+ ref = dj.model_ref(self.mod, nm)
1336
+ if ref is not None:
1337
+ self.args_use(call)
1338
+ return Inst(ref.model, new=True, per_iter=self.loop)
1339
+ # unknown receiver: a call only a queryset has is counted so the gap is measurable
1340
+ if recv is None and (method in DISTINCT or (method in ("filter", "exclude", "get") and any(
1341
+ k.arg and "__" in k.arg for k in call.keywords))):
1342
+ if id(call) not in dj.counted_nodes:
1343
+ dj.counted_nodes.add(id(call))
1344
+ if not _inner_counted(fn.value, dj.counted_nodes):
1345
+ dj.stats.seen += 1
1346
+ dj.stats.miss("receiver type unknown (no model could be attached to the variable)", f"{self.mod.rel}:{call.lineno}")
1347
+ self.args_use(call)
1348
+ return UNK
1349
+ self.args_use(call, "passed to " + method + "()")
1350
+ return None
1351
+ if isinstance(fn, ast.Name):
1352
+ name = fn.id
1353
+ v = self.env.get(name)
1354
+ if isinstance(v, ModelRef) or (v is None and name not in self.env and dj.model_ref(self.mod, name) is not None):
1355
+ ref = v if isinstance(v, ModelRef) else dj.model_ref(self.mod, name)
1356
+ self.args_use(call)
1357
+ return Inst(ref.model, new=True, per_iter=self.loop)
1358
+ if name in ("get_object_or_404", "get_list_or_404", "aget_object_or_404", "aget_list_or_404"):
1359
+ return self.shortcut(call, name)
1360
+ if name == "Q":
1361
+ return self._q(call)
1362
+ if name in EXPR_NAMES:
1363
+ return self._x(call)
1364
+ if name == "Prefetch":
1365
+ return self.prefetch_obj(call)
1366
+ if name == "get_user_model" and dj.index.auth_user is not None:
1367
+ return ModelRef(dj.index.auth_user)
1368
+ if name == "super":
1369
+ return SuperV(self.self_val)
1370
+ if name in CONSUMERS and call.args:
1371
+ first = self.ev(call.args[0])
1372
+ elem = None
1373
+ if isinstance(first, QS):
1374
+ self.emit_select(call.args[0], first, share=first)
1375
+ elem = None if first.has("values") else Inst(first.model, origin=first, conf=first.conf)
1376
+ elif isinstance(first, Seq):
1377
+ elem = first.elem
1378
+ for a in call.args[1:]:
1379
+ self.use(a)
1380
+ for k in call.keywords:
1381
+ self.use(k.value)
1382
+ if name == "enumerate":
1383
+ return Seq(TupleV([None, elem]))
1384
+ return Seq(elem) if elem is not None else None
1385
+ if name in ("cast",) and len(call.args) == 2:
1386
+ v2 = self.ev(call.args[1])
1387
+ return v2 if v2 is not None else self.ann_value(call.args[0])
1388
+ if name in ("isinstance", "hasattr", "getattr", "id", "type", "repr", "str", "print") and call.args:
1389
+ first = self.ev(call.args[0])
1390
+ for a in call.args[1:]:
1391
+ self.use(a)
1392
+ if name in ("str", "repr", "print"):
1393
+ self.consume(call.args[0], first)
1394
+ if name == "getattr" and isinstance(first, Inst) and len(call.args) >= 2 and str_const(call.args[1]):
1395
+ fake = ast.Attribute(value=call.args[0], attr=str_const(call.args[1]), ctx=ast.Load())
1396
+ ast.copy_location(fake, call)
1397
+ return self.inst_attr(fake, first)
1398
+ return None
1399
+ if name == "next" and call.args:
1400
+ first = self.ev(call.args[0])
1401
+ return first.elem if isinstance(first, Seq) else None
1402
+ if name not in self.env:
1403
+ got = dj.project.resolve(self.mod, name)
1404
+ if got is not None and got[0] == "func":
1405
+ return self.call_function(call, got[1], None, got[2])
1406
+ self.args_use(call, "" if hasattr(builtins, name) else f"passed to {name}()")
1407
+ return None
1408
+ self.use(fn)
1409
+ self.args_use(call)
1410
+ return None
1411
+
1412
+ def _held(self, build, node):
1413
+ """Build a predicate or expression function, keeping apart the querysets it embeds (subqueries)."""
1414
+ saved, self._absorbed = self._absorbed, frozenset()
1415
+ try:
1416
+ fn = build(node)
1417
+ for r in self._absorbed:
1418
+ self.dj.root_reason.setdefault(r, "used as a subquery of a queryset that was not seen to run in the function")
1419
+ return fn, self._absorbed
1420
+ finally:
1421
+ self._absorbed = saved
1422
+
1423
+ def _q(self, node: ast.AST) -> QObj:
1424
+ fn, roots = self._held(self.pfn, node)
1425
+ return QObj(fn, src(node), roots)
1426
+
1427
+ def _x(self, node: ast.AST) -> XV:
1428
+ fn, roots = self._held(self.xfn, node)
1429
+ return XV(fn, roots)
1430
+
1431
+ def _took(self, v):
1432
+ """A held Q object or expression is used: the querysets it embeds go with the user."""
1433
+ self._absorbed = self._absorbed | v.roots
1434
+ return v.fn
1435
+
1436
+ def shortcut(self, call: ast.Call, name: str):
1437
+ if not call.args:
1438
+ return None
1439
+ first = self.ev(call.args[0])
1440
+ qs = first.base if isinstance(first, Mgr) else first
1441
+ if isinstance(first, ModelRef):
1442
+ qs = self.manager(call.args[0], first.model, first.model.managers.get("_default_manager") or Manager("objects"), first.conf).base
1443
+ if not isinstance(qs, QS):
1444
+ for a in call.args[1:]:
1445
+ self.use(a)
1446
+ return None
1447
+ fake = ast.Call(func=call.func, args=call.args[1:], keywords=call.keywords)
1448
+ ast.copy_location(fake, call)
1449
+ qs = self.filter_op(qs, fake, False)
1450
+ if "list" in name:
1451
+ self.emit_select(call, qs)
1452
+ return Seq(Inst(qs.model, origin=qs))
1453
+ return self.terminal(call, qs, "get", fake, filtered=True)
1454
+
1455
+ def prefetch_obj(self, call: ast.Call):
1456
+ path = str_const(call.args[0]) if call.args else str_const(kwarg(call, "lookup"))
1457
+ qn = kwarg(call, "queryset") or (call.args[1] if len(call.args) > 1 else None)
1458
+ qs = self.ev(qn) if qn is not None else None
1459
+ if isinstance(qs, Mgr):
1460
+ qs = qs.base
1461
+ to_attr = str_const(kwarg(call, "to_attr")) or (str_const(call.args[2]) if len(call.args) > 2 else None)
1462
+ return PrefetchV(path, qs if isinstance(qs, QS) else None, to_attr)
1463
+
1464
+ # ---- helper functions ----------------------------------------------------------------------------------------
1465
+ def call_function(self, call: ast.Call, mod: Mod, cls: Cls | None, fn_def, self_val=None, capture: list | None = None):
1466
+ pos = [self.ev(a) for a in call.args]
1467
+ kws = {k.arg: self.ev(k.value) for k in call.keywords if k.arg}
1468
+ for k in call.keywords:
1469
+ if not k.arg:
1470
+ self.use(k.value)
1471
+ typed = any(isinstance(v, (QS, Inst, ModelRef, Seq, QObj, Mgr)) for v in pos + list(kws.values()))
1472
+ got = self.call_def(cls, fn_def, self_val, mod, pos, kws, capture, call if capture is not None else None)
1473
+ # a queryset passed to a helper that hands a queryset back is refined there, not run here
1474
+ absorbed = isinstance(got, QS)
1475
+ for node, v in list(zip(call.args, pos)) + [(k.value, kws.get(k.arg)) for k in call.keywords if k.arg]:
1476
+ if isinstance(v, QS):
1477
+ if absorbed and (v.roots <= got.roots or not v.roots):
1478
+ continue
1479
+ self.consume(node, v, f"passed to {fn_def.name}()")
1480
+ if got is None and fn_def.returns is not None:
1481
+ w = Walker(self.dj, mod, cls, "", emit=False, depth=self.depth + 1)
1482
+ got = w.ann_value(fn_def.returns)
1483
+ if isinstance(got, Inst):
1484
+ got.per_iter = self.loop
1485
+ _ = typed
1486
+ return got
1487
+
1488
+ def call_def(self, cls: Cls | None, fn_def, self_val, mod: Mod | None, pos: list, kws: dict, capture: list | None = None,
1489
+ fwd_call: ast.Call | None = None):
1490
+ """Evaluate a function of the project for the value it returns (no sites are emitted for its body here: it is
1491
+ walked on its own)."""
1492
+ dj = self.dj
1493
+ mod = mod or (cls.mod if cls is not None else self.mod)
1494
+ if self.depth >= SETTINGS["orm_helper_depth"] or id(fn_def) in dj._stack:
1495
+ return None
1496
+ # the result depends on the function and on what kind of value each argument is, so it is read once per
1497
+ # such signature; querysets and Q objects passed in carry state of their own and are never shared
1498
+ sigs = [_sig(self_val)] + [_sig(v) for v in pos] + [_sig(v) for _, v in sorted(kws.items())]
1499
+ key = None
1500
+ if capture is None and False not in sigs:
1501
+ key = (id(fn_def), tuple(sigs), tuple(sorted(kws)))
1502
+ if key in dj._helper_cache:
1503
+ got = dj._helper_cache[key]
1504
+ if isinstance(got, Inst):
1505
+ return Inst(got.model, origin=got.origin, path=got.path, per_iter=self.loop, conf=got.conf, new=got.new)
1506
+ return got.with_() if isinstance(got, QS) else got
1507
+ if isinstance(self_val, Inst):
1508
+ self_val = Inst(self_val.model, conf=self_val.conf, name="self")
1509
+ params = list(fn_def.args.posonlyargs) + list(fn_def.args.args)
1510
+ decos = {(dotted(d) or dotted(getattr(d, "func", None)) or "").split(".")[-1] for d in fn_def.decorator_list}
1511
+ is_method = cls is not None and "staticmethod" not in decos and cls.methods.get(fn_def.name) is fn_def
1512
+ names = [a.arg for a in (params[1:] if is_method and params else params)]
1513
+ preset = {}
1514
+ for i, v in enumerate(pos):
1515
+ if i < len(names) and v is not None:
1516
+ preset[names[i]] = _as_param(v, names[i])
1517
+ for k, v in kws.items():
1518
+ if v is not None:
1519
+ preset[k] = _as_param(v, k)
1520
+ dj._stack.append(id(fn_def))
1521
+ try:
1522
+ w = Walker(dj, mod, cls, "", func=fn_def, emit=False, depth=self.depth + 1, self_val=self_val, preset=preset)
1523
+ w.loop = 0
1524
+ w.captured = capture
1525
+ if fwd_call is not None and (fn_def.args.vararg or fn_def.args.kwarg):
1526
+ # `def filter(self, *args, **kwargs): ... return super().filter(*args, **kwargs)`: what the caller
1527
+ # passed is what gets forwarded
1528
+ w.fwd = (fn_def.args.vararg.arg if fn_def.args.vararg else None, fn_def.args.kwarg.arg if fn_def.args.kwarg else None,
1529
+ [a for a in fwd_call.args[len(names):] if not isinstance(a, ast.Starred)],
1530
+ [k for k in fwd_call.keywords if k.arg and k.arg not in names], self)
1531
+ try:
1532
+ w.run(fn_def.body)
1533
+ except RecursionError:
1534
+ return None
1535
+ got = _combine_returns(w.returns)
1536
+ finally:
1537
+ dj._stack.pop()
1538
+ if isinstance(got, Inst):
1539
+ got = Inst(got.model, origin=got.origin, path=got.path, per_iter=self.loop, conf=got.conf, new=got.new)
1540
+ if key is not None:
1541
+ dj._helper_cache[key] = got
1542
+ return got.with_() if isinstance(got, QS) else got
1543
+ return got
1544
+
1545
+ def super_call(self, call: ast.Call, method: str):
1546
+ sv = self.self_val
1547
+ if isinstance(sv, Mgr) and method == "get_queryset":
1548
+ return QS(sv.model, sv.base.ops if not sv.plain else (), sv.base.roots, sv.base.conf, qcls=sv.base.qcls)
1549
+ if isinstance(sv, Mgr):
1550
+ return self.qs_call(call, sv.base, method, builtin_only=True)
1551
+ if isinstance(sv, QS):
1552
+ return self.qs_call(call, sv, method, builtin_only=True)
1553
+ if isinstance(sv, SelfV) and self.cls is not None:
1554
+ # the parent's method when it is the project's, else the framework's default
1555
+ mro = self.dj.project.mro(sv.cls)
1556
+ here = False
1557
+ for c in mro:
1558
+ if c is self.cls:
1559
+ here = True
1560
+ continue
1561
+ if here and method in c.methods:
1562
+ pos = [self.ev(a) for a in call.args]
1563
+ return self.call_def(c, c.methods[method], sv, c.mod, pos, {})
1564
+ return self.framework_method(call, sv, method)
1565
+ if isinstance(sv, QS):
1566
+ return self.qs_call(call, sv, method) if method in QS_PASS else None
1567
+ self.args_use(call)
1568
+ return None
1569
+
1570
+ def self_call(self, call: ast.Call, sv: SelfV, method: str):
1571
+ found = self.dj.project.find_method(sv.cls, method)
1572
+ if found is not None:
1573
+ return self.call_function(call, found[0].mod, found[0], found[1], sv)
1574
+ return self.framework_method(call, sv, method)
1575
+
1576
+ def framework_method(self, call: ast.Call, sv: SelfV, method: str):
1577
+ """What Django / DRF generic views do when the class does not override the method."""
1578
+ if method == "get_queryset":
1579
+ self.args_use(call)
1580
+ return self.class_queryset(sv)
1581
+ if method == "filter_queryset" and call.args:
1582
+ v = self.ev(call.args[0])
1583
+ if isinstance(v, QS):
1584
+ return v.add(Op("mark", "filters of the view's filter backends"), conf=MEDIUM)
1585
+ return v
1586
+ if method == "get_object":
1587
+ self.args_use(call)
1588
+ found = self.dj.project.find_method(sv.cls, "get_queryset")
1589
+ qs = self.call_def(found[0], found[1], sv, found[0].mod, [], {}) if found else self.class_queryset(sv)
1590
+ if isinstance(qs, Mgr):
1591
+ qs = qs.base
1592
+ if isinstance(qs, QS) and qs.model.pk is not None:
1593
+ fn = lambda b: f"{b.pk_sql()} = " + marker("lookup value from the URL")
1594
+ one = qs.add(Op("where", (fn, False, "pk")), conf=MEDIUM, note="get_object(): the view's queryset narrowed to the URL's lookup field")
1595
+ b, notes, conf = self.compile(one)
1596
+ self.site(call, one, b.select(limit="21", order=False), "get", conf, notes)
1597
+ return Inst(qs.model, origin=qs, per_iter=self.loop, conf=MEDIUM)
1598
+ return None
1599
+ if method == "paginate_queryset" and call.args:
1600
+ v = self.ev(call.args[0])
1601
+ if isinstance(v, QS):
1602
+ paged = v.add(Op("slice", (marker("page offset"), marker("page offset + page size"))),
1603
+ note="paginate_queryset(): the page is fetched with LIMIT/OFFSET (a COUNT of the same queryset runs first)")
1604
+ self.emit_select(call, paged)
1605
+ b, notes, conf = self.compile(v)
1606
+ self.site(call, v, b.count(), "count", conf, notes + ["paginate_queryset(): the paginator's count"])
1607
+ return Seq(Inst(v.model, origin=v))
1608
+ return None
1609
+ self.args_use(call, f"passed to {method}()")
1610
+ return None
1611
+
1612
+ def model_call(self, call: ast.Call, ref: ModelRef, method: str):
1613
+ m = ref.model
1614
+ if m.cls is not None:
1615
+ found = self.dj.project.find_method(m.cls, method)
1616
+ if found is not None:
1617
+ return self.call_function(call, found[0].mod, found[0], found[1], ref)
1618
+ self.args_use(call)
1619
+ return None
1620
+
1621
+ # ---- instances -----------------------------------------------------------------------------------------------
1622
+ def inst_call(self, call: ast.Call, inst: Inst, method: str):
1623
+ m = inst.model
1624
+ who = unmark(inst.name or m.name.lower())
1625
+ if method in ("save", "asave") and m.pk is not None and m.table:
1626
+ self.args_use(call)
1627
+ fields = kwarg(call, "update_fields")
1628
+ ok, names = const(fields)
1629
+ cols = None
1630
+ if fields is not None and ok and isinstance(names, list):
1631
+ cols = [m.field_by_attname(n).column for n in names if isinstance(n, str) and m.field_by_attname(n) is not None
1632
+ and m.field_by_attname(n).kind != "m2m"]
1633
+ if inst.new and fields is None:
1634
+ for sql in self.insert_sql(m, None, who):
1635
+ self.raw_site(call, m, sql, "insert", max(inst.conf, HIGH), ["save() of an object created in this function"])
1636
+ return None
1637
+ own = [f.column for f in m.columns() if not f.pk]
1638
+ computed = fields is not None and cols is None and not (isinstance(fields, ast.Constant) and fields.value is None)
1639
+ cols = cols if cols is not None else own
1640
+ if not cols:
1641
+ return None
1642
+ if computed:
1643
+ sets = marker(f"each column in {src(fields)}") + " = " + marker("its value")
1644
+ notes = ["save(update_fields=...) with a computed list: the columns set are a run-time part"]
1645
+ else:
1646
+ sets = ", ".join(f"{c} = " + marker(f"{who}.{c}") for c in cols)
1647
+ notes = [] if fields is not None else ["save(): Django sends this UPDATE, and an INSERT instead when the row does not exist yet"]
1648
+ sql = f"UPDATE {m.table} SET {sets} WHERE {m.table}.{m.pk.column} = " + marker(f"{who}.pk")
1649
+ self.raw_site(call, m, sql, "update", max(inst.conf, MEDIUM if fields is None or computed else inst.conf), notes)
1650
+ return None
1651
+ if method in ("delete", "adelete") and m.pk is not None and m.table and not call.args:
1652
+ sql = f"DELETE FROM {m.table} WHERE {m.table}.{m.pk.column} IN (" + marker(f"{who}.pk") + ")"
1653
+ self.raw_site(call, m, sql, "delete", max(inst.conf, MEDIUM),
1654
+ ["delete() of one object: related rows are collected and deleted first when the model has cascades"])
1655
+ return None
1656
+ if method in ("refresh_from_db", "arefresh_from_db") and m.pk is not None and m.table:
1657
+ b = Build(m)
1658
+ ok, names = const(kwarg(call, "fields") or (call.args[1] if len(call.args) > 1 else None))
1659
+ cols = None
1660
+ if ok and isinstance(names, list):
1661
+ cols = [f"{b.root}.{m.field_by_attname(n).column}" for n in names if isinstance(n, str) and m.field_by_attname(n) is not None]
1662
+ sql = b.select(cols=cols or None, extra_where=[f"{b.pk_sql()} = " + marker(f"{who}.pk")], limit="21", order=False)
1663
+ self.raw_site(call, m, sql, "get", max(inst.conf, HIGH), ["refresh_from_db()"])
1664
+ return None
1665
+ if m.cls is not None:
1666
+ found = self.dj.project.find_method(m.cls, method)
1667
+ if found is not None:
1668
+ return self.call_function(call, found[0].mod, found[0], found[1], inst)
1669
+ self.args_use(call)
1670
+ return None
1671
+
1672
+ def insert_sql(self, m: Model, given: dict | None, who: str = "") -> list[str]:
1673
+ """INSERT statements for one new object: the parent tables of multi-table inheritance first."""
1674
+ out = []
1675
+ chain = []
1676
+ cur = m
1677
+ while cur is not None:
1678
+ chain.append(cur)
1679
+ cur = cur.parents[0] if cur.parents and not cur.proxy else (cur.parents[0] if cur.proxy and cur.parents else None)
1680
+ seen_tables = set()
1681
+ for model in reversed(chain):
1682
+ if model.table in seen_tables or not model.table:
1683
+ continue
1684
+ seen_tables.add(model.table)
1685
+ cols, vals = [], []
1686
+ for f in model.columns():
1687
+ if f.pk and (f.type_name in ("AutoField", "BigAutoField", "SmallAutoField", "") or f.type_name.endswith("AutoField")) \
1688
+ and not (given and (f.name in given or "pk" in given or f.column in given)):
1689
+ continue
1690
+ cols.append(f.column)
1691
+ v = None
1692
+ if given is not None:
1693
+ v = given.get(f.name) or given.get(f.column) or (given.get("pk") if f.pk else None)
1694
+ if v is None:
1695
+ v = marker(f"{who}.{f.column}") if who else marker("default")
1696
+ vals.append(v)
1697
+ if cols:
1698
+ out.append(f"INSERT INTO {model.table} ({', '.join(cols)}) VALUES ({', '.join(vals)})")
1699
+ return out
1700
+
1701
+ # ---- managers and querysets --------------------------------------------------------------------------------
1702
+ def mgr_call(self, call: ast.Call, mgr: Mgr, method: str):
1703
+ p = self.dj.project
1704
+ # the related manager's own methods
1705
+ if mgr.base.lazy is not None and method in ("add", "remove", "clear", "set", "aadd", "aremove", "aclear", "aset"):
1706
+ self.args_use(call)
1707
+ return None
1708
+ if method == "model":
1709
+ self.args_use(call)
1710
+ return Inst(mgr.model, new=True, per_iter=self.loop)
1711
+ if mgr.mgr is not None and mgr.mgr.cls is not None and method != "get_queryset":
1712
+ found = p.find_method(mgr.mgr.cls, method)
1713
+ if found is not None:
1714
+ cap: list = []
1715
+ got = self.call_function(call, found[0].mod, found[0], found[1], Mgr(mgr.model, mgr.mgr, mgr.base, plain=mgr.plain), cap)
1716
+ builtin = method in TERMINALS or method in QS_PASS or (method[:1] == "a" and method[1:] in TERMINALS)
1717
+ if cap or (not builtin) or (isinstance(got, QS) and method in QS_PASS):
1718
+ self._replay(call, cap, method)
1719
+ if got is None and not cap:
1720
+ self._drop(mgr.base, "custom manager method whose result could not be followed")
1721
+ return got
1722
+ return self.qs_call(call, mgr.base, method, from_manager=True)
1723
+
1724
+ def _replay(self, call: ast.Call, captured: list, method: str) -> None:
1725
+ """Statements a custom manager/queryset method sends are reported where it is called, with the caller's
1726
+ queryset in place of the method's `self`."""
1727
+ for qs, model, sql, operation, conf, notes, conditional in captured:
1728
+ note = f"sent inside {method}()"
1729
+ if conditional:
1730
+ note += ", on one of its branches or in a loop there"
1731
+ conf = max(conf, MEDIUM)
1732
+ if qs is not None:
1733
+ self.site(call, qs, sql, operation, conf, list(notes) + [note])
1734
+ else:
1735
+ self.raw_site(call, model, sql, operation, conf, list(notes) + [note])
1736
+
1737
+ def custom_qs_method(self, qs: QS, method: str):
1738
+ p = self.dj.project
1739
+ classes = [qs.qcls] if qs.qcls is not None else []
1740
+ for mg in qs.model.managers.values():
1741
+ if mg.qs_cls is not None and mg.qs_cls not in classes:
1742
+ classes.append(mg.qs_cls)
1743
+ for c in classes:
1744
+ found = p.find_method(c, method)
1745
+ if found is not None:
1746
+ return found
1747
+ return None
1748
+
1749
+ def qs_call(self, call: ast.Call, qs: QS, method: str, from_manager: bool = False, builtin_only: bool = False):
1750
+ saved, self._absorbed = self._absorbed, frozenset()
1751
+ try:
1752
+ got = self._qs_call(call, qs, method, builtin_only)
1753
+ if isinstance(got, QS) and self._absorbed:
1754
+ for r in self._absorbed:
1755
+ self.dj.root_reason.setdefault(r, "used as a subquery of a queryset that was not seen to run in the function")
1756
+ st = got.state
1757
+ got = got.with_(roots=self._absorbed)
1758
+ got.state = st
1759
+ return got
1760
+ finally:
1761
+ self._absorbed = saved
1762
+
1763
+ def _qs_call(self, call: ast.Call, qs: QS, method: str, builtin_only: bool = False):
1764
+ name = method
1765
+ if name.startswith("a") and name[1:] in TERMINALS and name not in ("all", "aggregate", "alias", "annotate"):
1766
+ name = name[1:]
1767
+ if method == "model":
1768
+ self.args_use(call)
1769
+ return Inst(qs.model, new=True, per_iter=self.loop)
1770
+ found = self.custom_qs_method(qs, method) if not builtin_only else None
1771
+ if found is not None:
1772
+ cap: list = []
1773
+ got = self.call_function(call, found[0].mod, found[0], found[1], qs, cap)
1774
+ builtin = name in TERMINALS or name in QS_PASS
1775
+ if cap or (not builtin) or (isinstance(got, QS) and name in QS_PASS):
1776
+ self._replay(call, cap, method)
1777
+ if got is None and not cap:
1778
+ self._drop(qs, "custom queryset method whose result could not be followed")
1779
+ return got
1780
+ if name == "_raw_delete":
1781
+ fake = ast.Call(func=call.func, args=[], keywords=[])
1782
+ ast.copy_location(fake, call)
1783
+ return self.terminal(call, qs, "delete", fake)
1784
+ if name in TERMINALS:
1785
+ return self.terminal(call, qs, name, call)
1786
+ if name == "raw":
1787
+ self.args_use(call)
1788
+ for r in qs.roots:
1789
+ self.dj.root_reason.setdefault(r, "raw SQL (`.raw()`): reported by the SQL-string extractor, not as an ORM site")
1790
+ return None
1791
+ if name not in QS_PASS:
1792
+ self.args_use(call)
1793
+ for r in qs.roots:
1794
+ self.dj.root_reason.setdefault(r, "method is not a queryset method we know and is not defined on the model's manager or queryset")
1795
+ return None
1796
+ if name in ("all", "_clone", "_chain", "using", "db_manager", "get_queryset", "nocache", "no_cache", "cache", "with_tree_fields"):
1797
+ self.args_use(call)
1798
+ return qs.with_()
1799
+ if name in ("filter", "exclude", "complex_filter"):
1800
+ return self.filter_op(qs, call, name == "exclude")
1801
+ if name == "order_by" or name == "order_siblings_by":
1802
+ fns = [self.order_fn(a) for a in call.args]
1803
+ return qs.add(Op("order", fns, line=call.lineno))
1804
+ if name == "distinct":
1805
+ return qs.add(Op("distinct", [s for s in (str_const(a) for a in call.args) if s]))
1806
+ if name in ("values", "values_list"):
1807
+ fields = []
1808
+ for a in call.args:
1809
+ s = str_const(a)
1810
+ if s is not None:
1811
+ fields.append((None, self.path_fn(s), s))
1812
+ elif isinstance(a, ast.Starred):
1813
+ fields.append((None, (lambda b, t=src(a): marker(t)), None))
1814
+ else:
1815
+ fields.append((None, self.xfn(a), None))
1816
+ for k in call.keywords:
1817
+ if k.arg in ("flat", "named") and name == "values_list":
1818
+ continue
1819
+ if k.arg is None:
1820
+ fields.append((None, (lambda b, t="**" + src(k.value): marker(t)), None))
1821
+ else:
1822
+ fields.append((k.arg, self.xfn(k.value), None))
1823
+ ok, flat = const(kwarg(call, "flat"))
1824
+ return qs.add(Op("values", (fields, bool(ok and flat))))
1825
+ if name in ("only", "defer"):
1826
+ names = [str_const(a) for a in call.args]
1827
+ if any(n is None for n in names):
1828
+ self.args_use(call)
1829
+ return qs.with_(conf=MEDIUM, note=f"{name}() with computed field names: all columns shown")
1830
+ return qs.add(Op(name, names))
1831
+ if name == "select_related":
1832
+ names = [str_const(a) for a in call.args]
1833
+ if call.args and all(isinstance(a, ast.Constant) and a.value is None for a in call.args):
1834
+ return qs.add(Op("sr", []))
1835
+ if any(n is None for n in names):
1836
+ self.args_use(call)
1837
+ return qs.add(Op("sr", [n for n in names if n]), conf=MEDIUM, note="select_related() with computed names: only the literal ones are joined")
1838
+ if not names:
1839
+ return qs.add(Op("sr", None), conf=MEDIUM, note="select_related() without arguments: the model's non-null foreign keys are joined (first level shown)")
1840
+ return qs.add(Op("sr", names))
1841
+ if name == "prefetch_related":
1842
+ specs = []
1843
+ note = ""
1844
+ for a in call.args:
1845
+ s = str_const(a)
1846
+ if s is not None:
1847
+ specs.append(PrefetchV(s, None, None))
1848
+ continue
1849
+ v = self.ev(a)
1850
+ if isinstance(v, PrefetchV) and v.path:
1851
+ specs.append(v)
1852
+ else:
1853
+ note = "prefetch_related() with computed lookups: those statements are not shown"
1854
+ return qs.add(Op("pf", specs), conf=MEDIUM if note else None, note=note)
1855
+ if name in ("annotate", "alias"):
1856
+ names = []
1857
+ for a in call.args:
1858
+ nm = _default_alias(a)
1859
+ names.append((nm or src(a), self.xfn(a)))
1860
+ conf = None
1861
+ note = ""
1862
+ for k in call.keywords:
1863
+ if k.arg is None:
1864
+ conf, note = MEDIUM, "annotate(**computed): those expressions are not shown"
1865
+ self.use(k.value)
1866
+ continue
1867
+ names.append((k.arg, self.xfn(k.value)))
1868
+ return qs.add(Op("annot", (names, name == "annotate")), conf=conf, note=note)
1869
+ if name == "reverse":
1870
+ return qs.add(Op("reverse"))
1871
+ if name == "none":
1872
+ return qs.add(Op("none"))
1873
+ if name == "select_for_update":
1874
+ ok, nowait = const(kwarg(call, "nowait"))
1875
+ ok2, skip = const(kwarg(call, "skip_locked"))
1876
+ return qs.add(Op("lock", " FOR UPDATE" + (" NOWAIT" if ok and nowait else "") + (" SKIP LOCKED" if ok2 and skip else "")))
1877
+ if name in ("iterator", "aiterator"):
1878
+ self.args_use(call)
1879
+ self.emit_select(call, qs, share=qs)
1880
+ return Seq(None if qs.has("values") else Inst(qs.model, origin=qs, conf=qs.conf))
1881
+ if name in ("union", "intersection", "difference"):
1882
+ roots = frozenset()
1883
+ for a in call.args:
1884
+ v = self.ev(a)
1885
+ if isinstance(v, QS):
1886
+ roots |= v.roots
1887
+ return qs.add(Op("mark", f"{name} with {', '.join(src(a) for a in call.args)}"), conf=MEDIUM, roots=roots,
1888
+ note=f"{name}(): the other querysets are not shown")
1889
+ if name == "extra":
1890
+ self.args_use(call)
1891
+ return qs.add(Op("mark", "extra(" + ", ".join(k.arg or "**" for k in call.keywords) + ")"), conf=MEDIUM,
1892
+ note="extra(): raw SQL fragments are shown as a run-time part")
1893
+ if name in ("dates", "datetimes") and call.args:
1894
+ path, kind = str_const(call.args[0]), (str_const(call.args[1]) if len(call.args) > 1 else None) or str_const(kwarg(call, "kind"))
1895
+ if path and kind:
1896
+ fn = lambda b, path=path, kind=kind: f"DATE_TRUNC('{kind}', {b.resolve(path, left=True).sql})"
1897
+ out = qs.add(Op("values", ([("datefield", fn, None)], True))).add(Op("distinct", []))
1898
+ return out.add(Op("order", [lambda b: "datefield ASC"]))
1899
+ return None
1900
+ self.args_use(call)
1901
+ return qs.with_(conf=MEDIUM)
1902
+
1903
+ def filter_op(self, qs: QS, call: ast.Call, negate: bool) -> QS:
1904
+ fns = []
1905
+ labels = []
1906
+ roots = frozenset()
1907
+ fwd = self.fwd
1908
+ for a in call.args:
1909
+ if isinstance(a, ast.Starred):
1910
+ if fwd is not None and isinstance(a.value, ast.Name) and a.value.id == fwd[0]:
1911
+ for node in fwd[2]:
1912
+ fns.append(fwd[4].pfn(node))
1913
+ labels.append(src(node))
1914
+ self._absorbed = self._absorbed | fwd[4]._absorbed
1915
+ fwd[4]._absorbed = frozenset()
1916
+ continue
1917
+ fns.append(lambda b, t=src(a): marker(t))
1918
+ else:
1919
+ fns.append(self.pfn(a))
1920
+ labels.append(src(a))
1921
+ for k in call.keywords:
1922
+ if k.arg is None:
1923
+ if fwd is not None and isinstance(k.value, ast.Name) and k.value.id == fwd[1]:
1924
+ for kk in fwd[3]:
1925
+ fns.append(fwd[4].kwfn(kk.arg, kk.value))
1926
+ labels.append(kk.arg + "=" + src(kk.value))
1927
+ self._absorbed = self._absorbed | fwd[4]._absorbed
1928
+ fwd[4]._absorbed = frozenset()
1929
+ continue
1930
+ fns.append(lambda b, t="**" + src(k.value): marker(t))
1931
+ self.use(k.value)
1932
+ else:
1933
+ fns.append(self.kwfn(k.arg, k.value))
1934
+ labels.append((k.arg or "**") + "=" + src(k.value))
1935
+ if not fns:
1936
+ return qs.with_()
1937
+ fn = _combine(fns, " AND ")
1938
+ roots = self._absorbed
1939
+ self._absorbed = frozenset()
1940
+ for r in roots:
1941
+ self.dj.root_reason.setdefault(r, "used as a subquery of a queryset that was not seen to run in the function")
1942
+ return qs.add(Op("where", (fn, negate, ", ".join(labels)), line=call.lineno), roots=roots)
1943
+
1944
+ _absorbed: frozenset = frozenset()
1945
+
1946
+ # ---- values, expressions, predicates -----------------------------------------------------------------------
1947
+ def path_fn(self, path: str):
1948
+ def fn(b: Build, path=path):
1949
+ return b.resolve(path, left=True).sql
1950
+ return fn
1951
+
1952
+ def order_fn(self, node: ast.AST):
1953
+ s = str_const(node)
1954
+ if s is not None:
1955
+ if s == "?":
1956
+ return lambda b: "RANDOM()"
1957
+ desc = s.startswith("-")
1958
+ path = s.lstrip("-+")
1959
+
1960
+ def fn(b: Build, path=path, desc=desc):
1961
+ try:
1962
+ return b.resolve(path, left=True).sql + (" DESC" if desc else " ASC")
1963
+ except Unresolved:
1964
+ b.unresolved.append("order_by " + path)
1965
+ return marker(("-" if desc else "") + path)
1966
+ return fn
1967
+ # F("x").desc(nulls_last=True), Lower("name").asc()
1968
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr in ("desc", "asc"):
1969
+ inner = self.xfn(node.func.value)
1970
+ suffix = " DESC" if node.func.attr == "desc" else " ASC"
1971
+ ok, nl = const(kwarg(node, "nulls_last"))
1972
+ ok2, nf = const(kwarg(node, "nulls_first"))
1973
+ suffix += " NULLS LAST" if ok and nl else (" NULLS FIRST" if ok2 and nf else "")
1974
+ return lambda b: _safe(inner, b, src(node)) + suffix
1975
+ if isinstance(node, ast.Starred) or isinstance(node, ast.Name) and not isinstance(self.env.get(node.id), XV):
1976
+ self.use(node.value if isinstance(node, ast.Starred) else node)
1977
+ return lambda b, t=src(node): marker(t)
1978
+ inner = self.xfn(node)
1979
+ return lambda b: _safe(inner, b, src(node)) + " ASC"
1980
+
1981
+ def valfn(self, node: ast.AST):
1982
+ """A lookup's right-hand side as a function (build, lookup name) -> SQL."""
1983
+ ok, v = const(node)
1984
+ if ok:
1985
+ if isinstance(v, list):
1986
+ lits = [sql_literal(x) for x in v]
1987
+ if all(x is not None for x in lits):
1988
+ def fn(b, op, lits=lits, node=node):
1989
+ if op == "in":
1990
+ return "(" + ", ".join(lits) + ")" if lits else "(NULL)"
1991
+ if op == "range" and len(lits) == 2:
1992
+ return f"{lits[0]} AND {lits[1]}"
1993
+ return marker(src(node))
1994
+ return fn
1995
+ else:
1996
+ s = sql_literal(v)
1997
+ if s is not None:
1998
+ return lambda b, op, s=s: s
1999
+ if isinstance(node, (ast.Tuple, ast.List)) and len(node.elts) == 2:
2000
+ parts = [self.valfn(e) for e in node.elts]
2001
+
2002
+ def fn2(b, op, parts=parts, node=node):
2003
+ if op == "range":
2004
+ return f"{parts[0](b, 'exact')} AND {parts[1](b, 'exact')}"
2005
+ if op == "in":
2006
+ return "(" + ", ".join(p(b, "exact") for p in parts) + ")"
2007
+ return marker(src(node))
2008
+ return fn2
2009
+ if isinstance(node, (ast.Tuple, ast.List, ast.Set)):
2010
+ for e in node.elts:
2011
+ self.use(e)
2012
+ return lambda b, op, t=src(node): ("(" + marker(t) + ")") if op == "in" else marker(t)
2013
+ if isinstance(node, ast.Call):
2014
+ last = (dotted(node.func) or "").split(".")[-1]
2015
+ if last in EXPR_NAMES and last != "Q":
2016
+ x = self.xfn(node)
2017
+ return lambda b, op, x=x, node=node: _safe(x, b, src(node))
2018
+ if isinstance(node, (ast.Call, ast.Attribute, ast.Name, ast.Subscript, ast.Await, ast.BinOp)):
2019
+ if isinstance(node, ast.BinOp) and _has_expr(node):
2020
+ x = self.xfn(node)
2021
+ return lambda b, op, x=x, node=node: _safe(x, b, src(node))
2022
+ v = self.ev(node)
2023
+ if isinstance(v, Mgr):
2024
+ v = v.base
2025
+ if isinstance(v, QS):
2026
+ self._absorbed = self._absorbed | v.roots
2027
+ return lambda b, op, v=v: self.subquery(b, v)
2028
+ if isinstance(v, XV):
2029
+ fn0 = self._took(v)
2030
+ return lambda b, op, fn0=fn0, node=node: _safe(fn0, b, src(node))
2031
+ else:
2032
+ self.use(node)
2033
+ text = src(node)
2034
+
2035
+ def fn3(b, op, text=text):
2036
+ if op == "range":
2037
+ return marker(text + "[0]") + " AND " + marker(text + "[1]")
2038
+ return marker(text)
2039
+ return fn3
2040
+
2041
+ def subquery(self, b: Build, qs: QS, cols: list[str] | None = None) -> str:
2042
+ prefix = chr(ord(b._prefix[0]) + 1) if b._prefix else "U"
2043
+ sub = Build(qs.model, outer=b, prefix=prefix).apply(qs)
2044
+ if cols is None:
2045
+ cols = [sql for _, sql in sub.values][:1] if sub.values else [sub.pk_sql()]
2046
+ return "(" + sub.select(cols=cols, order=sub.hi is not None, lock=False) + ")"
2047
+
2048
+ def kwfn(self, key: str, valnode: ast.AST):
2049
+ val = self.valfn(valnode)
2050
+ label = f"{key}={src(valnode)}"
2051
+
2052
+ def fn(b: Build, key=key, val=val, label=label):
2053
+ try:
2054
+ return b.lookup(key, val)
2055
+ except Unresolved:
2056
+ b.unresolved.append(key)
2057
+ return marker(label)
2058
+ return fn
2059
+
2060
+ def pfn(self, node: ast.AST):
2061
+ """A positional argument of filter(): Q objects and their combinations, as a function build -> SQL."""
2062
+ if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.BitOr, ast.BitAnd)):
2063
+ return _combine([self.pfn(node.left), self.pfn(node.right)], " OR " if isinstance(node.op, ast.BitOr) else " AND ")
2064
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Invert):
2065
+ inner = self.pfn(node.operand)
2066
+
2067
+ def neg(b: Build, inner=inner):
2068
+ was = b._ctx_left
2069
+ b._ctx_left = True
2070
+ try:
2071
+ s = inner(b)
2072
+ finally:
2073
+ b._ctx_left = was
2074
+ return f"NOT ({s})" if s else ""
2075
+ return neg
2076
+ if isinstance(node, ast.Call):
2077
+ last = (dotted(node.func) or "").split(".")[-1]
2078
+ if last == "Q":
2079
+ fns = [self.pfn(a) if not isinstance(a, ast.Starred) else (lambda b, t=src(a): marker(t)) for a in node.args]
2080
+ joiner = " AND "
2081
+ negated = False
2082
+ for k in node.keywords:
2083
+ if k.arg == "_connector":
2084
+ joiner = " OR " if "OR" in src(k.value) else " AND "
2085
+ elif k.arg == "_negated":
2086
+ negated = True
2087
+ elif k.arg is None:
2088
+ fns.append(lambda b, t="**" + src(k.value): marker(t))
2089
+ else:
2090
+ fns.append(self.kwfn(k.arg, k.value))
2091
+ fn = _combine(fns, joiner)
2092
+ return (lambda b, fn=fn: (f"NOT ({fn(b)})" if fn(b) else "")) if negated else fn
2093
+ if last in EXPR_NAMES:
2094
+ x = self.xfn(node)
2095
+ return lambda b, x=x, node=node: _safe(x, b, src(node))
2096
+ if isinstance(node, ast.Name):
2097
+ v = self.env.get(node.id)
2098
+ if isinstance(v, QObj):
2099
+ return self._took(v)
2100
+ if isinstance(v, XV):
2101
+ fn0 = self._took(v)
2102
+ return lambda b, fn0=fn0, node=node: _safe(fn0, b, src(node))
2103
+ else:
2104
+ v = self.ev(node)
2105
+ if isinstance(v, QObj):
2106
+ return self._took(v)
2107
+ return lambda b, t=src(node): marker(t)
2108
+
2109
+ def xarg(self, node: ast.AST):
2110
+ """An argument of an aggregate or function: a string names a field."""
2111
+ s = str_const(node)
2112
+ if s is not None:
2113
+ if s == "*":
2114
+ return lambda b: "*"
2115
+ return self.path_fn(s)
2116
+ return self.xfn(node)
2117
+
2118
+ def xfn(self, node: ast.AST):
2119
+ """A query expression (F, aggregates, functions, Subquery ...) as a function build -> SQL."""
2120
+ ok, v = const(node)
2121
+ if ok and not isinstance(v, list):
2122
+ s = sql_literal(v)
2123
+ if s is not None:
2124
+ return lambda b, s=s: s
2125
+ if isinstance(node, ast.Name):
2126
+ v = self.env.get(node.id)
2127
+ if isinstance(v, XV):
2128
+ return self._took(v)
2129
+ if isinstance(v, QObj):
2130
+ return self._took(v)
2131
+ if isinstance(v, QS):
2132
+ self._absorbed = self._absorbed | v.roots
2133
+ return lambda b, v=v: self.subquery(b, v)
2134
+ return lambda b, t=src(node): marker(t)
2135
+ if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Mod)) and _has_expr(node):
2136
+ l, r = self.xfn(node.left), self.xfn(node.right)
2137
+ sym = {ast.Add: "+", ast.Sub: "-", ast.Mult: "*", ast.Div: "/", ast.Mod: "%"}[type(node.op)]
2138
+ return lambda b: f"({l(b)} {sym} {r(b)})"
2139
+ if isinstance(node, (ast.BinOp, ast.UnaryOp)) and _is_q(node):
2140
+ return self.pfn(node)
2141
+ if not isinstance(node, ast.Call):
2142
+ v = self.ev(node) if isinstance(node, (ast.Attribute, ast.Subscript)) else None
2143
+ if isinstance(v, Mgr):
2144
+ v = v.base
2145
+ if isinstance(v, QS):
2146
+ self._absorbed = self._absorbed | v.roots
2147
+ return lambda b, v=v: self.subquery(b, v)
2148
+ return lambda b, t=src(node): marker(t)
2149
+ last = (dotted(node.func) or "").split(".")[-1]
2150
+ args = node.args
2151
+ if last == "F" and args:
2152
+ s = str_const(args[0])
2153
+ return self.path_fn(s) if s else (lambda b, t=src(node): marker(t))
2154
+ if last == "OuterRef" and args:
2155
+ s = str_const(args[0])
2156
+
2157
+ def outer(b: Build, s=s, node=node):
2158
+ if s and b.outer is not None:
2159
+ return b.outer.pk_sql() if s == "pk" else b.outer.resolve(s, left=True).sql
2160
+ return marker(src(node))
2161
+ return outer
2162
+ if last == "Value" and args:
2163
+ return self.xfn(args[0])
2164
+ if last in AGGREGATES:
2165
+ arg = self.xarg(args[0]) if args else (lambda b: "*")
2166
+ ok, distinct = const(kwarg(node, "distinct"))
2167
+ flt = self.pfn(kwarg(node, "filter")) if kwarg(node, "filter") is not None else None
2168
+ delim = self.xfn(kwarg(node, "delimiter") or args[1]) if last == "StringAgg" and (kwarg(node, "delimiter") is not None or len(args) > 1) else None
2169
+
2170
+ def agg(b: Build, last=last, arg=arg, distinct=bool(ok and distinct), flt=flt, delim=delim):
2171
+ was = b._ctx_left
2172
+ b._ctx_left = True
2173
+ try:
2174
+ inner = arg(b)
2175
+ cond = flt(b) if flt is not None else ""
2176
+ finally:
2177
+ b._ctx_left = was
2178
+ b.agg = True
2179
+ sql = f"{AGGREGATES[last]}({'DISTINCT ' if distinct else ''}{inner}{', ' + delim(b) if delim else ''})"
2180
+ return sql + (f" FILTER (WHERE {cond})" if cond else "")
2181
+ return agg
2182
+ if last in FUNCS:
2183
+ fns = [self.xarg(a) for a in args]
2184
+ return lambda b, last=last, fns=fns: f"{FUNCS[last]}({', '.join(f(b) for f in fns)})"
2185
+ if last == "Now":
2186
+ return lambda b: "CURRENT_TIMESTAMP"
2187
+ if last in TRUNCS and args:
2188
+ arg = self.xarg(args[0])
2189
+ return lambda b, last=last, arg=arg: f"DATE_TRUNC('{TRUNCS[last]}', {arg(b)})"
2190
+ if last == "Trunc" and len(args) >= 2 and str_const(args[1]):
2191
+ arg = self.xarg(args[0])
2192
+ return lambda b, arg=arg, kind=str_const(args[1]): f"DATE_TRUNC('{kind}', {arg(b)})"
2193
+ if last in EXTRACT_FUNCS and args:
2194
+ arg = self.xarg(args[0])
2195
+ return lambda b, last=last, arg=arg: f"EXTRACT({EXTRACT_FUNCS[last]} FROM {arg(b)})"
2196
+ if last == "Extract" and len(args) >= 2 and str_const(args[1]):
2197
+ arg = self.xarg(args[0])
2198
+ return lambda b, arg=arg, kind=str_const(args[1]).upper(): f"EXTRACT({kind} FROM {arg(b)})"
2199
+ if last == "Cast" and args:
2200
+ arg = self.xarg(args[0])
2201
+ of = kwarg(node, "output_field") or (args[1] if len(args) > 1 else None)
2202
+ tname = (dotted(of.func) if isinstance(of, ast.Call) else dotted(of) or "").split(".")[-1] if of is not None else ""
2203
+ sqlt = CAST_TYPES.get(tname)
2204
+ return (lambda b, arg=arg, sqlt=sqlt: f"CAST({arg(b)} AS {sqlt})") if sqlt else (lambda b, t=src(node): marker(t))
2205
+ if last == "ExpressionWrapper" and args:
2206
+ return self.xfn(args[0])
2207
+ if last in ("Subquery", "Exists") and args:
2208
+ v = self.ev(args[0])
2209
+ if isinstance(v, Mgr):
2210
+ v = v.base
2211
+ if isinstance(v, QS):
2212
+ self._absorbed = self._absorbed | v.roots
2213
+ if last == "Exists":
2214
+ return lambda b, v=v: "EXISTS" + self.subquery(b, v, ["1 AS a"])
2215
+ return lambda b, v=v: self.subquery(b, v)
2216
+ return lambda b, t=src(node): marker(t)
2217
+ if last == "Case":
2218
+ whens = []
2219
+ for a in args:
2220
+ if isinstance(a, ast.Call) and (dotted(a.func) or "").split(".")[-1] == "When":
2221
+ conds = [self.pfn(x) for x in a.args[:1]] + [self.kwfn(k.arg, k.value) for k in a.keywords if k.arg and k.arg != "then"]
2222
+ then = kwarg(a, "then") or (a.args[1] if len(a.args) > 1 else None)
2223
+ whens.append((_combine(conds, " AND "), self.xfn(then) if then is not None else (lambda b: "NULL")))
2224
+ else:
2225
+ whens.append((lambda b, t=src(a): marker(t), lambda b: marker("then")))
2226
+ default = self.xfn(kwarg(node, "default")) if kwarg(node, "default") is not None else None
2227
+
2228
+ def case(b: Build, whens=whens, default=default):
2229
+ body = " ".join(f"WHEN {c(b) or 'TRUE'} THEN {t(b)}" for c, t in whens)
2230
+ return f"CASE {body}{' ELSE ' + default(b) if default else ''} END"
2231
+ return case if whens else (lambda b, t=src(node): marker(t))
2232
+ if last == "Q":
2233
+ return self.pfn(node)
2234
+ if last == "RawSQL" and args:
2235
+ s = str_const(args[0])
2236
+ return (lambda b, s=s: f"({s})") if s and "%" not in s else (lambda b, t=src(node): marker(t))
2237
+ if last == "Func" and str_const(kwarg(node, "function")):
2238
+ fns = [self.xarg(a) for a in args]
2239
+ return lambda b, name=str_const(kwarg(node, "function")), fns=fns: f"{name}({', '.join(f(b) for f in fns)})"
2240
+ if isinstance(node.func, ast.Attribute) and node.func.attr in ("desc", "asc"):
2241
+ return self.xfn(node.func.value)
2242
+ if last in EXPR_NAMES: # an expression we do not write out (Window, a Func without a name ...)
2243
+ return lambda b, t=src(node): marker(t)
2244
+ v = self.ev(node)
2245
+ if isinstance(v, Mgr):
2246
+ v = v.base
2247
+ if isinstance(v, QS):
2248
+ self._absorbed = self._absorbed | v.roots
2249
+ return lambda b, v=v: self.subquery(b, v)
2250
+ if isinstance(v, XV):
2251
+ return self._took(v)
2252
+ return lambda b, t=src(node): marker(t)
2253
+
2254
+ # ---- emission ------------------------------------------------------------------------------------------------
2255
+ def compile(self, qs: QS) -> tuple[Build, list[str], int]:
2256
+ b = Build(qs.model).apply(qs)
2257
+ notes = list(qs.notes)
2258
+ conf = qs.conf
2259
+ return b, notes, conf
2260
+
2261
+ def _finish(self, b: Build, notes: list[str], conf: int) -> tuple[list[str], int]:
2262
+ if b.unresolved:
2263
+ conf = max(conf, MEDIUM)
2264
+ notes.append("not resolved against the model, shown as run-time parts: " + ", ".join(dict.fromkeys(b.unresolved)))
2265
+ if b.conditional:
2266
+ conf = max(conf, MEDIUM)
2267
+ notes.append("applied only on some run-time condition: " + ", ".join(dict.fromkeys(b.conditional)))
2268
+ return notes, conf
2269
+
2270
+ def site(self, node: ast.AST, qs: QS, sql: str, operation: str, conf: int, notes: list[str], b: Build | None = None) -> None:
2271
+ dj = self.dj
2272
+ if any(o.kind == "none" and not o.optional for o in qs.ops):
2273
+ # none(): Django knows the result is empty and sends no statement
2274
+ if self.emit:
2275
+ for r in qs.roots:
2276
+ dj.root_reason.setdefault(r, "none(): Django sends no statement for an empty queryset")
2277
+ return
2278
+ if not self.emit:
2279
+ if self.captured is not None:
2280
+ self.captured.append((qs, qs.model, sql, operation, conf, notes, self.cond > 0 or self.loop > 0))
2281
+ return
2282
+ for r in qs.roots | self._absorbed:
2283
+ dj.done_roots.add(r)
2284
+ in_loop = self.loop > 0 if self._in_loop is None else self._in_loop
2285
+ if qs.lazy is not None:
2286
+ inst, accessor, _ = qs.lazy
2287
+ if inst.per_iter and self.loop >= inst.per_iter:
2288
+ notes = notes + [f"related manager `{accessor}` read for each row of a loop: one query per row"]
2289
+ elif inst.row:
2290
+ notes = notes + [f"related manager `{accessor}` of the row a serializer or resolver handles: one query per row"]
2291
+ if not qs.roots and id(node) not in dj.counted_nodes:
2292
+ dj.counted_nodes.add(id(node))
2293
+ dj.stats.seen += 1
2294
+ dj.stats.translated += 1
2295
+ dj.out.emit(self.mod, node, self.symbol, sql, sink=qs.sink or _sink(node), in_loop=in_loop, model=qs.model.label,
2296
+ operation=operation, confidence=CONF[conf], notes="; ".join(dict.fromkeys(notes)), engine=dj.engine)
2297
+
2298
+ def raw_site(self, node: ast.AST, model: Model, sql: str, operation: str, conf: int, notes: list[str], *, in_loop: bool | None = None,
2299
+ sink: str = "") -> None:
2300
+ dj = self.dj
2301
+ if not self.emit:
2302
+ if self.captured is not None and operation != "lazy_load":
2303
+ self.captured.append((None, model, sql, operation, conf, notes, self.cond > 0 or self.loop > 0))
2304
+ return
2305
+ if id(node) not in dj.counted_nodes:
2306
+ dj.counted_nodes.add(id(node))
2307
+ dj.stats.seen += 1
2308
+ dj.stats.translated += 1
2309
+ dj.out.emit(self.mod, node, self.symbol, sql, sink=sink or _sink(node), in_loop=self.loop > 0 if in_loop is None else in_loop,
2310
+ model=model.label, operation=operation, confidence=CONF[conf], notes="; ".join(dict.fromkeys(notes)), engine=dj.engine)
2311
+
2312
+ def _served(self, qs: QS) -> bool:
2313
+ """A related manager read with nothing added, on an instance whose queryset prefetched it: no query."""
2314
+ if qs.lazy is None:
2315
+ return False
2316
+ inst, accessor, base_len = qs.lazy
2317
+ if len(qs.ops) != base_len:
2318
+ return False
2319
+ return self._covered(inst, inst.path + (accessor,))
2320
+
2321
+ def emit_select(self, node: ast.AST, qs: QS, share: QS | None = None) -> None:
2322
+ holder = share or qs
2323
+ if holder.state["emitted"] and self.emit:
2324
+ return
2325
+ if self.emit:
2326
+ holder.state["emitted"] = True
2327
+ if self._served(qs):
2328
+ if self.emit:
2329
+ self.dj.prefetch_served += 1
2330
+ return
2331
+ b, notes, conf = self.compile(qs)
2332
+ sql = b.select()
2333
+ notes, conf = self._finish(b, notes, conf)
2334
+ # a queryset object made outside the loop and read inside it is run once: Django keeps its rows on the object
2335
+ made = holder.state.get("loop")
2336
+ self._in_loop = None if made is None else made > 0
2337
+ try:
2338
+ self.site(node, qs, sql, "select", conf, notes)
2339
+ self.prefetch_sites(node, qs)
2340
+ finally:
2341
+ self._in_loop = None
2342
+
2343
+ _in_loop = None
2344
+
2345
+ def prefetch_sites(self, node: ast.AST, qs: QS) -> None:
2346
+ if not self.emit:
2347
+ return
2348
+ for op in qs.ops:
2349
+ if op.kind != "pf":
2350
+ continue
2351
+ for spec in op.data:
2352
+ self._prefetch_path(node, qs, spec, op.optional)
2353
+
2354
+ def _prefetch_path(self, node: ast.AST, qs: QS, spec: PrefetchV, optional: bool) -> None:
2355
+ model = qs.model
2356
+ parts = spec.path.split("__")
2357
+ dj = self.dj
2358
+ for i, part in enumerate(parts):
2359
+ last = i == len(parts) - 1
2360
+ f = model.fields.get(part)
2361
+ rel = model.reverse.get(part) if f is None else None
2362
+ inner = spec.qs if last and spec.qs is not None else None
2363
+ target = None
2364
+ where = None
2365
+ if f is not None and f.kind in ("fk", "o2o") and f.target is not None and f.target.pk is not None:
2366
+ target = f.target
2367
+ where = lambda b, f=f, model=model, target=target: f"{b.pk_sql()} IN (" + marker(f"{model.table}.{f.column} of the rows above") + ")"
2368
+ elif f is not None and f.kind == "m2m" and f.target is not None and f.m2m_table and f.m2m_from and f.target.pk is not None:
2369
+ target = f.target
2370
+ where = (lambda b, f=f, model=model, target=target:
2371
+ f"{b.join(('<m2m>',), f.m2m_table, b.pk_sql(), f.m2m_to, left=False)}.{f.m2m_from} IN ("
2372
+ + marker(f"{model.table}.{model.pk.column if model.pk else 'id'} of the rows above") + ")")
2373
+ elif rel is not None and rel.kind in ("rev_fk", "rev_o2o") and rel.model.table:
2374
+ target = rel.model
2375
+ where = lambda b, rel=rel, model=model: f"{b.root}.{rel.field.column} IN (" + marker(
2376
+ f"{model.table}.{model.pk.column if model.pk else 'id'} of the rows above") + ")"
2377
+ elif rel is not None and rel.kind == "rev_m2m" and rel.field.m2m_table and rel.field.m2m_from and rel.model.pk is not None:
2378
+ target = rel.model
2379
+ where = (lambda b, rel=rel, model=model:
2380
+ f"{b.join(('<m2m>',), rel.field.m2m_table, b.pk_sql(), rel.field.m2m_from, left=False)}.{rel.field.m2m_to} IN ("
2381
+ + marker(f"{model.table}.{model.pk.column if model.pk else 'id'} of the rows above") + ")")
2382
+ if target is None or not target.table:
2383
+ dj.stats.miss("prefetch_related lookup is not a relation we could resolve (generic relation, to_attr of another Prefetch, "
2384
+ "or a property)", f"{self.mod.rel}:{node.lineno}")
2385
+ return
2386
+ base = inner if inner is not None and inner.model is target else QS(target)
2387
+ pq = QS(target, (Op("where", (where, False, part)),) + base.ops, conf=max(qs.conf, base.conf))
2388
+ b, notes, conf = self.compile(pq)
2389
+ sql = b.select()
2390
+ notes, conf = self._finish(b, notes, conf)
2391
+ notes = [f"prefetch_related('{spec.path}'): one IN query per relation, after the main query"] + notes
2392
+ if optional:
2393
+ notes.append("applied only on some run-time condition")
2394
+ conf = max(conf, MEDIUM)
2395
+ dj.out.emit(self.mod, node, self.symbol, sql, sink=qs.sink or _sink(node),
2396
+ in_loop=self.loop > 0 if self._in_loop is None else self._in_loop, model=target.label,
2397
+ operation="prefetch", confidence=CONF[conf], notes="; ".join(notes), engine=dj.engine)
2398
+ model = target
2399
+
2400
+ def terminal(self, call: ast.Call, qs: QS, name: str, argcall: ast.Call, filtered: bool = False):
2401
+ m = qs.model
2402
+ if self._served(qs) and name in ("count", "exists"):
2403
+ if self.emit:
2404
+ self.dj.prefetch_served += 1
2405
+ self.args_use(argcall)
2406
+ return None
2407
+ one = Inst(m, origin=qs, per_iter=self.loop, conf=qs.conf)
2408
+ if name == "get":
2409
+ q = qs if filtered else self.filter_op(qs, argcall, False)
2410
+ b, notes, conf = self.compile(q)
2411
+ sql = b.select(limit="21" if b.hi is None else None, order=False)
2412
+ notes, conf = self._finish(b, notes, conf)
2413
+ self.site(call, q, sql, "get", conf, notes)
2414
+ self.prefetch_sites(call, q)
2415
+ return Inst(m, origin=q, per_iter=self.loop, conf=qs.conf)
2416
+ if name in ("first", "last"):
2417
+ self.args_use(argcall)
2418
+ b, notes, conf = self.compile(qs)
2419
+ sql = b.select(limit="1", force_pk=True, flip=name == "last")
2420
+ notes, conf = self._finish(b, notes, conf)
2421
+ self.site(call, qs, sql, name, conf, notes)
2422
+ self.prefetch_sites(call, qs)
2423
+ return one
2424
+ if name in ("earliest", "latest"):
2425
+ fields = [str_const(a) for a in argcall.args] or [str_const(kwarg(argcall, "field_name"))]
2426
+ q = qs
2427
+ if all(fields) and fields:
2428
+ q = qs.add(Op("order", [self.order_fn(ast.Constant(value=("-" if (name == "latest") != f.startswith("-") else "") + f.lstrip("-")))
2429
+ for f in fields]))
2430
+ b, notes, conf = self.compile(q)
2431
+ else:
2432
+ b, notes, conf = self.compile(q)
2433
+ notes.append(f"{name}(): ordered by the model's get_latest_by")
2434
+ conf = max(conf, MEDIUM)
2435
+ sql = b.select(limit="1")
2436
+ notes, conf = self._finish(b, notes, conf)
2437
+ self.site(call, q, sql, name, conf, notes)
2438
+ return one
2439
+ if name == "count":
2440
+ self.args_use(argcall)
2441
+ b, notes, conf = self.compile(qs)
2442
+ sql = b.count()
2443
+ notes, conf = self._finish(b, notes, conf)
2444
+ self.site(call, qs, sql, "count", conf, notes)
2445
+ return None
2446
+ if name in ("exists", "contains"):
2447
+ self.args_use(argcall)
2448
+ b, notes, conf = self.compile(qs)
2449
+ sql = b.exists()
2450
+ notes, conf = self._finish(b, notes, conf)
2451
+ self.site(call, qs, sql, "exists", conf, notes)
2452
+ return None
2453
+ if name == "explain":
2454
+ self.args_use(argcall)
2455
+ return None
2456
+ if name == "aggregate":
2457
+ names = [(_default_alias(a) or src(a), self.xfn(a)) for a in argcall.args]
2458
+ names += [(k.arg, self.xfn(k.value)) for k in argcall.keywords if k.arg]
2459
+ b, notes, conf = self.compile(qs)
2460
+ cols = []
2461
+ for alias, fn in names:
2462
+ cols.append(f"{_safe(fn, b, alias)} AS {alias}")
2463
+ if not cols:
2464
+ return None
2465
+ if b.needs_subquery:
2466
+ sql = f"SELECT {', '.join(cols)} FROM ({b.select(order=False, lock=False)}) subquery"
2467
+ notes.append("aggregate over a grouped, distinct or sliced queryset: Django wraps it in a subquery")
2468
+ conf = max(conf, MEDIUM)
2469
+ else:
2470
+ sql = "SELECT " + ", ".join(cols) + " FROM " + b._from(m.table, b.root) + b.joins_sql() + b.where_sql()
2471
+ notes, conf = self._finish(b, notes, conf)
2472
+ self.site(call, qs, sql, "aggregate", conf, notes)
2473
+ return None
2474
+ if name == "in_bulk":
2475
+ b, notes, conf = self.compile(qs)
2476
+ fname = str_const(kwarg(argcall, "field_name")) or "pk"
2477
+ f = m.pk if fname == "pk" else m.fields.get(fname)
2478
+ col = f"{b.root}.{f.column}" if f is not None else b.pk_sql()
2479
+ extra = [f"{col} IN (" + marker(src(argcall.args[0])) + ")"] if argcall.args else []
2480
+ self.args_use(argcall)
2481
+ sql = b.select(extra_where=extra, order=False)
2482
+ notes, conf = self._finish(b, notes, conf)
2483
+ self.site(call, qs, sql, "in_bulk", conf, notes)
2484
+ return None
2485
+ if name in ("create", "get_or_create", "update_or_create", "bulk_create"):
2486
+ return self.create_like(call, qs, name, argcall)
2487
+ if name == "bulk_update":
2488
+ ok, names = const(argcall.args[1] if len(argcall.args) > 1 else kwarg(argcall, "fields"))
2489
+ self.args_use(argcall)
2490
+ objs = src(argcall.args[0]) if argcall.args else "objs"
2491
+ if m.pk is None:
2492
+ return None
2493
+ pk = m.pk.column
2494
+ note = []
2495
+ if ok and isinstance(names, list):
2496
+ cols = [m.field_by_attname(n).column for n in names if isinstance(n, str) and m.field_by_attname(n) is not None]
2497
+ sets = ", ".join(f"{c} = CASE WHEN {m.table}.{pk} = " + marker("pk of each object") + " THEN " + marker(f"its {c}") + " END" for c in cols)
2498
+ else:
2499
+ fields_src = src(argcall.args[1]) if len(argcall.args) > 1 else "fields"
2500
+ sets = marker(f"each column in {fields_src}") + " = " + marker("CASE per object")
2501
+ note = ["bulk_update() with computed field names: the columns set are a run-time part"]
2502
+ sql = f"UPDATE {m.table} SET {sets} WHERE {m.table}.{pk} IN (" + marker(f"pks of {objs}") + ")"
2503
+ self.site(call, qs, sql, "bulk_update", max(qs.conf, MEDIUM if note else HIGH), list(qs.notes) + ["bulk_update(): one UPDATE per batch"] + note)
2504
+ return None
2505
+ if name == "update":
2506
+ b, notes, conf = self.compile(qs)
2507
+ sets = []
2508
+ for k in argcall.keywords:
2509
+ if k.arg is None:
2510
+ sets.append(marker("**" + src(k.value)))
2511
+ self.use(k.value)
2512
+ continue
2513
+ f = m.field_by_attname(k.arg)
2514
+ if f is None or f.kind == "m2m":
2515
+ b.unresolved.append(k.arg)
2516
+ sets.append(marker(f"{k.arg} = {src(k.value)}"))
2517
+ continue
2518
+ sets.append(f"{f.column} = {self.valfn(k.value)(b, 'exact')}")
2519
+ if not sets:
2520
+ return None
2521
+ sql = b.filtered_write(f"UPDATE {m.table} SET {', '.join(sets)}")
2522
+ notes, conf = self._finish(b, notes, conf)
2523
+ self.site(call, qs, sql, "update", conf, notes)
2524
+ return None
2525
+ if name == "delete":
2526
+ self.args_use(argcall)
2527
+ b, notes, conf = self.compile(qs)
2528
+ sql = b.filtered_write(f"DELETE FROM {m.table}")
2529
+ notes, conf = self._finish(b, notes, conf)
2530
+ notes.append("delete(): when the model has cascading relations or signals Django first selects the rows and deletes related rows too")
2531
+ self.site(call, qs, sql, "delete", max(conf, MEDIUM), notes)
2532
+ return None
2533
+ return None
2534
+
2535
+ def _drop(self, qs: QS, why: str) -> None:
2536
+ for r in qs.roots:
2537
+ self.dj.root_reason.setdefault(r, why)
2538
+
2539
+ def create_like(self, call: ast.Call, qs: QS, name: str, argcall: ast.Call):
2540
+ m = qs.model
2541
+ notes = list(qs.notes)
2542
+ if name == "bulk_create":
2543
+ self.args_use(argcall)
2544
+ objs = src(argcall.args[0]) if argcall.args else "objs"
2545
+ for sql in self.insert_sql(m, None)[-1:]:
2546
+ cols = sql[sql.index("("): sql.index(")") + 1]
2547
+ stmt = f"INSERT INTO {m.table} {cols} VALUES (" + marker(f"one row per object in {objs}") + ")"
2548
+ if kwarg(argcall, "update_conflicts") is not None or kwarg(argcall, "ignore_conflicts") is not None:
2549
+ stmt += " ON CONFLICT " + marker("conflict handling")
2550
+ self.site(call, qs, stmt, "bulk_create", qs.conf, notes + ["bulk_create(): one INSERT per batch"])
2551
+ return None
2552
+ given: dict[str, str] = {}
2553
+ lookups = []
2554
+ dyn = False
2555
+ b0 = Build(m)
2556
+ for k in argcall.keywords:
2557
+ if k.arg is None:
2558
+ dyn = True
2559
+ self.use(k.value)
2560
+ continue
2561
+ if k.arg in ("defaults", "create_defaults"):
2562
+ if isinstance(k.value, ast.Dict):
2563
+ for kk, vv in zip(k.value.keys, k.value.values):
2564
+ s = str_const(kk)
2565
+ if s:
2566
+ given[s] = self.valfn(vv)(b0, "exact")
2567
+ else:
2568
+ dyn = True
2569
+ else:
2570
+ dyn = True
2571
+ self.use(k.value)
2572
+ continue
2573
+ if "__" not in k.arg:
2574
+ given[k.arg] = self.valfn(k.value)(b0, "exact")
2575
+ lookups.append(k)
2576
+ if dyn:
2577
+ notes.append("some values come from a computed mapping (**kwargs / defaults): shown as defaults")
2578
+ conf = max(qs.conf, MEDIUM if dyn else HIGH)
2579
+ inst = Inst(m, origin=None if name == "create" else qs, per_iter=self.loop, conf=qs.conf, new=False)
2580
+ if name == "create":
2581
+ for sql in self.insert_sql(m, given):
2582
+ self.site(call, qs, sql, "insert", conf, notes)
2583
+ return inst
2584
+ fake = ast.Call(func=argcall.func, args=argcall.args, keywords=lookups)
2585
+ ast.copy_location(fake, argcall)
2586
+ q = self.filter_op(qs, fake, False)
2587
+ b, n2, c2 = self.compile(q)
2588
+ sel = b.select(limit="21", order=False, lock=False) + (" FOR UPDATE" if name == "update_or_create" else "")
2589
+ n2, c2 = self._finish(b, n2, c2)
2590
+ self.site(call, q, sel, "get", max(c2, conf), n2 + [f"{name}(): the lookup"])
2591
+ for sql in self.insert_sql(m, given):
2592
+ self.site(call, qs, sql, "insert", conf, notes + [f"{name}(): runs only when no row matched"])
2593
+ if name == "update_or_create" and m.pk is not None:
2594
+ cols = [m.field_by_attname(k) for k in given if k not in {x.arg for x in lookups}]
2595
+ cols = [f.column for f in cols if f is not None and f.kind != "m2m"] or [f.column for f in m.columns() if not f.pk]
2596
+ sets = ", ".join(f"{c} = " + (given.get(c) or given.get(c[:-3] if c.endswith('_id') else c) or marker(c)) for c in cols)
2597
+ sql = f"UPDATE {m.table} SET {sets} WHERE {m.table}.{m.pk.column} = " + marker("pk of the row found")
2598
+ self.site(call, qs, sql, "update", conf, notes + ["update_or_create(): runs only when a row matched"])
2599
+ return TupleV([inst, None])
2600
+
2601
+
2602
+ # ---- helpers ----------------------------------------------------------------------------------------------------
2603
+ _COMBINED = Op("mark", "combined (| or &) with another queryset")
2604
+
2605
+
2606
+ def _union(a: QS, b: QS, is_or: bool) -> QS:
2607
+ """`a | b` / `a & b` of two querysets of one model: one statement whose WHERE joins both filters. Written as the
2608
+ left side with the right side's filter as a run-time part; `none() | b` is just b."""
2609
+ if is_or and a.has("none") and a.model is b.model:
2610
+ return b.with_(conf=MEDIUM, roots=a.roots)
2611
+ if is_or and b.has("none"):
2612
+ return a.with_(conf=MEDIUM, roots=b.roots)
2613
+ if _COMBINED in a.ops:
2614
+ return a.with_(roots=b.roots)
2615
+ return a.add(_COMBINED, conf=MEDIUM, roots=b.roots)
2616
+
2617
+
2618
+ def _combine(fns: list, joiner: str):
2619
+ def fn(b: Build, fns=fns, joiner=joiner):
2620
+ if joiner == " OR ":
2621
+ was = b._ctx_left
2622
+ b._ctx_left = True
2623
+ try:
2624
+ parts = [f(b) for f in fns]
2625
+ finally:
2626
+ b._ctx_left = was
2627
+ else:
2628
+ parts = [f(b) for f in fns]
2629
+ parts = [p for p in parts if p]
2630
+ if not parts:
2631
+ return ""
2632
+ if len(parts) == 1:
2633
+ return parts[0]
2634
+ if joiner == " OR ":
2635
+ return "(" + " OR ".join(parts) + ")"
2636
+ return " AND ".join(f"({p})" if " OR " in p and not p.startswith("(") else p for p in parts)
2637
+ return fn
2638
+
2639
+
2640
+ def _safe(fn, b: Build, label: str) -> str:
2641
+ try:
2642
+ return fn(b)
2643
+ except Unresolved:
2644
+ b.unresolved.append(label)
2645
+ return marker(label)
2646
+
2647
+
2648
+ def _is_q(node: ast.AST) -> bool:
2649
+ """True when an expression is built from Q(...) calls with | & ~."""
2650
+ if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.BitOr, ast.BitAnd)):
2651
+ return _is_q(node.left) or _is_q(node.right)
2652
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Invert):
2653
+ return _is_q(node.operand)
2654
+ return isinstance(node, ast.Call) and (dotted(node.func) or "").split(".")[-1] in ("Q", "Exists")
2655
+
2656
+
2657
+ def _has_expr(node: ast.AST) -> bool:
2658
+ for n in ast.walk(node):
2659
+ if isinstance(n, ast.Call) and (dotted(n.func) or "").split(".")[-1] in EXPR_NAMES:
2660
+ return True
2661
+ return False
2662
+
2663
+
2664
+ def _default_alias(node: ast.AST) -> str | None:
2665
+ """Django's default alias of an aggregate passed positionally: `Count("x")` -> `x__count`."""
2666
+ if isinstance(node, ast.Call) and node.args:
2667
+ last = (dotted(node.func) or "").split(".")[-1]
2668
+ s = str_const(node.args[0])
2669
+ if last in AGGREGATES and s:
2670
+ return f"{s}__{last.lower()}"
2671
+ return None
2672
+
2673
+
2674
+ def _alias_for(alias: str | None, path: str | None) -> str | None:
2675
+ return alias
2676
+
2677
+
2678
+ def _plus_one(idx: str) -> str:
2679
+ return str(int(idx) + 1) if idx.isdigit() else marker(unmark(idx) + " + 1")
2680
+
2681
+
2682
+ def _sink(node: ast.AST) -> str:
2683
+ if isinstance(node, ast.Call):
2684
+ return src(node.func)
2685
+ return src(node)
2686
+
2687
+
2688
+ def _inner_counted(node: ast.AST, counted: set) -> bool:
2689
+ while isinstance(node, (ast.Call, ast.Attribute, ast.Subscript)):
2690
+ if id(node) in counted:
2691
+ return True
2692
+ node = node.func if isinstance(node, ast.Call) else node.value
2693
+ return False
2694
+
2695
+
2696
+ _REFINING = {"filter", "exclude", "annotate", "alias", "order_by", "select_related", "prefetch_related", "extra", "only", "defer",
2697
+ "distinct", "using", "complex_filter"}
2698
+
2699
+
2700
+ def _refines(fn_def) -> bool:
2701
+ """True when a get_queryset() body calls something that changes the queryset (not just builds its class)."""
2702
+ for n in ast.walk(fn_def):
2703
+ if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) and n.func.attr in _REFINING:
2704
+ return True
2705
+ return False
2706
+
2707
+
2708
+ def _sig(v):
2709
+ """What kind of value an argument is, for sharing a helper's result; False when the value carries its own state."""
2710
+ if v is None:
2711
+ return None
2712
+ if isinstance(v, Inst):
2713
+ return ("I", id(v.model))
2714
+ if isinstance(v, ModelRef):
2715
+ return ("M", id(v.model))
2716
+ if isinstance(v, SelfV):
2717
+ return ("C", id(v.cls))
2718
+ if isinstance(v, Seq) and isinstance(v.elem, Inst):
2719
+ return ("S", id(v.elem.model))
2720
+ if isinstance(v, (Seq, TupleV, SuperV, Unk)):
2721
+ return None
2722
+ return False
2723
+
2724
+
2725
+ def _as_param(v, name: str):
2726
+ """An argument as the callee sees it: an instance is known there by the parameter's name."""
2727
+ if isinstance(v, Inst):
2728
+ return Inst(v.model, conf=v.conf, name=name, new=v.new)
2729
+ if isinstance(v, Seq) and isinstance(v.elem, Inst):
2730
+ return Seq(Inst(v.elem.model, conf=v.elem.conf))
2731
+ if isinstance(v, (Unk, SuperV)):
2732
+ return None
2733
+ return v
2734
+
2735
+
2736
+ def _combine_returns(returns: list):
2737
+ vals = [v for v in returns if v is not None]
2738
+ if not vals:
2739
+ return None
2740
+ first = vals[0]
2741
+ if isinstance(first, Mgr):
2742
+ first = first.base
2743
+ if isinstance(first, QS):
2744
+ out = first
2745
+ for v in vals[1:]:
2746
+ v = v.base if isinstance(v, Mgr) else v
2747
+ if not isinstance(v, QS):
2748
+ return out.with_(conf=MEDIUM)
2749
+ m = merge_qs(out, v)
2750
+ if m is None:
2751
+ return None
2752
+ out = m
2753
+ if len(vals) < len(returns):
2754
+ out = out.with_(conf=MEDIUM)
2755
+ return out
2756
+ if isinstance(first, Inst):
2757
+ if all(isinstance(v, Inst) and v.model is first.model for v in vals):
2758
+ return first
2759
+ return None
2760
+ if isinstance(first, (Seq, ModelRef, TupleV, QObj, XV)) and len(vals) == 1:
2761
+ return first
2762
+ if isinstance(first, Seq) and all(isinstance(v, Seq) for v in vals):
2763
+ return first
2764
+ return None
2765
+
2766
+
2767
+ def run(root: Path, project: Project):
2768
+ dj = Django(root, project)
2769
+ if not dj.index.models:
2770
+ return [], dj.stats, []
2771
+ dj.run()
2772
+ return dj.out.sites, dj.stats, dj.index.tables()