ingraph/comparison/sql/flags.rs
1//! The flags comparison: [`SqlFlagsComparison`].
2
3use core::{fmt::Display, marker::PhantomData};
4
5use super::{
6 At, Carrier, SqlConjunction, not_wrapped, push_cmp, push_column, push_in, push_subject_cmp,
7};
8use crate::{
9 FlagsFilter, TryMapFilter,
10 comparison::{Backend, ComplexComparison, ToDatabaseComparison, TryFromFilter},
11};
12
13comparison_kind! {
14 /// A [`FlagsFilter`]'s storage-side twin: the whole value compared or enumerated, and three
15 /// questions about its BITS, over the integer this database stores the column as.
16 ///
17 /// SEVEN operators and no sugar. `isEmpty`, `isAll` and the per-flag boolean fan are folded into
18 /// four of these at the wire, so what reaches here is the same seven whatever a document wrote —
19 /// which is what makes this the single authority on what any flags question MEANS in SQL.
20 ///
21 /// No ordering, for the reason the enum kind has none: a bit set has no magnitude, and the order
22 /// the underlying integer imposes is an artefact of which bit a declaration numbered first.
23 SqlFlagsComparison {
24 one { eq, ne, has_all, has_any, has_none }
25 many { in_, not_in }
26 }
27}
28
29impl<V, Db> SqlFlagsComparison<V, Db> {
30 /// Cross a [`FlagsFilter`] into this comparison, converting each operand with `f`.
31 ///
32 /// The entry point a DECLARED converter uses. A declared flags type usually needs none — its
33 /// emitted [`Carrier`] binds the bit pattern directly — so the identity crossing below is the
34 /// common case and this is the escape for a column whose stored width is somebody's own.
35 pub fn try_from_filter_with<D, E, F, X>(filter: X, f: F) -> Result<Self, E>
36 where
37 X: TryMapFilter<D, V, Mapped = FlagsFilter<V>>,
38 F: FnMut(D) -> Result<V, E>,
39 {
40 let stored = filter.try_map_filter(f)?;
41 Ok(Self {
42 eq: stored.eq,
43 ne: stored.ne,
44 in_: stored.in_,
45 not_in: stored.not_in,
46 has_all: stored.has_all,
47 has_any: stored.has_any,
48 has_none: stored.has_none,
49 db: PhantomData,
50 })
51 }
52}
53
54/// The bounds are the LOWERING's, restated — see
55/// [`SqlEnumComparison`](super::SqlEnumComparison)'s row.
56impl<D, V, Db> ToDatabaseComparison<V, Db> for FlagsFilter<D>
57where
58 Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
59 V: Carrier<Db>,
60{
61 type Comparison = SqlFlagsComparison<V, Db>;
62}
63
64/// The crossing with no declared converter — see
65/// [`SqlScalarComparison`](super::SqlScalarComparison)'s for what the identity case buys.
66impl<D, V, Db> TryFromFilter<FlagsFilter<D>> for SqlFlagsComparison<V, Db>
67where
68 V: TryFrom<D>,
69{
70 type Error = V::Error;
71
72 fn try_from_filter(filter: FlagsFilter<D>) -> Result<Self, Self::Error> {
73 Self::try_from_filter_with(filter, V::try_from)
74 }
75}
76
77/// The flags kind answers, and answers NARROWLY: only a lone `eq` or `in` names one stored value.
78///
79/// A mask word does not, and that is a fact about the question rather than about the operand: a
80/// column satisfying `(key & m) = m` is a SET of stored keys, so the rewrite
81/// `fk IN (SELECT key FROM child WHERE …)` → `fk = v` has no `v` to be. Every mask slot is therefore
82/// checked empty, where the enum kind — which has none — checks only the negated pair.
83impl<V, Db: crate::comparison::Backend> crate::comparison::ReferentialComparison<Db>
84 for SqlFlagsComparison<V, Db>
85{
86 #[inline]
87 fn is_referential(&self) -> bool {
88 Self::conjuncts(self) == 1 && (self.eq.is_some() || self.in_.is_some())
89 }
90}
91
92/// `(col & ?)` — the SUBJECT the three mask words compare, and the one place this family spells a
93/// bitwise operator.
94///
95/// ONE spelling for three dialects, and that is measured rather than assumed: `&` is the bitwise AND
96/// of SQLite, PostgreSQL and MySQL alike, over every integer type this framework's carrier table
97/// binds a flags column at. What differs per dialect is the column's WIDTH — Postgres has no
98/// unsigned types, so a `u32` set is stored and bound as `i8`-wide `BIGINT` — and that is answered
99/// one layer down, at the [`Carrier`] row, exactly where a Postgres `ENUM` cast is answered for the
100/// vocabulary kind.
101///
102/// The parenthesis is not decoration. SQL's operator precedence puts `&` below `=` in MySQL and
103/// above it in PostgreSQL, so `col & ? = ?` is two different questions in two dialects and this is
104/// the one question in all three.
105fn push_masked<Db, V>(qb: &mut sqlx::QueryBuilder<Db>, at: At<'_>, mask: &V)
106where
107 Db: sqlx::Database + Backend<Buffer: Display>,
108 V: Carrier<Db>,
109{
110 qb.push("(");
111 push_column(qb, at);
112 qb.push(" & ");
113 mask.push_bind(qb);
114 qb.push(")");
115}
116
117/// `(col & ?) = 0`, wrapped in this family's ONE spelling of negation where the question is
118/// `hasAny`.
119///
120/// The zero is a LITERAL and not a bind, and it is the only literal this family writes: it is a
121/// constant of the language rather than an operand, so there is nothing for a bind to carry and no
122/// value of `V` this function would have to mint one from.
123///
124/// Both vacuous cases fall out rather than being special-cased, and they agree with `bitflags`' own
125/// reading: `hasNone(∅)` is `(col & 0) = 0`, true of every row, and `hasAny(∅)` is its negation,
126/// true of none — which is `contains(∅)` and `intersects(∅)` exactly.
127fn push_clear<Db, V>(qb: &mut sqlx::QueryBuilder<Db>, at: At<'_>, mask: &V, negated: bool)
128where
129 Db: sqlx::Database + Backend<Buffer: Display>,
130 V: Carrier<Db>,
131{
132 not_wrapped(qb, negated, |qb| {
133 push_masked(qb, at, mask);
134 qb.push(" = 0");
135 });
136}
137
138/// ONE impl for every dialect — [`SqlEnumComparison`](super::SqlEnumComparison)'s finding over a
139/// larger operator set, and true for the same two reasons.
140///
141/// - **The SQL is identical.** Equality, membership and `&` read the same in SQLite, PostgreSQL and
142/// MySQL, and the one place they could have diverged — operator precedence around `&` — is closed
143/// by [`push_masked`]'s parenthesis rather than by three impls.
144/// - **The bounds are identical, and admit the same types.** `V: Carrier<Db>`, and nothing else.
145///
146/// The three mask words are lowered as ONE shape each and never as a rewrite of another: `hasAll` is
147/// `(col & m) = m`, `hasAny` is `NOT ( (col & m) = 0 )` and `hasNone` is `(col & m) = 0`. `hasAll`
148/// is not spelled as a pair of the other two, and the reason is the vacuous case — at `m = ∅` the
149/// three answer TRUE, FALSE and TRUE, which no single rewrite reproduces.
150impl<V, Db> ComplexComparison<Db> for SqlFlagsComparison<V, Db>
151where
152 Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
153 V: Carrier<Db>,
154{
155 #[inline]
156 fn conjuncts(&self) -> usize {
157 Self::conjuncts(self)
158 }
159
160 fn apply<'q>(
161 &'q self,
162 at: At<'_>,
163 mut builder: Db::Builder<'q>,
164 ) -> Result<Db::Builder<'q>, Db::Error> {
165 if let Some(value) = &self.eq {
166 push_cmp(builder.open(), at, " = ", value, false);
167 }
168 if let Some(value) = &self.ne {
169 push_cmp(builder.open(), at, " = ", value, true);
170 }
171 if let Some(values) = &self.in_ {
172 push_in(builder.open(), at, values, false);
173 }
174 if let Some(values) = &self.not_in {
175 push_in(builder.open(), at, values, true);
176 }
177 if let Some(mask) = &self.has_all {
178 push_subject_cmp(
179 builder.open(),
180 |qb| push_masked(qb, at, mask),
181 " = ",
182 mask,
183 false,
184 );
185 }
186 if let Some(mask) = &self.has_any {
187 push_clear(builder.open(), at, mask, true);
188 }
189 if let Some(mask) = &self.has_none {
190 push_clear(builder.open(), at, mask, false);
191 }
192 Ok(builder)
193 }
194}
195
196#[cfg(test)]
197mod tests;