ingraph/comparison/sql/bytes/mod.rs
1//! The bytes comparison: [`SqlBytesComparison`], one concrete lowering per dialect, and the crossing
2//! that stopped having a refusal to own.
3
4use core::marker::PhantomData;
5
6#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
7use core::fmt::Display;
8
9// Gated with their only user, the shared slot walk below — which is itself gated with the
10// per-dialect impls that call it. An import carries the cfg its consumer carries, and the run
11// that catches a mismatch is the one where the family root is on and every dialect is off.
12#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
13use super::{Carrier, SqlConjunction, push_cmp, push_in};
14#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
15use crate::comparison::At;
16use crate::{
17 BytesFilter, FixedBytesFilter, TryMapFilter,
18 comparison::{Backend, ComplexComparison, ToDatabaseComparison, TryFromFilter},
19 graphql::filter::ByteSlots,
20};
21
22comparison_kind! {
23 /// The byte kinds' storage-side twin: ten operator slots, over the type this database stores the
24 /// column as.
25 ///
26 /// # BOTH byte kinds reach it, and it reads no width
27 ///
28 /// [`BytesFilter`] fills all ten and [`FixedBytesFilter`] fills eight, its substring pair being a
29 /// field it does not have. Nothing downstream of the crossing asks which arrived: the SQL a slot
30 /// renders is the same either way, and a slot no filter could set is a slot no walk visits.
31 ///
32 /// This kind carried the WIDTH as a third parameter — `SqlBytesComparison<V, K, Db>` — for one
33 /// reason, and the reason retired with the shape axis: its crossing was an INHERENT method reading
34 /// `K::SUBSTRING`, and an inherent method may only name its own type's parameters. The refusal is
35 /// gone, so the parameter that carried the fact it read is gone with it.
36 ///
37 /// # The dialects do not agree, and the difference is the argument order
38 ///
39 /// A byte-substring match is `instr(col, ?) > 0` on SQLite, `position(? in col) > 0` on Postgres
40 /// and `LOCATE(?, col) > 0` on MySQL — the operand comes SECOND in one and FIRST in the other two,
41 /// which is the kind of difference that renders plausible SQL and matches the wrong rows rather
42 /// than failing. So the lowering is three concrete impls.
43 ///
44 /// Their BOUNDS agree — `V: Carrier<Db>`, since nothing here derives a value from the operand the
45 /// way a `LIKE` pattern does — and the SQL does not, which is why this kind is split where
46 /// `scalar` is not. Both halves of the test have to hold for one impl to be right.
47 SqlBytesComparison {
48 one { eq, ne, gt, gte, lt, lte, contains, not_contains }
49 many { in_, not_in }
50 }
51}
52
53impl<V, Db> SqlBytesComparison<V, Db> {
54 /// Cross a byte filter into this comparison, converting each operand with `f`.
55 ///
56 /// The entry point a DECLARED converter uses (`<db>(into = …)`), and it is a PURE MAP —
57 /// every operator either kind can express has an answer in this family.
58 ///
59 /// # The refusal this used to own, and where it went
60 ///
61 /// `legacy/ingraph` refused a fixed-width substring match while RENDERING, which is what made its
62 /// whole `apply` return a `Result`; this crate moved the refusal to the crossing and read it off
63 /// `K::SUBSTRING`, a monomorphized const on a shape marker. Both arrangements published a schema
64 /// field — `contains` on a `BINARY(32)` column — whose every use was an error.
65 ///
66 /// [`FixedBytesFilter`] does not have the field. So there is no operand to refuse, no const to
67 /// read, and no `BytesCrossingError` to name: a request writing `contains` on a fixed-width column
68 /// is answered by the wire's own unknown-field validation, before any of this crate's code runs.
69 ///
70 /// # The parameter is a BOUND rather than a spelling
71 ///
72 /// `X` is anything that maps its operands into `V` and lands on a byte filter — which is the two
73 /// framework kinds and any MINTED element filter over either, the row `ingraph-codegen`'s element
74 /// door emits. Naming one filter type here is what used to make a minted filter `E0308` at an
75 /// expansion its author cannot edit.
76 ///
77 /// # Errors
78 ///
79 /// Whatever `f` refuses an operand with, and nothing of this crossing's own.
80 // SEALED, deliberately: `ByteSlots` is `pub(crate)`, so a caller in any crate may SATISFY this
81 // bound — with either byte kind, or with a minted filter over one — and no crate may add an
82 // implementor. What a declaring crate extends is `BytesWire` (its own operand's wire face) and
83 // `TryMapFilter` (its minted filter's operand map); the gather between a filter and this family's
84 // comparison is not a seam anything outside answers.
85 #[allow(private_bounds)]
86 pub fn try_from_filter_with<D, E, F, X>(filter: X, f: F) -> Result<Self, E>
87 where
88 X: TryMapFilter<D, V, Mapped: ByteSlots<V>>,
89 F: FnMut(D) -> Result<V, E>,
90 {
91 let stored = filter.try_map_filter(f)?.byte_operands();
92 Ok(Self {
93 eq: stored.eq,
94 ne: stored.ne,
95 gt: stored.gt,
96 gte: stored.gte,
97 lt: stored.lt,
98 lte: stored.lte,
99 contains: stored.contains,
100 not_contains: stored.not_contains,
101 in_: stored.in_,
102 not_in: stored.not_in,
103 db: PhantomData,
104 })
105 }
106}
107
108/// The lowering promise is stated as the COMPARISON's own bound, for the reason
109/// [`SqlTextComparison`](super::SqlTextComparison)'s row gives: this kind lowers through three
110/// concrete per-dialect impls, so there is no generic bound list to restate — only the fact that
111/// the dialect in hand has one of them.
112impl<D, V, I, Db> ToDatabaseComparison<V, Db> for BytesFilter<D, I>
113where
114 Db: sqlx::Database + Backend,
115 SqlBytesComparison<V, Db>: ComplexComparison<Db>,
116{
117 type Comparison = SqlBytesComparison<V, Db>;
118}
119
120/// The fixed kind's row, and it lands on the SAME comparison — a storage side reads no width.
121impl<D, V, const N: usize, I, Db> ToDatabaseComparison<V, Db> for FixedBytesFilter<D, N, I>
122where
123 Db: sqlx::Database + Backend,
124 SqlBytesComparison<V, Db>: ComplexComparison<Db>,
125{
126 type Comparison = SqlBytesComparison<V, Db>;
127}
128
129/// The crossing with no declared converter: the storage type's own [`TryFrom`].
130///
131/// Its error is the CONVERTER's, like every other kind's in this family. It was
132/// `BytesCrossingError<V::Error>` while a fixed column's substring refusal lived here — an error
133/// with a second inhabited variant even at [`Infallible`](core::convert::Infallible), which meant
134/// the identity crossing over a blob genuinely could not fail and the type would not say so. It says
135/// so now, for both kinds, because there is nothing left to refuse.
136impl<D, V, I, Db> TryFromFilter<BytesFilter<D, I>> for SqlBytesComparison<V, Db>
137where
138 V: TryFrom<D>,
139{
140 type Error = V::Error;
141
142 fn try_from_filter(filter: BytesFilter<D, I>) -> Result<Self, Self::Error> {
143 Self::try_from_filter_with(filter, V::try_from)
144 }
145}
146
147/// The fixed kind's identity crossing — the same two lines, over eight slots.
148impl<D, V, const N: usize, I, Db> TryFromFilter<FixedBytesFilter<D, N, I>>
149 for SqlBytesComparison<V, Db>
150where
151 V: TryFrom<D>,
152{
153 type Error = V::Error;
154
155 fn try_from_filter(filter: FixedBytesFilter<D, N, I>) -> Result<Self, Self::Error> {
156 Self::try_from_filter_with(filter, V::try_from)
157 }
158}
159
160/// The bytes kind answers, and it is the SAFEST family in the crate to collapse: a byte `eq` is
161/// BITWISE on every dialect here — no collation, no case fold, nothing a schema can configure — so
162/// the one assumption the collapse makes about the two columns it moves a predicate between is the
163/// assumption a byte column cannot get wrong. [`SqlTextComparison`](super::SqlTextComparison)'s row
164/// records that same question as live for MySQL's default collations; there is no version of it
165/// here.
166///
167/// The absence this row fills was a LEGACY-WIRE ARTIFACT rather than a judgement. `legacy/ingraph`
168/// answered the question for text and not for bytes, which had the order backwards, and the omission
169/// travelled across with the wire it was written on. A byte-keyed declaration is a full
170/// relation-filter citizen with this row, where before it was refused at the position that wanted the
171/// collapse.
172///
173/// It reads no WIDTH, and there is nothing for one to decide: both kinds hold `eq` and `in_`, and
174/// the operators the width DOES decide — the substring pair — are not a field a fixed-width filter
175/// has. Either way the count is what declines.
176impl<V, Db: crate::comparison::Backend> crate::comparison::ReferentialComparison<Db>
177 for SqlBytesComparison<V, Db>
178{
179 #[inline]
180 fn is_referential(&self) -> bool {
181 Self::conjuncts(self) == 1 && (self.eq.is_some() || self.in_.is_some())
182 }
183}
184
185/// The slot walk the three concrete impls share: the six comparison operators, the byte match
186/// through `leaf` with its negated twin, then the two membership lists — in the order the struct
187/// declares them.
188///
189/// The walk does NOT ask which byte kind filled the comparison, and it has nothing to ask: a
190/// substring operand on a fixed-width column cannot reach a slot here, the filter having no field to
191/// set one from. What used to be a refusal the crossing owned and this walk deliberately did not
192/// re-check is now an absence neither of them has to know about.
193///
194/// No affix family and no case fold: a byte string has no characters to take a prefix of and no case
195/// to ignore, so the byte match is one operator with a negated twin — which is also why `leaf` takes
196/// four arguments where the text kind's takes six.
197// Gated with its only callers, the per-dialect impls below: with the family root on and no
198// dialect there is no lowering, so there is no walk to share.
199#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
200fn push_slots<V, Db, L>(
201 comparison: &SqlBytesComparison<V, Db>,
202 at: At<'_>,
203 out: &mut SqlConjunction<'_, Db>,
204 leaf: L,
205) where
206 Db: sqlx::Database + Backend<Buffer: Display>,
207 V: Carrier<Db>,
208 L: Fn(&mut sqlx::QueryBuilder<Db>, At<'_>, &V, bool),
209{
210 if let Some(value) = &comparison.eq {
211 push_cmp(out.open(), at, " = ", value, false);
212 }
213 if let Some(value) = &comparison.ne {
214 push_cmp(out.open(), at, " = ", value, true);
215 }
216 if let Some(value) = &comparison.gt {
217 push_cmp(out.open(), at, " > ", value, false);
218 }
219 if let Some(value) = &comparison.gte {
220 push_cmp(out.open(), at, " >= ", value, false);
221 }
222 if let Some(value) = &comparison.lt {
223 push_cmp(out.open(), at, " < ", value, false);
224 }
225 if let Some(value) = &comparison.lte {
226 push_cmp(out.open(), at, " <= ", value, false);
227 }
228 if let Some(value) = &comparison.contains {
229 leaf(out.open(), at, value, false);
230 }
231 if let Some(value) = &comparison.not_contains {
232 leaf(out.open(), at, value, true);
233 }
234 if let Some(values) = &comparison.in_ {
235 push_in(out.open(), at, values, false);
236 }
237 if let Some(values) = &comparison.not_in {
238 push_in(out.open(), at, values, true);
239 }
240}
241
242/// A binary column matches with `LOCATE`, which is byte-exact and — like Postgres's `position` and
243/// unlike SQLite's `instr` — takes the operand first.
244#[cfg(feature = "mysql")]
245mod mysql;
246
247/// `BYTEA` has only `position` — byte-substring, case-blind, and with the operand FIRST, which is
248/// the reverse of `instr`'s argument order.
249#[cfg(feature = "postgres")]
250mod postgres;
251
252/// SQLite's `instr` is blob-aware, so the byte form and the text form are the same function — and
253/// the operand comes SECOND.
254#[cfg(feature = "sqlite")]
255mod sqlite;
256
257#[cfg(test)]
258mod tests;