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,662 @@
1
+ """Django querysets as data, and the SQL they stand for.
2
+
3
+ A queryset is a model plus a list of operations (`Op`), exactly as the chain states them. `Build` turns that list
4
+ into SQL the way Django's compiler does: real table and column names, joins for relation spans, the documented
5
+ SQL of each lookup. An operation that only applies on some run-time condition is written as a «run-time part».
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from .orm_django_models import Field, Model, Rel
11
+ from .orm_py import SETTINGS, marker, sql_literal, unmark
12
+
13
+ LOOKUPS = {"exact", "iexact", "contains", "icontains", "in", "gt", "gte", "lt", "lte", "startswith", "istartswith",
14
+ "endswith", "iendswith", "range", "isnull", "regex", "iregex", "overlap", "contained_by", "has_key",
15
+ "has_keys", "has_any_keys", "search", "trigram_similar", "trigram_word_similar", "unaccent", "isempty"}
16
+ EXTRACTS = {"year": "YEAR", "month": "MONTH", "day": "DAY", "hour": "HOUR", "minute": "MINUTE", "second": "SECOND",
17
+ "week": "WEEK", "week_day": "DOW", "iso_week_day": "ISODOW", "quarter": "QUARTER", "iso_year": "ISOYEAR"}
18
+ TRANSFORMS = set(EXTRACTS) | {"date", "time", "lower", "upper", "length", "len", "trim"}
19
+ HIGH, MEDIUM, LOW = 0, 1, 2
20
+ CONF = {HIGH: "high", MEDIUM: "medium", LOW: "low"}
21
+
22
+
23
+ class Op:
24
+ __slots__ = ("kind", "data", "optional", "line")
25
+
26
+ def __init__(self, kind: str, data=None, optional: bool = False, line: int = 0):
27
+ self.kind, self.data, self.optional, self.line = kind, data, optional, line
28
+
29
+ def opt(self) -> "Op":
30
+ return self if self.optional else Op(self.kind, self.data, True, self.line)
31
+
32
+
33
+ class QS:
34
+ """A queryset value: immutable; every chained call makes a new one."""
35
+ __slots__ = ("model", "ops", "roots", "conf", "notes", "state", "lazy", "sink", "qcls")
36
+
37
+ def __init__(self, model: Model, ops: tuple = (), roots: frozenset = frozenset(), conf: int = HIGH, notes: tuple = (),
38
+ lazy=None, sink: str = "", qcls=None):
39
+ self.model, self.ops, self.roots, self.conf, self.notes = model, ops, roots, conf, notes
40
+ self.state = {"emitted": False}
41
+ self.lazy = lazy # (instance, accessor, length of ops when the related manager was made)
42
+ self.sink = sink
43
+ self.qcls = qcls # the project's QuerySet subclass, when the manager names one
44
+
45
+ def add(self, op: Op, *, conf: int | None = None, note: str = "", roots: frozenset = frozenset()) -> "QS":
46
+ return QS(self.model, self.ops + (op,), self.roots | roots, max(self.conf, conf if conf is not None else HIGH),
47
+ self.notes + ((note,) if note and note not in self.notes else ()), self.lazy, self.sink, self.qcls)
48
+
49
+ def with_(self, *, conf: int | None = None, note: str = "", roots: frozenset = frozenset()) -> "QS":
50
+ return QS(self.model, self.ops, self.roots | roots, max(self.conf, conf if conf is not None else HIGH),
51
+ self.notes + ((note,) if note and note not in self.notes else ()), self.lazy, self.sink, self.qcls)
52
+
53
+ def has(self, kind: str) -> bool:
54
+ return any(o.kind == kind for o in self.ops)
55
+
56
+
57
+ def merge_qs(a: QS, b: QS) -> QS | None:
58
+ """Two querysets a run-time condition chooses between: what they share, then each one's own operations as
59
+ optional. None when they are not about the same model."""
60
+ if a.model is not b.model:
61
+ return None
62
+ k = 0
63
+ while k < len(a.ops) and k < len(b.ops) and a.ops[k] is b.ops[k]:
64
+ k += 1
65
+ if k == len(a.ops) == len(b.ops):
66
+ return a
67
+ ops = a.ops[:k] + tuple(o.opt() for o in a.ops[k:]) + tuple(o.opt() for o in b.ops[k:])
68
+ notes = a.notes + tuple(n for n in b.notes if n not in a.notes)
69
+ out = QS(a.model, ops, a.roots | b.roots, max(a.conf, b.conf, MEDIUM), notes, a.lazy or b.lazy, a.sink or b.sink, a.qcls or b.qcls)
70
+ return out
71
+
72
+
73
+ class Col:
74
+ __slots__ = ("sql", "field", "rest", "multi", "agg", "model")
75
+
76
+ def __init__(self, sql: str, field: Field | None, rest: list, multi: bool = False, agg: bool = False, model: Model | None = None):
77
+ self.sql, self.field, self.rest, self.multi, self.agg, self.model = sql, field, rest, multi, agg, model
78
+
79
+
80
+ class Unresolved(Exception):
81
+ """A lookup path that names no field: the predicate becomes a run-time part, never a guessed column."""
82
+
83
+
84
+ class Build:
85
+ def __init__(self, model: Model, outer: "Build | None" = None, prefix: str = ""):
86
+ self.model = model
87
+ self.outer = outer
88
+ self.used: dict[str, int] = {}
89
+ self.joins: dict[tuple, list] = {} # path -> [alias, table, kind, on]
90
+ self._prefix = prefix
91
+ self._pred_agg = False
92
+ self.root = self._alias(model.table)
93
+ self.where: list[str] = []
94
+ self.having: list[str] = []
95
+ self.annotations: dict[str, tuple[str, bool]] = {} # name -> (sql, is aggregate)
96
+ self.annot_selected: list[str] = []
97
+ self.values: list[tuple[str | None, str]] | None = None
98
+ self.flat = False
99
+ self.only: list[str] | None = None
100
+ self.defer: list[str] = []
101
+ self.order: list[str] | None = None
102
+ self.order_optional: list[str] = []
103
+ self.distinct = False
104
+ self.distinct_on: list[str] = []
105
+ self.group_by: list[str] | None = None
106
+ self.lo = None
107
+ self.hi = None
108
+ self.reverse = False
109
+ self.none = False
110
+ self.lock = ""
111
+ self.sr: list[str] = []
112
+ self.sr_all = False
113
+ self.agg = False
114
+ self.unresolved: list[str] = []
115
+ self.conditional: list[str] = []
116
+ self.multi_exclude = False
117
+ self._ctx_left = False
118
+
119
+ # ---- aliases and joins -------------------------------------------------------------------------------------
120
+ def _alias(self, table: str) -> str:
121
+ n = sum(self.used.values())
122
+ self.used[table] = self.used.get(table, 0) + 1
123
+ if self._prefix:
124
+ return f"{self._prefix}{n}"
125
+ return table if self.used[table] == 1 else f"T{n + 1}"
126
+
127
+ def _from(self, table: str, alias: str) -> str:
128
+ return table if alias == table else f"{table} {alias}"
129
+
130
+ def join(self, path: tuple, table: str, on_left: str, on_right_col: str, *, left: bool) -> str:
131
+ cur = self.joins.get(path)
132
+ if cur is not None:
133
+ if not left and cur[2] == "LEFT OUTER JOIN" and not self._ctx_left:
134
+ cur[2] = "INNER JOIN" # a filter on the joined row rules out the null-extended rows
135
+ return cur[0]
136
+ alias = self._alias(table)
137
+ self.joins[path] = [alias, table, "LEFT OUTER JOIN" if left else "INNER JOIN", f"{on_left} = {alias}.{on_right_col}"]
138
+ return alias
139
+
140
+ def joins_sql(self) -> str:
141
+ return "".join(f" {kind} {self._from(table, alias)} ON {on}" for alias, table, kind, on in self.joins.values())
142
+
143
+ # ---- lookup paths ------------------------------------------------------------------------------------------
144
+ def _owner_alias(self, model: Model, alias: str, path: tuple, f: Field) -> str:
145
+ """The alias of the table that holds field `f`: the model's own, or a parent's (multi-table inheritance)."""
146
+ cur, cur_alias, cur_path = model, alias, path
147
+ guard = 0
148
+ while f.owner is not None and f.owner is not cur and cur.parents and guard < 8:
149
+ parent = cur.parents[0]
150
+ link = cur.pk if cur.pk is not None and cur.pk.parent_link else None
151
+ if cur.proxy:
152
+ cur = parent
153
+ guard += 1
154
+ continue
155
+ if link is None or parent.pk is None:
156
+ break
157
+ cur_path = cur_path + ("<parent>",)
158
+ cur_alias = self.join(cur_path, parent.table, f"{cur_alias}.{link.column}", parent.pk.column, left=False)
159
+ cur = parent
160
+ guard += 1
161
+ return cur_alias
162
+
163
+ def resolve(self, path: str, *, left: bool = False) -> Col:
164
+ """A lookup path (`author__profile__name__icontains`) to its column, adding the joins it spans."""
165
+ parts = path.split("__")
166
+ # an annotation by this name (its default alias may hold `__`: Count("id") is `id__count`)
167
+ for k in range(len(parts), 0, -1):
168
+ name = "__".join(parts[:k])
169
+ if name in self.annotations and (k == 1 or name not in self.model.fields):
170
+ sql, agg = self.annotations[name]
171
+ return Col(sql, None, parts[k:], agg=agg)
172
+ model, alias, jpath = self.model, self.root, ()
173
+ multi = False
174
+ i = 0
175
+ left = left or self._ctx_left
176
+ depth_limit = SETTINGS["orm_max_relation_depth"]
177
+ while i < len(parts):
178
+ if i > depth_limit:
179
+ raise Unresolved(path)
180
+ part = parts[i]
181
+ rest = parts[i + 1:]
182
+ f = model.pk if part == "pk" else model.fields.get(part)
183
+ attname = False
184
+ if f is None and part.endswith("_id"):
185
+ f = model.fields.get(part[:-3])
186
+ attname = f is not None and f.kind in ("fk", "o2o")
187
+ if not attname:
188
+ f = None
189
+ if f is not None:
190
+ own = self._owner_alias(model, alias, jpath, f) if f.kind != "m2m" else alias
191
+ if f.kind == "col" or attname:
192
+ if f.is_json and rest and not _is_lookup_tail(rest):
193
+ keys = []
194
+ while rest and rest[0] not in LOOKUPS:
195
+ keys.append(rest.pop(0))
196
+ args = ", ".join("'" + k.replace("'", "''") + "'" for k in keys)
197
+ return Col(f"JSON_EXTRACT_PATH_TEXT({own}.{f.column}, {args})", f, rest, multi, model=model)
198
+ return Col(f"{own}.{f.column}", f, rest, multi, model=model)
199
+ target = f.target
200
+ if f.kind in ("fk", "o2o"):
201
+ ends = not rest or _is_lookup_tail(rest, target)
202
+ to_pk = bool(rest) and target is not None and target.pk is not None and rest[0] in ("pk", target.pk.name) \
203
+ and _is_lookup_tail(rest[1:], None) and not f.to_field
204
+ if ends:
205
+ return Col(f"{own}.{f.column}", f, rest, multi, model=model)
206
+ if to_pk:
207
+ return Col(f"{own}.{f.column}", f, rest[1:], multi, model=model)
208
+ if target is None or not target.table or target.pk is None:
209
+ raise Unresolved(path)
210
+ jpath = jpath + (part,)
211
+ tcol = target.pk.column
212
+ if f.to_field and target.fields.get(f.to_field) is not None:
213
+ tcol = target.fields[f.to_field].column
214
+ alias = self.join(jpath, target.table, f"{own}.{f.column}", tcol, left=left and (f.null or self._has_left(jpath[:-1])))
215
+ model = target
216
+ i += 1
217
+ continue
218
+ # many-to-many, forward
219
+ if target is None or not f.m2m_table or not f.m2m_from or not f.m2m_to or model.pk is None or target.pk is None:
220
+ raise Unresolved(path)
221
+ multi = True
222
+ root_alias = self._owner_alias(model, alias, jpath, model.pk)
223
+ thr = self.join(jpath + (part, "<through>"), f.m2m_table, f"{root_alias}.{model.pk.column}", f.m2m_from, left=True if left else False)
224
+ if not rest or _is_lookup_tail(rest, target):
225
+ return Col(f"{thr}.{f.m2m_to}", target.pk, rest, True, model=target)
226
+ if rest[0] in ("pk", target.pk.name) and _is_lookup_tail(rest[1:], None):
227
+ return Col(f"{thr}.{f.m2m_to}", target.pk, rest[1:], True, model=target)
228
+ jpath = jpath + (part,)
229
+ alias = self.join(jpath, target.table, f"{thr}.{f.m2m_to}", target.pk.column, left=left)
230
+ model = target
231
+ i += 1
232
+ continue
233
+ rel: Rel | None = model.reverse_query.get(part) or model.reverse.get(part)
234
+ if rel is not None and model.pk is not None and rel.model.table and rel.model.pk is not None:
235
+ multi = multi or rel.kind != "rev_o2o"
236
+ far = rel.model
237
+ here = self._owner_alias(model, alias, jpath, model.pk)
238
+ if rel.kind in ("rev_fk", "rev_o2o"):
239
+ jpath = jpath + (part,)
240
+ alias = self.join(jpath, far.table, f"{here}.{model.pk.column}", rel.field.column, left=True if left else False)
241
+ else:
242
+ f2 = rel.field
243
+ if not f2.m2m_table or not f2.m2m_from or not f2.m2m_to:
244
+ raise Unresolved(path)
245
+ thr = self.join(jpath + (part, "<through>"), f2.m2m_table, f"{here}.{model.pk.column}", f2.m2m_to, left=True if left else False)
246
+ if not rest or _is_lookup_tail(rest, far):
247
+ return Col(f"{thr}.{f2.m2m_from}", far.pk, rest, True, model=far)
248
+ jpath = jpath + (part,)
249
+ alias = self.join(jpath, far.table, f"{thr}.{f2.m2m_from}", far.pk.column, left=left)
250
+ model = far
251
+ if not rest or _is_lookup_tail(rest, far):
252
+ return Col(f"{alias}.{far.pk.column}", far.pk, rest, multi, model=far)
253
+ i += 1
254
+ continue
255
+ raise Unresolved(path)
256
+ raise Unresolved(path)
257
+
258
+ # ---- predicates --------------------------------------------------------------------------------------------
259
+ def lookup(self, key: str, val, *, negated: bool = False) -> str:
260
+ """`key=val` of a filter() as SQL. `val` is a rendered-value function taking (build, lookup name)."""
261
+ col = self.resolve(key)
262
+ if col.agg:
263
+ self._pred_agg = True
264
+ sql = col.sql
265
+ rest = list(col.rest)
266
+ while rest and rest[0] in TRANSFORMS and (len(rest) > 1 or rest[0] not in LOOKUPS):
267
+ t = rest.pop(0)
268
+ if t in EXTRACTS:
269
+ sql = f"EXTRACT({EXTRACTS[t]} FROM {sql})"
270
+ elif t in ("date", "time"):
271
+ sql = f"CAST({sql} AS {t.upper()})"
272
+ elif t in ("length", "len"):
273
+ sql = f"LENGTH({sql})" if t == "length" else f"CARDINALITY({sql})"
274
+ else:
275
+ sql = f"{t.upper()}({sql})"
276
+ if len(rest) > 1:
277
+ raise Unresolved(key)
278
+ op = rest[0] if rest else "exact"
279
+ if op not in LOOKUPS:
280
+ raise Unresolved(key)
281
+ v = val(self, op)
282
+ f = col.field
283
+ if op == "exact":
284
+ if v == "NULL":
285
+ return f"{sql} IS NULL"
286
+ if f is not None and f.is_json and not col.sql.startswith("JSON_EXTRACT"):
287
+ return f"{sql} = {v}"
288
+ return f"{sql} = {v}"
289
+ if op == "iexact":
290
+ return f"UPPER({sql}) = UPPER({v})"
291
+ if op in ("gt", "gte", "lt", "lte"):
292
+ return f"{sql} {dict(gt='>', gte='>=', lt='<', lte='<=')[op]} {v}"
293
+ if op == "in":
294
+ return f"{sql} IN {v}" if v.startswith("(") else f"{sql} IN ({v})"
295
+ if op == "isnull":
296
+ if v == "TRUE":
297
+ return f"{sql} IS NULL"
298
+ if v == "FALSE":
299
+ return f"{sql} IS NOT NULL"
300
+ return f"({sql} IS NULL) = {v}"
301
+ if op == "range":
302
+ return f"{sql} BETWEEN {v}"
303
+ if op in ("contains", "icontains") and f is not None and (f.is_json or f.type_name in ("ArrayField", "HStoreField")):
304
+ return f"{sql} @> {v}"
305
+ if op in ("contains", "startswith", "endswith", "icontains", "istartswith", "iendswith"):
306
+ base = op.lstrip("i") if op.startswith("i") and op != "in" else op
307
+ pat = {"contains": f"'%' || {v} || '%'", "startswith": f"{v} || '%'", "endswith": f"'%' || {v}"}[base]
308
+ return f"UPPER({sql}) LIKE UPPER({pat})" if op.startswith("i") else f"{sql} LIKE {pat}"
309
+ if op in ("regex", "iregex"):
310
+ return f"REGEXP_LIKE({sql}, {v})" if op == "regex" else f"REGEXP_LIKE({sql}, {v}, 'i')"
311
+ if op == "overlap":
312
+ return f"{sql} && {v}"
313
+ if op == "contained_by":
314
+ return f"{sql} <@ {v}"
315
+ if op == "isempty":
316
+ return f"ISEMPTY({sql}) = {v}"
317
+ raise Unresolved(key)
318
+
319
+ # ---- applying a queryset's operations ---------------------------------------------------------------------
320
+ def apply(self, qs: QS) -> "Build":
321
+ for op in qs.ops:
322
+ try:
323
+ self._apply(op)
324
+ except Unresolved as e:
325
+ self.unresolved.append(str(e))
326
+ return self
327
+
328
+ def _apply(self, op: Op) -> None:
329
+ k, d = op.kind, op.data
330
+ if k == "where":
331
+ fn, negate, label = d
332
+ self._pred_agg = False
333
+ was = self._ctx_left
334
+ self._ctx_left = was or op.optional or negate
335
+ try:
336
+ sql = fn(self)
337
+ except Unresolved:
338
+ sql = marker(label)
339
+ self.unresolved.append(label)
340
+ finally:
341
+ self._ctx_left = was
342
+ if not sql:
343
+ return
344
+ if negate:
345
+ sql = f"NOT ({sql})"
346
+ if op.optional:
347
+ sql = marker("optional: " + unmark(sql))
348
+ self.conditional.append("filter")
349
+ (self.having if self._pred_agg else self.where).append(sql)
350
+ elif k == "mark":
351
+ self.where.append(marker(("optional: " if op.optional else "") + d))
352
+ elif k == "order":
353
+ items = [fn(self) for fn in d]
354
+ items = [x for x in items if x]
355
+ if op.optional:
356
+ self.order_optional = items
357
+ self.conditional.append("order_by")
358
+ else:
359
+ self.order, self.order_optional = items, []
360
+ elif k == "distinct":
361
+ self.distinct = True
362
+ self.distinct_on = [self.resolve(p, left=True).sql for p in d]
363
+ elif k == "values":
364
+ fields, flat = d
365
+ vals = []
366
+ for alias, fn, path in fields:
367
+ if path and path in self.annotations:
368
+ vals.append((path, self.annotations[path][0]))
369
+ continue
370
+ try:
371
+ vals.append((alias, fn(self)))
372
+ except Unresolved:
373
+ self.unresolved.append(path or alias or "values()")
374
+ vals.append((alias, marker(path or alias or "value")))
375
+ self.values = vals
376
+ self.flat = flat
377
+ elif k == "only":
378
+ self.only = (self.only or []) + list(d) if d is not None else None
379
+ elif k == "defer":
380
+ self.defer = (self.defer + list(d)) if d is not None else []
381
+ elif k == "sr":
382
+ if d is None:
383
+ self.sr_all = True
384
+ elif d == []:
385
+ self.sr, self.sr_all = [], False
386
+ else:
387
+ self.sr += [p for p in d if p not in self.sr]
388
+ elif k == "annot":
389
+ names, selected = d
390
+ grouped_before = self.agg
391
+ for name, fn in names:
392
+ was_agg, self.agg = self.agg, False
393
+ try:
394
+ sql = fn(self)
395
+ except Unresolved:
396
+ sql = marker(name)
397
+ is_agg = self.agg
398
+ self.agg = was_agg or is_agg
399
+ self.annotations[name] = (sql, is_agg)
400
+ if selected:
401
+ self.annot_selected.append(name)
402
+ if self.values is not None and self.values and not self.flat:
403
+ self.values.append((name, sql)) # values() then annotate(): the annotation is selected too
404
+ if self.agg and not grouped_before:
405
+ # values() before an aggregate annotation groups by those values; otherwise by the row
406
+ if self.values is not None:
407
+ self.group_by = [sql for _, sql in self.values]
408
+ elif self.model.pk is not None:
409
+ self.group_by = [f"{self.root}.{self.model.pk.column}"]
410
+ elif k == "slice":
411
+ lo, hi = d
412
+ # a slice of a slice narrows the first
413
+ if self.lo is None and self.hi is None:
414
+ self.lo, self.hi = lo, hi
415
+ else:
416
+ self.lo, self.hi = _add(self.lo, lo), (_add(self.lo, hi) if hi is not None else self.hi)
417
+ elif k == "reverse":
418
+ self.reverse = not self.reverse
419
+ elif k == "none":
420
+ if op.optional:
421
+ self.conditional.append("none() (then no statement is sent)")
422
+ else:
423
+ self.none = True
424
+ elif k == "lock":
425
+ self.lock = d or " FOR UPDATE"
426
+ if op.optional and k in ("values", "only", "defer", "sr", "annot", "slice", "distinct", "pf"):
427
+ self.conditional.append(k)
428
+
429
+ # ---- output ------------------------------------------------------------------------------------------------
430
+ def model_columns(self, model: Model | None = None, alias: str | None = None, path: tuple = ()) -> list[str]:
431
+ model = model or self.model
432
+ alias = alias or self.root
433
+ out = []
434
+ for f in model.all_columns():
435
+ own = self._owner_alias(model, alias, path, f)
436
+ sql = f"{own}.{f.column}"
437
+ if sql not in out:
438
+ out.append(sql)
439
+ return out
440
+
441
+ def select_list(self) -> list[str]:
442
+ if self.values is not None:
443
+ cols = [sql if not alias or sql.split(".")[-1] == alias else f"{sql} AS {alias}" for alias, sql in self.values]
444
+ if not cols:
445
+ cols = self.model_columns() + [f"{sql} AS {n}" for n, (sql, _) in self.annotations.items() if n in self.annot_selected]
446
+ return cols or ["1"]
447
+ if self.only is not None:
448
+ keep = []
449
+ pk = self.model.pk
450
+ if pk is not None:
451
+ keep.append(f"{self._owner_alias(self.model, self.root, (), pk)}.{pk.column}")
452
+ for p in self.only:
453
+ try:
454
+ c = self.resolve(p, left=True).sql
455
+ except Unresolved:
456
+ continue
457
+ if c not in keep:
458
+ keep.append(c)
459
+ cols = keep
460
+ else:
461
+ cols = self.model_columns()
462
+ if self.defer:
463
+ drop = set()
464
+ for p in self.defer:
465
+ try:
466
+ drop.add(self.resolve(p, left=True).sql)
467
+ except Unresolved:
468
+ continue
469
+ cols = [c for c in cols if c not in drop]
470
+ for n in self.annot_selected:
471
+ sql, _ = self.annotations[n]
472
+ cols.append(f"{sql} AS {n}")
473
+ for p in self.sr_paths():
474
+ cols += [c for c in p if c not in cols]
475
+ return cols
476
+
477
+ def sr_paths(self) -> list[list[str]]:
478
+ """Columns of every select_related() target, adding the joins."""
479
+ out = []
480
+ paths = list(self.sr)
481
+ if self.sr_all:
482
+ paths += [f.name for f in self.model.fields.values() if f.kind in ("fk", "o2o") and not f.null and not f.parent_link
483
+ and f.name not in paths]
484
+ for p in paths:
485
+ model, alias, jpath = self.model, self.root, ()
486
+ ok = True
487
+ for part in p.split("__"):
488
+ f = model.fields.get(part)
489
+ rel = model.reverse.get(part) if f is None else None
490
+ if f is not None and f.kind in ("fk", "o2o") and f.target is not None and f.target.pk is not None and f.target.table:
491
+ own = self._owner_alias(model, alias, jpath, f)
492
+ jpath = jpath + (part,)
493
+ alias = self.join(jpath, f.target.table, f"{own}.{f.column}", f.target.pk.column, left=f.null or self._has_left(jpath[:-1]))
494
+ model = f.target
495
+ elif rel is not None and rel.kind == "rev_o2o" and model.pk is not None and rel.model.table:
496
+ jpath = jpath + (part,)
497
+ alias = self.join(jpath, rel.model.table, f"{alias}.{model.pk.column}", rel.field.column, left=True)
498
+ model = rel.model
499
+ else:
500
+ ok = False
501
+ self.unresolved.append(f"select_related({p})")
502
+ break
503
+ out.append(self.model_columns(model, alias, jpath))
504
+ if not ok:
505
+ continue
506
+ return out
507
+
508
+ def _has_left(self, path: tuple) -> bool:
509
+ j = self.joins.get(path)
510
+ return j is not None and j[2].startswith("LEFT")
511
+
512
+ def where_sql(self, extra: list[str] | None = None) -> str:
513
+ parts = list(extra or []) + self.where
514
+ if self.none:
515
+ parts = ["1 = 0"] + parts
516
+ return " WHERE " + " AND ".join(_paren(p) for p in parts) if parts else ""
517
+
518
+ def order_sql(self, default: bool = True, force_pk: bool = False, flip: bool = False) -> str:
519
+ items = self.order
520
+ if items is None and default and self.group_by is None:
521
+ items = []
522
+ for name in self.model.ordering:
523
+ desc = name.startswith("-")
524
+ try:
525
+ c = self.resolve(name.lstrip("-+"), left=True).sql
526
+ except Unresolved:
527
+ continue
528
+ items.append(c + (" DESC" if desc else " ASC"))
529
+ items = list(items or [])
530
+ if not items and force_pk and self.model.pk is not None:
531
+ items = [f"{self._owner_alias(self.model, self.root, (), self.model.pk)}.{self.model.pk.column} ASC"]
532
+ if flip != self.reverse:
533
+ items = [_flip(x) for x in items]
534
+ if self.order_optional:
535
+ alt = ", ".join(unmark(x) for x in self.order_optional)
536
+ if items:
537
+ return " ORDER BY " + marker(f"one of: {', '.join(unmark(x) for x in items)} | {alt}")
538
+ return " ORDER BY " + marker("optional: " + alt)
539
+ return " ORDER BY " + ", ".join(items) if items else ""
540
+
541
+ def limit_sql(self) -> str:
542
+ out = ""
543
+ if self.hi is not None:
544
+ out += f" LIMIT {_sub(self.hi, self.lo)}"
545
+ if self.lo is not None and self.lo != "0":
546
+ out += f" OFFSET {self.lo}"
547
+ return out
548
+
549
+ def select(self, *, cols: list[str] | None = None, limit: str | None = None, order: bool = True, force_pk: bool = False,
550
+ flip: bool = False, extra_where: list[str] | None = None, lock: bool = True) -> str:
551
+ cols = cols if cols is not None else self.select_list()
552
+ order_sql = self.order_sql(force_pk=force_pk, flip=flip) if order else ""
553
+ head = "SELECT "
554
+ if self.distinct:
555
+ head += "DISTINCT " + (f"ON ({', '.join(self.distinct_on)}) " if self.distinct_on else "")
556
+ sql = head + ", ".join(cols) + " FROM " + self._from(self.model.table, self.root) + self.joins_sql() + self.where_sql(extra_where)
557
+ if self.group_by:
558
+ sql += " GROUP BY " + ", ".join(dict.fromkeys(self.group_by))
559
+ if self.having:
560
+ sql += " HAVING " + " AND ".join(_paren(p) for p in self.having)
561
+ sql += order_sql
562
+ sql += f" LIMIT {limit}" + (f" OFFSET {self.lo}" if self.lo not in (None, "0") else "") if limit is not None else self.limit_sql()
563
+ if lock and self.lock:
564
+ sql += self.lock
565
+ return sql
566
+
567
+ @property
568
+ def needs_subquery(self) -> bool:
569
+ return bool(self.distinct or self.group_by or self.lo is not None or self.hi is not None)
570
+
571
+ def count(self) -> str:
572
+ if self.needs_subquery:
573
+ return f"SELECT COUNT(*) FROM ({self.select(order=False, lock=False)}) subquery"
574
+ return "SELECT COUNT(*) FROM " + self._from(self.model.table, self.root) + self.joins_sql() + self.where_sql()
575
+
576
+ def exists(self) -> str:
577
+ sql = "SELECT 1 AS a FROM " + self._from(self.model.table, self.root) + self.joins_sql() + self.where_sql()
578
+ if self.group_by:
579
+ sql += " GROUP BY " + ", ".join(dict.fromkeys(self.group_by))
580
+ if self.having:
581
+ sql += " HAVING " + " AND ".join(_paren(p) for p in self.having)
582
+ return sql + " LIMIT 1"
583
+
584
+ def pk_sql(self) -> str:
585
+ pk = self.model.pk
586
+ return f"{self._owner_alias(self.model, self.root, (), pk)}.{pk.column}" if pk is not None else f"{self.root}.id"
587
+
588
+ def filtered_write(self, head: str) -> str:
589
+ """UPDATE / DELETE: a plain WHERE on the table, or `pk IN (SELECT ...)` when the filter spans joins."""
590
+ t = self.model.table
591
+ if self.joins or self.needs_subquery:
592
+ inner = self.select(cols=[self.pk_sql()], order=bool(self.hi is not None), lock=False)
593
+ return f"{head} WHERE {t}.{self.model.pk.column if self.model.pk else 'id'} IN ({inner})"
594
+ return head + self.where_sql()
595
+
596
+
597
+ def _is_lookup_tail(rest: list, target: Model | None = None) -> bool:
598
+ """True when what follows a field in a path is transforms and a lookup, not another field."""
599
+ if not rest:
600
+ return True
601
+ first = rest[0]
602
+ if target is not None and (first in target.fields or first == "pk" or first in target.reverse_query or first in target.reverse
603
+ or (first.endswith("_id") and first[:-3] in target.fields)):
604
+ return False
605
+ return first in LOOKUPS or first in TRANSFORMS
606
+
607
+
608
+ def _paren(sql: str) -> str:
609
+ return f"({sql})" if " OR " in sql and not (sql.startswith("(") and sql.endswith(")") and _balanced(sql)) \
610
+ and not sql.startswith("«") else sql
611
+
612
+
613
+ def _balanced(sql: str) -> bool:
614
+ depth = 0
615
+ for i, c in enumerate(sql):
616
+ if c == "(":
617
+ depth += 1
618
+ elif c == ")":
619
+ depth -= 1
620
+ if depth == 0 and i != len(sql) - 1:
621
+ return False
622
+ return depth == 0
623
+
624
+
625
+ def _flip(item: str) -> str:
626
+ if item.startswith("«"):
627
+ return item
628
+ for a, b in ((" DESC NULLS LAST", " ASC NULLS FIRST"), (" ASC NULLS FIRST", " DESC NULLS LAST"),
629
+ (" DESC NULLS FIRST", " ASC NULLS LAST"), (" ASC NULLS LAST", " DESC NULLS FIRST")):
630
+ if item.endswith(a):
631
+ return item[: -len(a)] + b
632
+ if item.endswith(" DESC"):
633
+ return item[:-5] + " ASC"
634
+ if item.endswith(" ASC"):
635
+ return item[:-4] + " DESC"
636
+ return item + " DESC"
637
+
638
+
639
+ def _isint(x) -> bool:
640
+ return isinstance(x, str) and x.isdigit()
641
+
642
+
643
+ def _add(a, b):
644
+ if a is None:
645
+ return b
646
+ if b is None:
647
+ return a
648
+ if _isint(a) and _isint(b):
649
+ return str(int(a) + int(b))
650
+ return marker(f"{unmark(a)} + {unmark(b)}")
651
+
652
+
653
+ def _sub(hi, lo):
654
+ if lo is None or lo == "0":
655
+ return hi
656
+ if _isint(hi) and _isint(lo):
657
+ return str(max(int(hi) - int(lo), 0))
658
+ return marker(f"{unmark(hi)} - {unmark(lo)}")
659
+
660
+
661
+ def lit(value) -> str | None:
662
+ return sql_literal(value)