ingraph/comparison/sql/collection/mod.rs
1//! The collection comparisons for a collection kept IN ITS OWN COLUMN — [`SqlListComparison`] for a
2//! sequence and [`SqlSetComparison`] for a set — with one concrete lowering of each per dialect.
3//!
4//! The two are separate types rather than one under a shape marker for the reason
5//! [`ListFilter`](crate::ListFilter) and [`SetFilter`](crate::SetFilter) are: they hold different
6//! operators. What they share is the storage question — which of them a dialect can keep in a column
7//! at all — and that is [`CollectionStorage`], one row per dialect answering for both.
8
9use core::marker::PhantomData;
10
11// Gated with their only users, the two dialects with no array type: they name `Carrier` and the
12// second storage strategy's two kinds in their storage rows, and the shared JSON slot walks below
13// are themselves gated with the per-dialect impls that call them. An import carries the cfg its
14// consumer carries, and the run that catches a mismatch is the one where the family root is on and
15// every dialect is off. Postgres reaches the same two kinds from its own module, where the element
16// type rather than the dialect names them.
17#[cfg(any(feature = "sqlite", feature = "mysql"))]
18use super::{
19 Carrier, CollectionOp, JsonElement, SqlConjunction, SqlEdgeComparison, SqlEdgeSetComparison,
20 json_elements,
21};
22#[cfg(any(feature = "sqlite", feature = "mysql"))]
23use crate::comparison::At;
24use crate::{
25 ListFilter, QuantifiedFilter, SetFilter, TryMapFilter,
26 comparison::{Backend, ComplexComparison, ToDatabaseComparison, TryFromFilter},
27};
28
29comparison_kind! {
30 /// A [`ListFilter`]'s storage-side twin for a SEQUENCE kept in its own column: the same nine
31 /// operators, over the ELEMENT type this database stores the members as.
32 ///
33 /// # One of two strategies, and [`CollectionStorage`] is where a dialect picks
34 ///
35 /// Postgres can name this one, because it has a native `ARRAY` and the operators to match — and
36 /// it names it per ELEMENT TYPE, through [`PgCollectionStorage`], because an array holds only the
37 /// elements sqlx names an array type for. SQLite and MySQL name
38 /// [`SqlEdgeComparison`](super::SqlEdgeComparison) for every element, because what they can keep
39 /// in a column is JSON and a JSON collection cannot be indexed. This kind is what a sequence
40 /// stored in a column is compared through wherever one IS stored that way, which is what the
41 /// three impls below are.
42 ///
43 /// # The kind whose dialects agree about NOTHING — which is why it is three impls
44 ///
45 /// | dialect | column | operand | ordering |
46 /// |---|---|---|---|
47 /// | Postgres | native `ARRAY` | the ELEMENTS, bound as one array — `V: PgHasArrayType` | element-wise `<`, native |
48 /// | SQLite | TEXT holding a JSON array | one canonical JSON string — `V: JsonElement` | none |
49 /// | MySQL | native `JSON` | one canonical JSON string — `V: JsonElement` | none |
50 ///
51 /// The bounds are disjoint, and that is the point this kind proves. `V: PgHasArrayType` is a trait
52 /// sqlx declares for Postgres and for nothing else, so ONE impl over three dialects could not ask
53 /// for it — and the version of this kind that had one lowered Postgres through `jsonb`, on an
54 /// engine with native arrays and the operators to match. The JSON encoding was not a judgement
55 /// about Postgres; it was what the impl shape left available.
56 ///
57 /// # The JSON lowerings are correct, and correctness is not what settled the default
58 ///
59 /// Neither SQLite nor MySQL has an array type, so a collection kept in a column there is JSON, and
60 /// both give the right answer for whole-collection equality and for membership. What they cannot
61 /// do is ORDER two collections, and that is refused at the crossing rather than approximated — see
62 /// [`ListCrossingError::JsonOrdering`].
63 ///
64 /// What they also cannot do is use an INDEX, which is the whole of why [`CollectionStorage`]
65 /// sends a declared value list to an edge table on those two dialects instead. These two impls
66 /// are what a sequence ALREADY held as a JSON array is compared through.
67 ///
68 /// # The bind count does not follow the operand's LENGTH
69 ///
70 /// One bind per operator on every dialect. Postgres binds an ARRAY of N elements as one parameter
71 /// and the other two bind one JSON string, so a thousand-element `eq` costs one bind where a
72 /// thousand-element `IN` costs a thousand — the 65535 / 32766 ceilings are unreachable from this
73 /// kind on any dialect.
74 ///
75 /// # `has_element` is the exception to the operand SHAPE and not to the encoding
76 ///
77 /// It holds one element and lowers as containment of the singleton collection, so it takes the
78 /// same path as the six whole-collection slots on every dialect. Containment is order-blind where
79 /// every other operator here is not, and that is membership's own nature rather than this kind
80 /// borrowing from [`SqlSetComparison`]: "is `x` in this sequence" has no positional answer to
81 /// give.
82 ///
83 /// # `any` holds a COMPARISON, and `C` is the element's
84 ///
85 /// The eighth slot is not an operand. It is the comparison ONE element of this collection is
86 /// asked, which is whatever the element's own filter kind crossed into — a scalar's, a text's, a
87 /// byte string's — so it is a type parameter rather than another `Option<V>`. What renders it is
88 /// [`push_element_scope`](super::push_element_scope), which opens a scope naming the member and
89 /// hands the comparison an [`At`] like any other.
90 ///
91 /// Only ONE of this kind's two dialect groups can answer it. Postgres has `unnest`, which is a
92 /// real element scope; SQLite has `json_each`, which is one for the element vocabularies whose
93 /// canonical JSON token decodes to the value their carrier binds; MySQL has neither and refuses —
94 /// see [`SqlLoweringError::JsonElementScope`](super::SqlLoweringError::JsonElementScope).
95 ///
96 /// # `count` holds a comparison too, and every dialect answers it
97 ///
98 /// The ninth slot is a [`SqlCountComparison`](super::SqlCountComparison) — the eight operators a
99 /// number takes, against this column's LENGTH. Each dialect names its own cardinality
100 /// (`json_array_length`, `cardinality`, `JSON_LENGTH`) and the operators to the right of it are
101 /// one walk, so a count is one question with three spellings of the expression it compares.
102 ///
103 /// MySQL answers it where it refuses `any`, and the difference is what each needs: a cardinality
104 /// is a SCALAR function over the stored value, where an element question needs a table function
105 /// whose rows the optimizer moves out from under the correlation.
106 SqlListComparison {
107 one { has_element }
108 many { eq, ne, gt, gte, lt, lte }
109 element { any: C }
110 cardinality { count }
111 }
112}
113
114comparison_kind! {
115 /// A [`SetFilter`]'s storage-side twin for a set kept in its own column: the same eight
116 /// operators, over the ELEMENT type this database stores the members as.
117 ///
118 /// # No engine has a set type, so this is a column shape it shares with the sequence
119 ///
120 /// Postgres has no set type and stores one in an `ARRAY` column; SQLite and MySQL have neither and
121 /// store one as JSON. MySQL's `SET` is real and does not generalise — it is a fixed enumerated
122 /// type of at most 64 members declared in the schema, so an open vocabulary cannot use it. The two
123 /// column-stored kinds therefore guard the same physical column and differ in which operators they
124 /// emit against it, which is exactly what the shape parameter they replace used to decide.
125 ///
126 /// | dialect | operators |
127 /// |---|---|
128 /// | Postgres | `@>` `<@` `&&`, all native; equality is mutual containment |
129 /// | SQLite | `json_each` set expressions |
130 /// | MySQL | `JSON_CONTAINS` / `JSON_OVERLAPS` |
131 ///
132 /// # No OPERATOR here can be refused, which is why the crossing is ONE impl
133 ///
134 /// The sequence kind's crossings are per-dialect because two dialects cannot answer an ordering.
135 /// Every operator here is order- and multiplicity-blind, so all three dialects and both storage
136 /// strategies answer all six, and no dialect has a no to give about them. That is what makes the
137 /// crossing dialect-free, and it is the split paying for itself: the crossing error used to carry
138 /// a variant for an unordered column asked to compare as a magnitude, and no such column can be
139 /// asked any more.
140 ///
141 /// One dialect does refuse `any`, and it refuses at the LOWERING rather than here — the element
142 /// SCOPE is an address, and an address arrives with the application. So this crossing stays one
143 /// impl and gains only the two failures every collection crossing now has: the ELEMENT crossing's
144 /// own, and a `count` operand no cardinality integer can hold.
145 ///
146 /// # Whole-collection equality binds each direction
147 ///
148 /// A set's stored element order is an artefact of insertion, so its equality is mutual containment
149 /// and costs two binds where every other operator costs one. The bind count still does not follow
150 /// the operand's LENGTH on any dialect.
151 ///
152 /// `has_element` holds one element and lowers as containment of the singleton, so it takes the
153 /// same path as the five whole-collection slots. `any` and `count` each hold a whole COMPARISON
154 /// and take none of them — see [`SqlListComparison`], whose two slots these are the twins of.
155 SqlSetComparison {
156 one { has_element }
157 many { eq, ne, encloses, enclosed_by, overlaps }
158 element { any: C }
159 cardinality { count }
160 }
161}
162
163/// Why a [`ListFilter`]'s operands did not become storage values.
164///
165/// The second crossing error in the family, and it carries the same shape
166/// [`BytesCrossingError`](super::BytesCrossingError) does: the converter's own failure beside the
167/// refusal the vocabulary can express but this dialect cannot answer. A refusal says so, where an
168/// empty result set would read as an honest miss.
169///
170/// # Two converter errors, because a collection filter now holds two kinds of operand
171///
172/// `E` is the ELEMENT converter's — the `f` a crossing is given, or the storage type's own
173/// [`TryFrom`] where it is not — and `X` is the ELEMENT FILTER's crossing error, which belongs to
174/// whatever kind guards one member. They are independent: a `Vec<[u8; 32]>` converts its elements
175/// with one and crosses its `any` slot with [`BytesCrossingError`](super::BytesCrossingError), and
176/// no bound makes those one type.
177///
178/// `X` DEFAULTS to `E`, which is the case every value kind produces: a scalar, text, enum, boolean
179/// or duration element crosses with exactly its storage type's conversion error, so
180/// `ListCrossingError<Infallible>` still spells the identity crossing over such an element.
181///
182/// # The CARDINALITY's failure is a variant and not a third parameter
183///
184/// A `count` operand is a `usize` and this family compares a cardinality as `i64`, so what can fail
185/// there is fixed by the family rather than chosen by a caller — there is nothing for a parameter to
186/// range over. That is the whole difference from the two above, each of which carries a converter
187/// somebody else wrote.
188#[derive(Debug, Clone, Copy, PartialEq, Eq)]
189pub enum ListCrossingError<E, X = E> {
190 /// An element did not convert into the column's storage type — the converter's own error.
191 ///
192 /// Either LEVEL: an operand written inside the nested `any` filter is an element too, so the
193 /// one-converter crossing reports its refusal here rather than under `Element`.
194 Operand(E),
195 /// The ELEMENT filter did not cross into an element comparison — that crossing's own error.
196 Element(X),
197 /// A `count` operand does not fit the integer this family compares a cardinality as.
198 ///
199 /// Refused rather than saturated: an operand a client sent is not a number this crate may
200 /// substitute, and a substituted one is a wrong result set reported as a right one. No collection
201 /// any engine here can hold reaches it.
202 Cardinality(core::num::TryFromIntError),
203 /// A sequence stored as JSON was asked to compare as a magnitude, named here by its operator
204 /// (`"gt"` / `"gte"` / `"lt"` / `"lte"`).
205 ///
206 /// SQLite and MySQL have no array type: a collection column is a JSON array, and JSON has no
207 /// element-wise collection order. MySQL does define an ordering over JSON VALUES, and it is not
208 /// this one — it ranks by element type before value — so adopting it would answer a different
209 /// question under the same operator name. Postgres has the operator natively and an edge table has
210 /// an ordinal column, so neither raises this.
211 JsonOrdering(&'static str),
212}
213
214impl<E: core::fmt::Display, X: core::fmt::Display> core::fmt::Display for ListCrossingError<E, X> {
215 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
216 match self {
217 Self::Operand(error) => error.fmt(f),
218 Self::Element(error) => error.fmt(f),
219 Self::Cardinality(error) => error.fmt(f),
220 Self::JsonOrdering(operator) => write!(
221 f,
222 "operator {operator:?} compares collections element-wise and this dialect stores a \
223 collection as JSON, which has no such order"
224 ),
225 }
226 }
227}
228
229impl<E, X> std::error::Error for ListCrossingError<E, X>
230where
231 E: std::error::Error + 'static,
232 X: std::error::Error + 'static,
233{
234 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
235 match self {
236 Self::Operand(error) => Some(error),
237 Self::Element(error) => Some(error),
238 Self::Cardinality(error) => Some(error),
239 Self::JsonOrdering(_) => None,
240 }
241 }
242}
243
244/// Why a [`SetFilter`]'s operands did not become storage values.
245///
246/// It exists because a collection filter carries a nested FILTER — the `any` slot — and a nested
247/// filter crosses through its own kind with its own error. Before that slot, a set crossing's only
248/// failure was the element converter's and its error simply WAS the converter's; there is now a
249/// second, so there is a type.
250///
251/// What it still has no variant for is a REFUSAL, and that absence is the same load-bearing one it
252/// always was: [`ListCrossingError::JsonOrdering`] has no counterpart here, because the operator
253/// that raises it is not on this kind. The one dialect that declines `any` declines it at the
254/// lowering rather than at the crossing — the element scope is an ADDRESS — so nothing here names a
255/// dialect either.
256///
257/// `E` and `X` are [`ListCrossingError`]'s two, with the same default and for the same reason, and
258/// the cardinality variant is that type's for the reason stated there.
259#[derive(Debug, Clone, Copy, PartialEq, Eq)]
260pub enum SetCrossingError<E, X = E> {
261 /// An element did not convert into the column's storage type — the converter's own error.
262 ///
263 /// Either LEVEL: an operand written inside the nested `any` filter is an element too, so the
264 /// one-converter crossing reports its refusal here rather than under `Element`.
265 Operand(E),
266 /// The ELEMENT filter did not cross into an element comparison — that crossing's own error.
267 Element(X),
268 /// A `count` operand does not fit the integer this family compares a cardinality as — as
269 /// [`ListCrossingError::Cardinality`].
270 Cardinality(core::num::TryFromIntError),
271}
272
273impl<E: core::fmt::Display, X: core::fmt::Display> core::fmt::Display for SetCrossingError<E, X> {
274 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
275 match self {
276 Self::Operand(error) => error.fmt(f),
277 Self::Element(error) => error.fmt(f),
278 Self::Cardinality(error) => error.fmt(f),
279 }
280 }
281}
282
283impl<E, X> std::error::Error for SetCrossingError<E, X>
284where
285 E: std::error::Error + 'static,
286 X: std::error::Error + 'static,
287{
288 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
289 match self {
290 Self::Operand(error) => Some(error),
291 Self::Element(error) => Some(error),
292 Self::Cardinality(error) => Some(error),
293 }
294 }
295}
296
297/// Collapse the element leg's own refusal into the crossing's, which is what makes ONE declared
298/// converter's refusal read the same at both levels.
299///
300/// The one-converter crossings hand the `g` slot a closure that reports the CONVERTER's refusal as
301/// [`ListCrossingError::Operand`] and the element comparison's as
302/// [`ListCrossingError::Element`] — so what comes back is this type inside its own `Element`, and
303/// what a caller is owed is one level. `Element(inner) => inner` is the whole of the collapse; the
304/// other three arms are the outer crossing's own refusals, which the inner leg never produces and
305/// which nothing here should be able to invent a second spelling of.
306///
307/// Shared by every kind that refuses with [`ListCrossingError`] — the edge-table sequence and the
308/// three column-stored ones — because a nested operand is the converter's refusal on all four.
309pub(super) fn flatten_list<E, X>(
310 why: ListCrossingError<E, ListCrossingError<E, X>>,
311) -> ListCrossingError<E, X> {
312 match why {
313 ListCrossingError::Operand(error) => ListCrossingError::Operand(error),
314 ListCrossingError::Element(inner) => inner,
315 ListCrossingError::Cardinality(error) => ListCrossingError::Cardinality(error),
316 ListCrossingError::JsonOrdering(operator) => ListCrossingError::JsonOrdering(operator),
317 }
318}
319
320/// The same collapse for a set — see [`flatten_list`], whose note this shares. A set has no
321/// ordering refusal to carry through, which is the one arm of difference.
322pub(super) fn flatten_set<E, X>(
323 why: SetCrossingError<E, SetCrossingError<E, X>>,
324) -> SetCrossingError<E, X> {
325 match why {
326 SetCrossingError::Operand(error) => SetCrossingError::Operand(error),
327 SetCrossingError::Element(inner) => inner,
328 SetCrossingError::Cardinality(error) => SetCrossingError::Cardinality(error),
329 }
330}
331
332/// The first ordering operator `filter` sets, by name — the list both refusals walk, so the two
333/// cannot disagree about which four operators are the ordering ones.
334///
335/// Gated with the two JSON dialects that are its only callers: an edge-table sequence has an ordinal
336/// column and answers all four, and Postgres has the operator natively, so neither asks.
337#[cfg(any(feature = "sqlite", feature = "mysql"))]
338pub(super) fn ordering_operator<D, VF>(filter: &ListFilter<D, VF>) -> Option<&'static str> {
339 [
340 ("gt", filter.gt().is_some()),
341 ("gte", filter.gte().is_some()),
342 ("lt", filter.lt().is_some()),
343 ("lte", filter.lte().is_some()),
344 ]
345 .into_iter()
346 .find_map(|(name, set)| set.then_some(name))
347}
348
349/// Cross ONE element filter into the element comparison a collection holds, or `None` where the
350/// operator is absent.
351///
352/// The `any` half of every collection crossing, shared by all four kinds and both shapes — the
353/// `Option` walk, so that six crossings hold one statement of what an absent operator crosses into.
354///
355/// `g` is the element's own crossing rather than the element CONVERTER, and the division is
356/// [`Nullable`](crate::Nullable)'s: a wrapper's parameter ranges over what it holds, and this slot
357/// holds a whole filter.
358///
359/// It is what makes the second error variant necessary, and also why that variant cannot be folded
360/// into the first: `g`'s error is the element kind's, and nothing relates it to the element
361/// converter's.
362// Not gated on a dialect, where `from_stored` below is: two of the six crossings this serves are the
363// correlated kinds', which name no database.
364pub(super) fn cross_element<VF, C, X>(
365 filter: Option<VF>,
366 g: impl FnOnce(VF) -> Result<C, X>,
367) -> Result<Option<C>, X> {
368 match filter {
369 Some(filter) => g(filter).map(Some),
370 None => Ok(None),
371 }
372}
373
374/// Cross ONE cardinality filter into the count comparison a collection holds, or `None` where the
375/// operator is absent.
376///
377/// The `count` half of every collection crossing, and it takes NO converter where
378/// [`cross_element`] does: a cardinality is a `usize` on one side and this family's integer on the
379/// other, so the conversion is settled here rather than by the caller — which is the same fact the
380/// concrete error variant states.
381// Ungated for the reason [`cross_element`] is.
382pub(super) fn cross_count<Db>(
383 filter: Option<crate::ScalarFilter<usize>>,
384) -> Result<Option<super::SqlCountComparison<i64, Db>>, core::num::TryFromIntError> {
385 match filter {
386 Some(filter) => super::SqlCountComparison::try_from_filter(filter).map(Some),
387 None => Ok(None),
388 }
389}
390
391/// The half of a sequence crossing that is the same in every dialect: the already-converted filter's
392/// slots, moved across. What differs is the REFUSAL each dialect makes first.
393#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
394fn from_stored<V, VF, C, Db>(
395 stored: ListFilter<V, VF>,
396 any: Option<C>,
397 count: Option<super::SqlCountComparison<i64, Db>>,
398) -> SqlListComparison<V, C, Db> {
399 SqlListComparison {
400 has_element: stored.has_element,
401 eq: stored.eq,
402 ne: stored.ne,
403 gt: stored.gt,
404 gte: stored.gte,
405 lt: stored.lt,
406 lte: stored.lte,
407 any,
408 count,
409 db: PhantomData,
410 }
411}
412
413impl<V, C, Db> SqlSetComparison<V, C, Db> {
414 /// Cross a [`SetFilter`] into a column-stored set comparison through ONE converter — see
415 /// [`SqlEdgeComparison::try_from_filter_with`](super::SqlEdgeComparison::try_from_filter_with)
416 /// for what the single converter is and why a declaration gets one.
417 ///
418 /// # Errors
419 ///
420 /// As [`try_from_filter_with_element`](Self::try_from_filter_with_element), with `f`'s refusal
421 /// standing for both levels of operand.
422 pub fn try_from_filter_with<D, VF, E, F>(
423 filter: SetFilter<D, VF>,
424 f: F,
425 ) -> Result<Self, SetCrossingError<E, <C as TryFromFilter<VF::Mapped>>::Error>>
426 where
427 F: Fn(D) -> Result<V, E>,
428 VF: TryMapFilter<D, V>,
429 C: TryFromFilter<VF::Mapped>,
430 {
431 Self::try_from_filter_with_element(filter, &f, |element| {
432 let stored = element
433 .try_map_filter(&f)
434 .map_err(SetCrossingError::Operand)?;
435 C::try_from_filter(stored).map_err(SetCrossingError::Element)
436 })
437 .map_err(flatten_set)
438 }
439
440 /// Cross a [`SetFilter`] into a column-stored set comparison, converting each ELEMENT with `f` and
441 /// the nested ELEMENT FILTER with `g`.
442 ///
443 /// Dialect-free, where the sequence kind's three crossings each name their database: every
444 /// operator a set carries is answerable on all three, so no dialect has a refusal to make here.
445 ///
446 /// # Errors
447 ///
448 /// [`SetCrossingError::Operand`] for whatever `f` refuses an element with, and
449 /// [`SetCrossingError::Element`] for whatever `g` refuses the element filter with.
450 ///
451 /// `g` crosses the ELEMENT filter, and it is a second function rather than a use of `f` because
452 /// the two convert different things: `f` maps one ELEMENT into its storage type, while the `any`
453 /// slot holds a whole FILTER whose own operands are the element kind's to convert. A caller
454 /// holding ONE converter for both is asking [`try_from_filter_with`](Self::try_from_filter_with),
455 /// which composes them; the identity crossing below passes [`TryFromFilter::try_from_filter`] and
456 /// needs no closure at all.
457 pub fn try_from_filter_with_element<D, VF, E, F, X, G>(
458 filter: SetFilter<D, VF>,
459 f: F,
460 g: G,
461 ) -> Result<Self, SetCrossingError<E, X>>
462 where
463 F: FnMut(D) -> Result<V, E>,
464 G: FnOnce(VF) -> Result<C, X>,
465 {
466 let mut stored = filter.try_map(f).map_err(SetCrossingError::Operand)?;
467 let any = cross_element(stored.any.take(), g).map_err(SetCrossingError::Element)?;
468 let count = cross_count(stored.count).map_err(SetCrossingError::Cardinality)?;
469 Ok(Self {
470 has_element: stored.has_element,
471 eq: stored.eq,
472 ne: stored.ne,
473 encloses: stored.encloses,
474 enclosed_by: stored.enclosed_by,
475 overlaps: stored.overlaps,
476 any,
477 count,
478 db: PhantomData,
479 })
480 }
481}
482
483/// The identity crossing for a column-stored set — a set of `String` kept in a `text[]` is the
484/// common one.
485///
486/// # Errors
487///
488/// As [`try_from_filter_with_element`](SqlSetComparison::try_from_filter_with_element).
489impl<D, VF, V: TryFrom<D>, C: TryFromFilter<VF>, Db> TryFromFilter<SetFilter<D, VF>>
490 for SqlSetComparison<V, C, Db>
491{
492 type Error = SetCrossingError<V::Error, C::Error>;
493
494 fn try_from_filter(filter: SetFilter<D, VF>) -> Result<Self, Self::Error> {
495 Self::try_from_filter_with_element(filter, V::try_from, C::try_from_filter)
496 }
497}
498
499/// Which storage strategy a dialect keeps a value list in, named by the comparisons that address it.
500///
501/// # The one split in this family that is not about spelling
502///
503/// Every other per-dialect split here is a disagreement about how to WRITE a question, or about the
504/// bounds an operand needs. This one is a disagreement about what is STORED. SQLite and MySQL have
505/// no array type: what they can keep in a column is JSON, and both JSON forms give the right answer
506/// while neither can use an INDEX — `json_each` is a table-valued function, so SQLite's is a full
507/// scan with a JSON parse per row, and `JSON_CONTAINS` is not sargable on a plain `JSON` column.
508/// SQLite is this project's primary database, so those two keep a value list in an EDGE TABLE and
509/// name [`SqlEdgeComparison`](super::SqlEdgeComparison) and
510/// [`SqlEdgeSetComparison`](super::SqlEdgeSetComparison), whose every operator is an indexed
511/// `EXISTS`. Postgres has a native `ARRAY` and can keep a value list in the column — for the element
512/// types whose bytes an array can actually hold, which is not all of them, so its row delegates to
513/// [`PgCollectionStorage`] rather than answering.
514///
515/// Two storage shapes are two comparison TYPES rather than more impls of one, because what the
516/// second one needs is not a different rendering: it is a table name and the parent's key columns,
517/// which [`ComplexComparison::apply`](crate::ComplexComparison::apply) does not carry and which
518/// would be dead on a dialect keeping a list in its column.
519///
520/// # Two associated types, because the shape stopped being a parameter
521///
522/// This trait was keyed on a `List` / `Set` marker that every row was generic over and no row read:
523/// the shape decided what a comparison MEANT and never which strategy stored it. With the collection
524/// filter split in two, the shape is the NAME of an answer instead — a row states both, and states
525/// them independently. An element type whose sequence belongs in an array column while its set
526/// belongs in an edge table costs one row either way, and a parameter no row branched on could not
527/// express it at all.
528///
529/// # A trait rather than one [`ToDatabaseComparison`] row per dialect
530///
531/// The map stays ONE impl per filter kind and what varies is an associated type stated per dialect —
532/// the arrangement [`QuoteIdent`](super::QuoteIdent) and [`BindCeiling`](super::BindCeiling) already
533/// have one level further out, where the dialect states a character or a number and the work is
534/// written once. It is also what keeps the choice open: a dialect this crate does not ship states
535/// its own strategy in a row of its own, where concrete rows would have to be edited to admit a
536/// fourth.
537///
538/// # The lowering promise travels DOWN to here, because this is where the strategy is chosen
539///
540/// [`ToDatabaseComparison::Comparison`](crate::ToDatabaseComparison::Comparison) promises
541/// [`ComplexComparison`], and the two rows below it hand that question straight to this trait: their
542/// `Comparison` IS one of this one's, so a promise stated only up there would have to be proved from
543/// `Db: CollectionStorage<V>` alone, where the types are opaque. Restating it here is what makes it
544/// provable, and it is stated at the right place — a dialect choosing a strategy is choosing a
545/// comparison, and a strategy whose comparison cannot be lowered is not one.
546///
547/// It is also what keeps the choice OPEN under the promise: a dialect this crate does not ship
548/// states its own row and keeps the same promise, rather than the promise being a list of the four
549/// types this file happens to name.
550///
551/// # `VF` is the ELEMENT's FILTER, and the element's crossing happens in the ROW
552///
553/// A collection comparison holds the comparison one MEMBER is asked, so a strategy names that
554/// strategy over this element type AND that element's comparison. What travels here is the element's
555/// FILTER rather than its comparison, and the difference is where
556/// `<VF as ToDatabaseComparison<V, Db>>::Comparison` is written: inside a row, which is selected only
557/// once a dialect is named.
558///
559/// Written on THIS trait instead, it would land in
560/// [`ToDatabaseComparison`]'s own header — and an emitted comparison assumes exactly that predicate
561/// at a database it has not named yet. A projection in it makes rustc resolve the inner crossing to
562/// know the outer trait-ref's arguments, and a nested crossing is not something an expansion states.
563/// Measured: every collection column in `ingraph-derive`'s fixtures failed as
564/// *`__INGRAPH_DB__: CollectionStorage<Vec<String>, _>` is not satisfied*, with the second argument
565/// an inference variable. With the filter here the trait-ref is concrete on both arguments, and the
566/// assumption applies exactly as it did before this parameter existed.
567pub trait CollectionStorage<V, VF>: sqlx::Database + Backend {
568 /// The comparison a [`ListFilter`] crosses into on this dialect.
569 type Sequence: ComplexComparison<Self>;
570 /// The comparison a [`SetFilter`] crosses into on this dialect.
571 type Set: ComplexComparison<Self>;
572}
573
574/// The one dialect with a choice to make, so its row makes none: it states whatever the ELEMENT
575/// type's [`PgCollectionStorage`] row states, and that is where array-versus-edge is decided.
576#[cfg(feature = "postgres")]
577impl<V: PgCollectionStorage<VF>, VF> CollectionStorage<V, VF> for sqlx::Postgres {
578 type Sequence = <V as PgCollectionStorage<VF>>::Sequence;
579 type Set = <V as PgCollectionStorage<VF>>::Set;
580}
581
582/// Which storage strategy Postgres keeps a collection of THIS element type in — the half of
583/// [`CollectionStorage`] that the one dialect with two usable strategies cannot answer from the
584/// dialect alone.
585///
586/// Public, and for the reason [`Carrier`](super::Carrier) is: this is the surface a downstream
587/// element type joins the collection vocabulary through on Postgres, and a type with a row here
588/// needs nothing else from this crate to be filtered on as a list or as a set.
589///
590/// # Why the dialect cannot answer alone
591///
592/// Both column-stored kinds' Postgres lowerings are bounded `V: PgHasArrayType` — the sqlx row
593/// naming the array type OID an element lives in — and a great many element types have no such row.
594/// This crate's own [`BeU64`](crate::BeU64) is one: it binds fine as a scalar and sqlx names no
595/// array type for a blob carrier. A dialect-keyed answer sends every one of them to a column-stored
596/// kind and the bound then fails at the LOWERING, naming a sqlx trait, with no fallback and no way
597/// to ask for one.
598///
599/// So the refusal moves here, and moving it is half of what this trait buys: a missing row is
600/// `E0277` at the crossing, naming the row a reader can go and write, where it used to be `E0599`
601/// on `apply` naming `PgHasArrayType`. That message is pinned as exact text —
602/// `tests/pg_collection_strategy/` — because it is the deliverable rather than a side effect.
603///
604/// # Why the choice is declared rather than deduced
605///
606/// The two impls that would deduce it —
607///
608/// ```text
609/// impl<V: PgHasArrayType> CollectionStorage<V> for Postgres { … }
610/// impl<V> CollectionStorage<V> for Postgres { … }
611/// ```
612///
613/// — are `E0119`, and both routes out of that are unstable: `V: !PgHasArrayType` is a negative bound
614/// and the alternative is specialization. So the choice is a ROW, and the row is keyed on the
615/// element type because that is what it is a fact about.
616///
617/// A blanket `impl<V: PgHasArrayType> PgCollectionStorage for V` is refused for the same reason one
618/// level down: it would make the array case automatic and then leave a type WITHOUT an array type
619/// unable to be given a row at all, since a specific impl would overlap the blanket and rustc will
620/// not prove the negative for a foreign trait. That closes the surface this trait exists to open.
621/// Per-type rows are what [`Carrier`](super::Carrier) already asks for, and a downstream pays the
622/// same one-line price here that it pays there.
623///
624/// # A row that has the array and declines it is legal, and that is the second thing this buys
625///
626/// The strategy is not a fallback for types the array cannot hold. An element type with a perfectly
627/// good `PgHasArrayType` may name the edge table anyway — a list long enough that an unindexed `@>`
628/// over it is the wrong plan, or an index shape an array cannot give — and it costs one row. That
629/// was unspellable while the dialect answered.
630///
631/// # The two answers are independent, which the shape parameter could not make them
632///
633/// A row states its sequence strategy and its set strategy separately, so an element may keep an
634/// ordered column in an array and send its unordered one to an edge table — where an index on
635/// `(key…, value)` answers containment with a seek and an array cannot. Every row this crate ships
636/// states the same strategy twice, and that is a fact about these elements rather than a rule.
637///
638/// # The rows this crate ships
639///
640/// One per element type in the Postgres [`Carrier`](super::Carrier) table, and the rule that picks
641/// between the two is a single question: **does sqlx's array type for this element match the column
642/// its carrier row binds into?** Where it does, the array; where it does not — or where there is no
643/// array type at all — the edge table. See the two lists beside the rows themselves.
644///
645/// # The lowering promise travels ONE level further, for the reason it reached
646/// [`CollectionStorage`] at all
647///
648/// Postgres's row states whatever this one states — its two answers ARE this one's — so a promise
649/// that stopped at the dialect would have to be proved from `V: PgCollectionStorage` alone, where
650/// the types are opaque. Restating it here is what makes it provable, and it lands where the choice
651/// is actually made: an element type picking a strategy is picking a comparison, and a strategy
652/// whose comparison cannot be lowered is not one.
653///
654/// # `VF` travels here too, for the reason it reached [`CollectionStorage`]
655///
656/// A strategy names a comparison and a collection comparison holds the ELEMENT's, so a row states
657/// its answer over both. A row is still one line per element type, and it is where the element's own
658/// crossing is finally written — at a named dialect, which is the only place a projection through it
659/// resolves.
660///
661/// # The refusal is WRITTEN, and the list beside it is made to stop moving
662///
663/// Unimplemented, rustc names the eight types with a row that sort first and says *and N others*.
664/// Which eight was a function of the FEATURE SET — the wrapper's rows are `jiff` + `time`, so their
665/// presence displaced another entry — and the fixture that pins this refusal as exact text was
666/// therefore unassertable in any build without both, which is what kept a dialect-only build red.
667/// The wrapper's two rows carry [`do_not_recommend`](diagnostic::do_not_recommend) and no other row
668/// does: they were the only entries that could come and go, so suppressing exactly them settles the
669/// text and leaves the list itself — which is a real suggestion to whoever reads it.
670///
671/// The sentence above is what a reader acts on, and it is written rather than inferred from that
672/// list, which names types and not the thing to do. The second note is there because this bound has
673/// a second way to fail that the first does not describe: `Self` may HAVE a row while `{VF}` has no
674/// [`ToDatabaseComparison`](crate::comparison::ToDatabaseComparison) into it. Which message a reader
675/// sees then depends on what they wrote — a failing PROJECTION is reported at that crossing directly
676/// and never reaches this text, while a caller who named this bound in a where-clause gets this one,
677/// and there the note is the only thing distinguishing the two missing pieces.
678#[cfg(feature = "postgres")]
679#[diagnostic::on_unimplemented(
680 message = "a collection of `{Self}` has no Postgres storage strategy",
681 label = "this element type has no `PgCollectionStorage` row",
682 note = "write `impl PgCollectionStorage<{VF}> for {Self}` stating its `Sequence` and \
683 `Set`: the array kinds where sqlx's array type for `{Self}` is the array of the \
684 column its `Carrier` row binds into, the edge-table kinds where it is not or \
685 where there is no array type at all",
686 note = "if `{Self}` already has a row, then `{VF}` is what is missing — an element filter \
687 reaches a strategy through `ToDatabaseComparison<{Self}, sqlx::Postgres>`"
688)]
689pub trait PgCollectionStorage<VF> {
690 /// The comparison a [`ListFilter`] over a sequence of `Self` crosses into on Postgres.
691 type Sequence: ComplexComparison<sqlx::Postgres>;
692 /// The comparison a [`SetFilter`] over a set of `Self` crosses into on Postgres.
693 type Set: ComplexComparison<sqlx::Postgres>;
694}
695
696/// One collection strategy, re-stated over a different element type.
697///
698/// `Self` is a comparison some element's storage row named, `V` is the element the same strategy is
699/// wanted over, and [`Comparison`](Self::Comparison) is that strategy holding `V`. The four rows
700/// this crate ships are the whole of it: each kind re-stated is that kind.
701///
702/// # What needs it
703///
704/// A WRAPPER element stores exactly where the element it wraps does, so its strategy has to be that
705/// element's — and [`Temporal<T>`](super::Temporal) is the one such element this crate ships. What
706/// stands in the way is that a storage row states a COMPARISON rather than a strategy token, and a
707/// comparison names its element: reading `T`'s row gives `Strategy<T, Db>` where the wrapper needs
708/// `Strategy<Temporal<T>, Db>`. An associated type cannot rewrite the element inside one. This is
709/// what does, and it is the same manoeuvre the borrowed halves of the [`PgCollectionStorage`] table
710/// make by hand — `&'a V`'s row is a fresh row over the same strategies rather than a delegation to
711/// `V`'s, for want of exactly this.
712///
713/// # It reads a declaration and makes none
714///
715/// Which row matches is settled by the comparison the element ALREADY declared, so nothing here
716/// asks whether an element can be held in an array. That question is [`PgCollectionStorage`]'s to
717/// refuse: deducing an array row from `T: PgHasArrayType + Type + Encode` admits `Temporal<i8>`
718/// wrongly, since `i8` satisfies all three while this crate's carrier widens it to `smallint` and
719/// sqlx types it `"char"`. A trait that is handed the answer cannot reintroduce that.
720///
721/// # Generic in the dialect, where its consumer is not
722///
723/// Substituting an element is not a per-dialect fact, and all four kinds are already generic in
724/// `Db`. The one caller is Postgres's, because Postgres is the one dialect with two strategies to
725/// pick between — see [`CollectionStorage`].
726///
727/// # Openness
728///
729/// A downstream comparison type joins by writing one row for itself, exactly as
730/// [`Carrier`](super::Carrier) and [`PgCollectionStorage`] are joined, and the orphan rule allows
731/// it because the self type is the downstream's. Without one, a wrapper over an element whose row
732/// names that comparison has no row of its own — which is the honest answer, and the same one an
733/// element with no storage row at all gets.
734pub trait StrategyOver<V> {
735 /// The strategy `Self` is, over element type `V`.
736 type Comparison;
737}
738
739/// The column-stored sequence kind re-stated is that kind: the dialect keeps, and the element MOVES
740/// — both the collection's own operands and the comparison one MEMBER is asked, since a member is
741/// stored in the same form the collection's operands are.
742///
743/// The element comparison re-states through this same trait, which is what keeps the two halves from
744/// disagreeing: `Temporal<T>`'s members bind as `Temporal<T>`, so its element comparison is over the
745/// wrapper too, and a crossing from the DOMAIN element's filter — `ScalarFilter<jiff::Timestamp>` —
746/// reaches it exactly as the collection's own operands do. Keeping `T`'s element comparison instead
747/// compiles and then refuses the crossing, which is how the recursion was found.
748impl<V, C: StrategyOver<W>, Db, W> StrategyOver<W> for SqlListComparison<V, C, Db> {
749 type Comparison = SqlListComparison<W, C::Comparison, Db>;
750}
751
752/// The column-stored set kind, likewise.
753impl<V, C: StrategyOver<W>, Db, W> StrategyOver<W> for SqlSetComparison<V, C, Db> {
754 type Comparison = SqlSetComparison<W, C::Comparison, Db>;
755}
756
757/// No array type, and the JSON alternative cannot be indexed — so an edge table, for both shapes.
758///
759/// The bound is the edge comparisons' lowering: one bind per element through the dialect's carrier
760/// table.
761#[cfg(feature = "sqlite")]
762impl<V: Carrier<sqlx::Sqlite>, VF: ToDatabaseComparison<V, sqlx::Sqlite>> CollectionStorage<V, VF>
763 for sqlx::Sqlite
764{
765 type Sequence = SqlEdgeComparison<V, VF::Comparison, sqlx::Sqlite>;
766 type Set = SqlEdgeSetComparison<V, VF::Comparison, sqlx::Sqlite>;
767}
768
769/// No general array type — its `SET` is a fixed enumerated type of at most 64 members, not one —
770/// and the same JSON ceiling, so the same edge table.
771#[cfg(feature = "mysql")]
772impl<V: Carrier<sqlx::MySql>, VF: ToDatabaseComparison<V, sqlx::MySql>> CollectionStorage<V, VF>
773 for sqlx::MySql
774{
775 type Sequence = SqlEdgeComparison<V, VF::Comparison, sqlx::MySql>;
776 type Set = SqlEdgeSetComparison<V, VF::Comparison, sqlx::MySql>;
777}
778
779/// The type-level map, keyed on the dialect's declared strategy: a [`ListFilter`] crosses into
780/// whichever comparison the database that answers keeps a SEQUENCE in.
781///
782/// It is the crossing where the choice lands rather than anything below it, because
783/// [`ToDatabaseComparison`]'s `Comparison` is already keyed on `Db`. Nothing about
784/// [`ComplexComparison`](crate::ComplexComparison) changes and no other filter kind pays for it.
785///
786/// # The element filter crosses FIRST, and the collection reads its answer
787///
788/// `VF` is the element's filter kind, and the comparison the collection holds is whatever THAT
789/// filter crosses into over the SAME storage type and the same dialect — because a collection's
790/// members are stored as `V`, whether in a column, an array or an edge row. So this row projects
791/// through `VF`'s own crossing and hands the result to the storage map, which is what keeps the
792/// element's vocabulary the element's: a text element brings the substring family and a scalar one
793/// does not, with nothing here choosing between them.
794impl<D, VF, V, Db: CollectionStorage<V, VF>> ToDatabaseComparison<V, Db> for ListFilter<D, VF> {
795 type Comparison = <Db as CollectionStorage<V, VF>>::Sequence;
796}
797
798/// The same map for a set, reading the other half of the same row.
799impl<D, VF, V, Db: CollectionStorage<V, VF>> ToDatabaseComparison<V, Db> for SetFilter<D, VF> {
800 type Comparison = <Db as CollectionStorage<V, VF>>::Set;
801}
802
803/// The narrow collection reads the SEQUENCE half, and that is a storage fact rather than a choice
804/// between two equally good rows.
805///
806/// [`CollectionStorage`]'s two answers name a STRATEGY — a native array, or an edge table — and
807/// nothing about which operators a filter publishes. A quantified column's elements are written in
808/// the order the writer produced them, so a sequence is what is stored; the filter simply declines to
809/// ask about that order. Reading the `Set` half instead would name the strategy an UNORDERED column
810/// takes, and the two differ in the shape of the table on the dialects where they differ at all.
811///
812/// So no third associated type is added, and none is wanted: a row this crate does not ship would
813/// have to answer it, and what it would answer is the sequence strategy it already states.
814impl<D, VF, V, Db: CollectionStorage<V, VF>> ToDatabaseComparison<V, Db>
815 for QuantifiedFilter<D, VF>
816{
817 type Comparison = <Db as CollectionStorage<V, VF>>::Sequence;
818}
819
820/// The narrow crossing into a column-stored sequence comparison — ONE impl for every dialect, where
821/// the wide sequence crossing is three.
822///
823/// # The two arms are the wide kinds' own, called rather than restated
824///
825/// [`cross_element`] and [`cross_count`] are what a collection crossing's `any` and `count` slots go
826/// through, on all six of the existing ones. This crossing calls exactly those two, so *what an
827/// absent operator crosses into* and *how a `usize` cardinality becomes this family's integer* have
828/// one statement each in the whole crate and this kind inherits both. What is left here is
829/// `Self::new()` and two assignments, which is not semantics: the seven element slots stay unset
830/// STRUCTURALLY — nothing writes them — rather than by seven `None`s a reader has to count.
831///
832/// # Dialect-free, where the wide sequence crossing names its database
833///
834/// [`ListCrossingError::JsonOrdering`] is why that one is per-dialect: two dialects cannot answer an
835/// element-wise collection ordering, so each refuses before crossing. This kind has no ordering
836/// operator for any dialect to refuse, which is the same reason [`SqlSetComparison`]'s crossing is
837/// one impl.
838///
839/// # Errors
840///
841/// [`ListCrossingError::Element`] for whatever the ELEMENT filter's own crossing refuses, and
842/// [`ListCrossingError::Cardinality`] for a `count` operand past the integer this family compares a
843/// length as.
844///
845/// The other two variants cannot arrive, and each is closed by something different.
846/// [`Operand`](ListCrossingError::Operand) carries [`Infallible`](core::convert::Infallible) here —
847/// this filter holds no element operand, so there is no converter to refuse one and the variant is
848/// UNINHABITED, which is the compiler stating it rather than this sentence.
849/// [`JsonOrdering`](ListCrossingError::JsonOrdering) is inhabited and unreachable: it names one of
850/// four operators none of which is on this kind.
851///
852/// The error type is the wide kind's all the same, at a different `E`. That is what a caller gets
853/// from the reuse — a cell already absorbing a column-stored sequence's refusal absorbs this one
854/// through the same row, where a fourth crossing-error type whose whole content is two variants of
855/// an existing one would have cost every declaration another `From`.
856impl<D, VF, V, C: TryFromFilter<VF>, Db> TryFromFilter<QuantifiedFilter<D, VF>>
857 for SqlListComparison<V, C, Db>
858{
859 type Error = ListCrossingError<core::convert::Infallible, C::Error>;
860
861 fn try_from_filter(filter: QuantifiedFilter<D, VF>) -> Result<Self, Self::Error> {
862 let mut crossed = Self::new();
863 crossed.any =
864 cross_element(filter.any, C::try_from_filter).map_err(ListCrossingError::Element)?;
865 crossed.count = cross_count(filter.count).map_err(ListCrossingError::Cardinality)?;
866 Ok(crossed)
867 }
868}
869
870/// The sequence slot walk the JSON-storing dialects share: whole-collection equality in the order
871/// the FILTER declares it, then `has_element` — which is the order a client wrote and not the order
872/// the struct stores, where the single-operand slot leads because the kind macro groups slots by
873/// arity.
874///
875/// The four ORDERING slots are absent from it, and that is the single-gate rule rather than an
876/// omission: neither of these dialects can answer them, so neither crossing lets one be set. A
877/// second check here would be a second place for the two to disagree.
878///
879/// Shared by SQLite and MySQL and by nothing else. Postgres stores a collection as a native array
880/// and its lowering binds the ELEMENTS rather than one JSON value, so it neither reads
881/// [`JsonElement`] nor calls this walk.
882// Gated with its only callers, the two JSON impls below.
883#[cfg(any(feature = "sqlite", feature = "mysql"))]
884fn push_json_list_slots<V, C, Db, L>(
885 comparison: &SqlListComparison<V, C, Db>,
886 at: At<'_>,
887 out: &mut SqlConjunction<'_, Db>,
888 leaf: L,
889) where
890 Db: sqlx::Database,
891 V: JsonElement,
892 L: Fn(&mut sqlx::QueryBuilder<Db>, At<'_>, CollectionOp, &str, bool),
893{
894 let mut slot = |values: &Option<Box<[V]>>, negated| {
895 if let Some(elements) = values {
896 let json = json_elements(elements);
897 leaf(out.open(), at, CollectionOp::SequenceEq, &json, negated);
898 }
899 };
900 slot(&comparison.eq, false);
901 slot(&comparison.ne, true);
902 push_json_membership(comparison.has_element.as_ref(), at, out, leaf);
903}
904
905/// The set slot walk the JSON-storing dialects share, in the order the FILTER declares its slots.
906// Gated with its only callers, the two JSON impls below.
907#[cfg(any(feature = "sqlite", feature = "mysql"))]
908fn push_json_set_slots<V, C, Db, L>(
909 comparison: &SqlSetComparison<V, C, Db>,
910 at: At<'_>,
911 out: &mut SqlConjunction<'_, Db>,
912 leaf: L,
913) where
914 Db: sqlx::Database,
915 V: JsonElement,
916 L: Fn(&mut sqlx::QueryBuilder<Db>, At<'_>, CollectionOp, &str, bool),
917{
918 let mut slot = |values: &Option<Box<[V]>>, op, negated| {
919 if let Some(elements) = values {
920 let json = json_elements(elements);
921 leaf(out.open(), at, op, &json, negated);
922 }
923 };
924 slot(&comparison.eq, CollectionOp::SetEq, false);
925 slot(&comparison.ne, CollectionOp::SetEq, true);
926 slot(&comparison.encloses, CollectionOp::Encloses, false);
927 slot(&comparison.enclosed_by, CollectionOp::EnclosedBy, false);
928 slot(&comparison.overlaps, CollectionOp::Overlaps, false);
929 push_json_membership(comparison.has_element.as_ref(), at, out, leaf);
930}
931
932/// The `has_element` slot both walks end with.
933///
934/// Membership IS containment of the singleton, so it needs no operator of its own — and it encodes
935/// through the same writer, which is what keeps its token identical to the one the same value would
936/// carry inside a list operand. Both kinds reach it, because the question is the same one whether
937/// the column's order is meaningful.
938// Gated with its only callers, the two walks above.
939#[cfg(any(feature = "sqlite", feature = "mysql"))]
940fn push_json_membership<V, Db, L>(
941 element: Option<&V>,
942 at: At<'_>,
943 out: &mut SqlConjunction<'_, Db>,
944 leaf: L,
945) where
946 Db: sqlx::Database,
947 V: JsonElement,
948 L: Fn(&mut sqlx::QueryBuilder<Db>, At<'_>, CollectionOp, &str, bool),
949{
950 if let Some(element) = element {
951 let json = json_elements(core::slice::from_ref(element));
952 leaf(out.open(), at, CollectionOp::Encloses, &json, false);
953 }
954}
955
956/// MySQL has a native `JSON` type and the `JSON_CONTAINS` / `JSON_OVERLAPS` functions over it.
957#[cfg(feature = "mysql")]
958mod mysql;
959
960/// Postgres has a native `ARRAY` type, its containment operators (`@>` `<@` `&&`) and an
961/// element-wise `<` — so both lowerings here bind the operand's ELEMENTS as one array and ask the
962/// engine directly. Nothing on this path is JSON.
963///
964/// # The bound that could not be asked for before
965///
966/// `V: PgHasArrayType` is declared by sqlx-postgres and by no other driver: it is the row that names
967/// the array type OID an element lives in, and it is what makes `push_bind(&[V])` type as
968/// `V[]` rather than fail. A single `impl<…, Db> ComplexComparison<Db>` had no way to require it, which
969/// is the whole reason the collection kind lowered through `jsonb` here — an encoding chosen by the
970/// impl shape rather than by anything about Postgres.
971///
972/// An element type with no `PgHasArrayType` row therefore has no ARRAY lowering on this dialect,
973/// and the omission is an unsatisfied bound naming the missing trait. Such a type reaches an edge
974/// table instead — [`PgCollectionStorage`] is where it says so — but naming these kinds for it
975/// directly still does not compile, and [`BeU64`](crate::BeU64) is the case that actually occurs:
976/// this crate's own blob carrier, which binds fine as a SCALAR and which sqlx names no array type
977/// for.
978///
979/// ```compile_fail,E0599
980/// use ingraph::{
981/// At, BeU64, ComplexComparison, FieldName, RecordAddress, SetFilter, TryFromFilter,
982/// comparison::sql::{SqlConjunction, SqlScalarComparison, SqlSetComparison},
983/// };
984///
985/// type Element = SqlScalarComparison<BeU64, sqlx::Postgres>;
986/// let c = SqlSetComparison::<BeU64, Element, sqlx::Postgres>::try_from_filter(
987/// SetFilter::<u64>::new().with_encloses([1u64]),
988/// )
989/// .unwrap();
990/// let mut qb = sqlx::QueryBuilder::<sqlx::Postgres>::default();
991/// const ROW: RecordAddress = RecordAddress::new(FieldName::new("t"), &[FieldName::new("id")]);
992/// let out = SqlConjunction::with_lead(&mut qb, "");
993/// let frame = At::new(&ROW).frame(FieldName::new("t"));
994/// c.apply(frame.at(), out).unwrap();
995/// ```
996///
997/// Its twin, which must COMPILE — stable rustdoc runs a `compile_fail` block just far enough to see
998/// it fail and never checks why, so the pair shares its call shape and one half has to be positive:
999///
1000/// ```
1001/// use ingraph::{
1002/// At, ComplexComparison, FieldName, RecordAddress, SetFilter, TryFromFilter,
1003/// comparison::sql::{SqlConjunction, SqlScalarComparison, SqlSetComparison},
1004/// };
1005///
1006/// type Element = SqlScalarComparison<i64, sqlx::Postgres>;
1007/// let c = SqlSetComparison::<i64, Element, sqlx::Postgres>::try_from_filter(
1008/// SetFilter::<i64>::new().with_encloses([1i64]),
1009/// )
1010/// .unwrap();
1011/// let mut qb = sqlx::QueryBuilder::<sqlx::Postgres>::default();
1012/// const ROW: RecordAddress = RecordAddress::new(FieldName::new("t"), &[FieldName::new("id")]);
1013/// let out = SqlConjunction::with_lead(&mut qb, "");
1014/// let frame = At::new(&ROW).frame(FieldName::new("t"));
1015/// c.apply(frame.at(), out).unwrap();
1016/// assert_eq!(qb.sql(), "\"t\" @> $1");
1017/// ```
1018///
1019/// # `ARRAY` is ordered, which is what lets one column shape carry both kinds
1020///
1021/// A Postgres array keeps its element order, so a sequence's equality is `=` and a set's is mutual
1022/// containment. The JSON dialects make the same split for the same reason, under other spellings.
1023#[cfg(feature = "postgres")]
1024mod postgres;
1025
1026/// SQLite has no array type and no `JSON` type: a collection column is TEXT holding a JSON array,
1027/// and every element question is a `json_each` set expression over it.
1028#[cfg(feature = "sqlite")]
1029mod sqlite;
1030
1031#[cfg(test)]
1032mod tests;