1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
//! Subquery, `EXISTS` and `OuterRef` builders.
//!
//! Primitives that turn a [`SelectQuery`] into something you can
//! embed inside a larger queryset.
//!
//! [`SelectQuery`]: crate::core::SelectQuery
//!
//! ```ignore
//! use rustango::core::subquery::{exists, not_exists, in_subquery, outer_ref};
//! use rustango::core::{Column as _, F};
//!
//! // EXISTS — "authors who have at least one book".
//! let with_books = Book::objects()
//! .where_(Book::author_id.eq_expr(outer_ref("id")))
//! .compile()?;
//! let authors = Author::objects()
//! .where_expr(exists(with_books))
//! .fetch(&pool).await?;
//!
//! // NOT EXISTS — "authors with no books".
//! let no_books = Book::objects()
//! .where_(Book::author_id.eq_expr(outer_ref("id")))
//! .compile()?;
//! let empty = Author::objects()
//! .where_expr(not_exists(no_books))
//! .fetch(&pool).await?;
//!
//! // IN (SELECT …) — "posts in any of the public categories".
//! let public_cat_ids = Category::objects()
//! .where_(Category::is_public.eq(true))
//! .compile()?;
//! let visible = Post::objects()
//! .where_expr(in_subquery("category_id", public_cat_ids))
//! .fetch(&pool).await?;
//! ```
//!
//! ## How OuterRef resolves
//!
//! [`outer_ref("col")`][outer_ref] returns an [`Expr::OuterRef`]. The
//! SQL writer resolves it against the query one level out:
//!
//! ```text
//! SELECT … FROM "author" WHERE EXISTS (
//! SELECT … FROM "book" WHERE "book"."author_id" = "author"."id"
//! ^^^^^^^^
//! OuterRef
//! )
//! ```
//!
//! The writer keeps a stack of scopes. Every `EXISTS`, `NOT EXISTS`,
//! `IN (SELECT …)` and scalar [`subquery`] pushes a frame, and
//! `outer_ref("col")` reads the nearest one out. Deeper nesting works
//! the same way.
//!
//! ## Validation happens on the inner queryset
//!
//! These builders take an already-compiled [`SelectQuery`], so a bad
//! column name is reported by the inner `queryset.compile()` call, not
//! when the outer query runs. Build the subquery first, propagate `?`,
//! then embed it.
use ;
use ;
use ;
use SqlValue;
/// `EXISTS (subquery)` — true when the subquery returns at least one
/// row.
/// `NOT EXISTS (subquery)` — true when the subquery returns no rows.
/// Use it to find rows in A with no related row in B.
/// `<column> IN (subquery)`. Use it when the inner query needs joins
/// or aggregation that a flat [`crate::core::Op::In`] list cannot
/// express.
///
/// `column` is the outer column. `subquery` must select one column.
/// `<column> NOT IN (subquery)` — inverse of [`in_subquery`].
/// Scalar subquery — `(SELECT … FROM …)`. Usable as an `Expr`
/// wherever `set_expr`, `eq_expr` or a CASE THEN slot takes a value.
///
/// Shape the inner queryset yourself (`.limit(1)`, one projected
/// column) so it returns one column and one row. Anything else is a
/// database error at runtime.
/// Project a correlated scalar subquery as an annotation column,
/// such as "the title of each author's newest book".
/// Wraps the subquery as an [`AggregateExpr`], so it fits
/// [`crate::query::QuerySet::annotate`] and
/// [`crate::query::AggregateBuilder::annotate`]. Any [`outer_ref`]
/// inside `inner` is correlated to the enclosing query.
///
/// Shape `inner` to one column and at most one row
/// (`.values_list_flat(col)` + `.limit(1)`). When nothing matches the
/// column is `NULL`; more than one row is a database error.
///
/// ```ignore
/// // Newest book title per author.
/// let newest = Book::objects()
/// .where_(Book::author_id.eq_expr(outer_ref("id")))
/// .order_by(&[("id", true)])
/// .limit(1)
/// .values_list_flat("title")
/// .compile()?;
/// let rows = Author::objects()
/// .annotate("newest", scalar_subquery(newest))
/// .fetch_values(&pool).await?;
/// ```
/// Correlated `EXISTS (SELECT 1 FROM <child_table> WHERE
/// <child_fk_column> = <outer>.<self_pk_column>)` for a
/// [`ReverseRelation`]. Backs [`crate::query::QuerySet::where_has`].
///
/// The inner query projects nothing, since `EXISTS` only asks whether
/// a row is there. It joins through `OuterRef(self_pk_column)`, which
/// the writer qualifies with the parent table.
/// `NOT EXISTS (subquery)` counterpart of [`reverse_has_exists`].
/// Backs [`crate::query::QuerySet::where_doesnt_have`].
/// Correlated `(SELECT <agg> FROM <child_table> WHERE
/// <child_fk_column> = <outer>.<self_pk_column>)` scalar-aggregate
/// subquery for a [`ReverseRelation`]. Backs
/// [`crate::query::QuerySet::where_has_count`] and the relation
/// aggregates [`crate::query::QuerySet::annotate_count`],
/// `annotate_sum` and friends.
///
/// The inner [`AggregateQuery`] runs `agg` over the child table with
/// no `GROUP BY`, so it yields one scalar row.
/// Correlated `(SELECT COUNT(*) FROM <child> WHERE <child_fk> =
/// <outer>.<pk>)` — [`reverse_has_aggregate`] with `COUNT`. Use it as
/// the left side of a count comparison such as `… > 3`.
/// Wrap any existence predicate (`EXISTS`, `NOT EXISTS`, `RelExists`)
/// in `CASE WHEN <exists> THEN 1 ELSE 0 END` so it can be projected as
/// a column. Backs [`crate::query::QuerySet::annotate_exists`].
///
/// The `1`/`0` integers are deliberate: the column then decodes as
/// `SqlValue::I64(0|1)` on every backend. A bare `EXISTS(…)`
/// projection would give a native `bool` on Postgres but `0|1` on the
/// other two.
/// `OuterRef("col")` — use a column of the enclosing query inside a
/// correlated subquery.
///
/// It only works inside a subquery wrapper ([`exists`],
/// [`not_exists`], [`in_subquery`], [`subquery`]); anywhere else the
/// writer returns
/// [`crate::sql::SqlError::OuterRefOutsideSubquery`]. `column` is a
/// column on the outer model and is emitted as
/// `"<outer_table>"."<col>"`, so it stays unambiguous when inner and
/// outer tables share a column name.
// ----------------------------------------------------------------- M2M
/// `[NOT ]EXISTS (SELECT 1 FROM <through> WHERE <src_col> =
/// <outer>.<self_pk>)` — many-to-many existence, checked on the
/// junction table. `self_pk` is the parent model's primary-key
/// column. Backs [`crate::query::QuerySet::where_has`] for M2M.
/// Correlated many-to-many aggregate. `Count` counts **junction rows**
/// (`SELECT COUNT(*) FROM <through> WHERE <src_col> = <outer>.<self_pk>`);
/// `Sum`/`Avg`/`Max`/`Min` aggregate `column` on the **target** table,
/// reached through the junction:
///
/// ```text
/// (SELECT <agg>(<column>) FROM <to>
/// WHERE <to>.id IN (SELECT <dst_col> FROM <through>
/// WHERE <src_col> = <outer>.<self_pk>))
/// ```
///
/// The target PK is assumed to be `"id"`, rustango's surrogate-PK
/// convention, because [`M2MRelation`] does not carry it.
// ----------------------------------------------------------- GFK / generic
/// Content-type discriminator for a generic-FK relation. The registry
/// names (`rustango_content_types` / `id` / `table`) match
/// [`crate::contenttypes::ContentType`]. They are inlined instead of
/// read from `ContentType::SCHEMA` so `core` does not depend on the
/// contenttypes app module.
/// `[NOT ]EXISTS (SELECT 1 FROM <child> WHERE <pk_column> =
/// <outer>.<self_pk> AND <ct_column> = (SELECT id FROM
/// rustango_content_types WHERE "table" = '<parent_table>'))` —
/// generic (polymorphic) relation existence. `parent_table` is the
/// querying model's table name, a compile-time constant. The nested
/// subquery resolves its content-type id, so no async lookup is
/// needed.
/// Correlated generic-FK aggregate over a child column. The child
/// table holds the data, so no junction table is involved. `Count`
/// ignores `column`.