Skip to main content

sql_builder/backend/
dialect.rs

1//! The SQL a backend writes beyond its statements.
2//!
3//! TideORM's query builder renders JSON and array predicates, JSON column
4//! updates, window defaults, parameter markers and literals as text, and asks
5//! the backend's [`SqlDialect`] for each piece, so every difference between the
6//! dialects lives in the backend that speaks it. A piece with values comes
7//! back as a [`BoundSql`], its values standing where they are bound.
8
9use super::bound_sql::bound;
10pub use super::bound_sql::{BoundPart, BoundPiece, BoundSql};
11use crate::{Expr, ExprTrait, Quote, Value, error::RenderError};
12
13pub(crate) use super::json_path::{JsonPathStep, json_path_text, parse_json_path};
14
15/// A predicate that holds for no row.
16///
17/// A condition that cannot hold (an overlap with no values, a search with no
18/// word) renders as it rather than leaving the WHERE clause.
19pub const MATCH_NOTHING: &str = "0 = 1";
20
21/// Lists longer than this are long. Every backend caps a statement at 32,766
22/// or 65,535 bind parameters, so [`SqlDialect::in_list`] writes a long list
23/// without binding each value.
24pub const LONG_LIST: usize = 1_000;
25
26/// The escape character of every `LIKE` pattern [`SqlDialect::literal_match`]
27/// writes.
28///
29/// Deliberately **not** a backslash: SQLite string literals do not process it
30/// (so `'\\'` is a two-character escape argument SQLite rejects), and MySQL's
31/// handling flips with `NO_BACKSLASH_ESCAPES`. `!` is a single character in
32/// all three dialects and is not special inside a `LIKE` pattern.
33const LIKE_ESCAPE: char = '!';
34
35/// Which way a JSON containment test reads, as PostgreSQL's `@>` and `<@` do.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum JsonContainment {
38    /// The column holds every key and element of the value.
39    Contains,
40    /// The value holds every key and element of the column.
41    ContainedBy,
42}
43
44/// What a JSON existence predicate looks for.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum JsonExistence {
47    /// A top-level member, named by a plain key.
48    Key,
49    /// A JSON path such as `$.user.name`.
50    Path,
51}
52
53/// An array predicate, read as PostgreSQL's array operators read it.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum ArrayOperator {
56    /// The column holds every listed value (`@>`).
57    Contains,
58    /// The list holds every element of the column (`<@`).
59    ContainedBy,
60    /// The column holds some listed value (`&&`).
61    Overlaps,
62}
63
64/// The SQL dialect of a backend, for SQL written as text.
65///
66/// `column` arguments are SQL already quoted. JSON is compared as PostgreSQL
67/// compares `jsonb` on every backend: as documents, not text, so key order
68/// and spacing do not count and `1` equals `1.0`.
69pub trait SqlDialect: Send + Sync {
70    /// The quotes around an identifier.
71    fn identifier_quote(&self) -> Quote;
72
73    /// Append `name` to `out` as a quoted identifier, doubling any quote inside it.
74    fn push_identifier(&self, out: &mut String, name: &str) {
75        super::write_identifier(out, self.identifier_quote(), name);
76    }
77
78    /// The marker of the `index`-th (1-based) bound value.
79    fn marker(&self, index: usize) -> String;
80
81    /// Whether markers are numbered (`$1`).
82    ///
83    /// A fragment with numbered markers is renumbered when it is spliced
84    /// behind other values; one with positional `?` markers is not.
85    fn numbered_markers(&self) -> bool;
86
87    /// SQL written with this dialect's markers, such as a raw fragment, as an
88    /// expression binding `values` to its markers in order. The dialect's own
89    /// pieces need no reading: a [`BoundSql`] is an expression as it is.
90    ///
91    /// A marker without a value, or a value without a marker, is an error.
92    fn expression(&self, sql: String, values: Vec<Value>) -> Result<Expr, RenderError>;
93
94    /// `sql` with `values` written in place of its markers, for display.
95    fn inline_values(&self, sql: &str, values: &[Value]) -> Result<String, RenderError>;
96
97    /// `text` as a quoted string literal, escaped as [`inline_values`]
98    /// writes one, for SQL that cannot bind it: DDL, or a constant an index
99    /// expression must match.
100    ///
101    /// [`inline_values`]: Self::inline_values
102    fn string_literal(&self, text: &str) -> String;
103
104    /// Whether an array column is the database's own array type.
105    ///
106    /// Its elements are then bound as values of the element type; elsewhere an
107    /// array is a JSON document and its elements are JSON values
108    /// (`Value::Json`).
109    fn native_arrays(&self) -> bool {
110        false
111    }
112
113    /// `column` holds the JSON document `value`, or does not when `negated`.
114    ///
115    /// A NULL column matches neither the test nor its negation.
116    fn json_equals(&self, column: &str, value: &serde_json::Value, negated: bool) -> BoundSql;
117
118    /// A JSON containment test of `column` against `value`.
119    fn json_containment(
120        &self,
121        column: &str,
122        value: &serde_json::Value,
123        containment: JsonContainment,
124    ) -> BoundSql;
125
126    /// A JSON key- or path-existence test, or its negation.
127    ///
128    /// Every backend reads a path strictly: a member step finds a member of an
129    /// object only, never of the objects inside an array, and an index step an
130    /// element of an array only. A key is the one-member path that names it,
131    /// so it exists only in an object. A member holding JSON `null` exists,
132    /// and a NULL column is unknown, so that the negation does not match it
133    /// either. A path with steps the backend cannot express is refused:
134    /// matching nothing, both the test and its negation, would hide the
135    /// mistake.
136    fn json_exists(
137        &self,
138        column: &str,
139        existence: JsonExistence,
140        target: &str,
141        negated: bool,
142    ) -> Result<BoundSql, RenderError>;
143
144    /// An array predicate on `column` against the list `elements`.
145    ///
146    /// `elements` are bound as [`native_arrays`](Self::native_arrays) says,
147    /// and `null_allowed` says whether a contained-by list of native elements
148    /// also held a NULL, which `elements` leaves out.
149    fn array_predicate(
150        &self,
151        column: &str,
152        operator: ArrayOperator,
153        elements: Vec<Value>,
154        null_allowed: bool,
155    ) -> BoundSql;
156
157    /// `column` with `element` appended; a NULL column starts a new array.
158    fn array_append(&self, column: &str, element: Value) -> BoundSql;
159
160    /// `column` without the elements equal to `element`.
161    ///
162    /// `source` is the column qualified with its table, for a subquery that
163    /// reads its elements.
164    fn array_remove(&self, column: &str, source: &str, element: Value) -> BoundSql;
165
166    /// `column` with the member or element at `path` set to `value`.
167    ///
168    /// A path whose parent is missing (read strictly, as
169    /// [`json_exists`](Self::json_exists) reads a path), or is not the object
170    /// its member step needs or the array its index step needs, leaves the
171    /// document as it is, and an index past an array's end appends the value.
172    fn json_set(&self, column: &str, path: &[JsonPathStep], value: &serde_json::Value) -> BoundSql;
173
174    /// `LAG` or `LEAD` (`function`) with a default, over the window `over`.
175    fn window_default(
176        &self,
177        function: &str,
178        column: &str,
179        offset: &str,
180        default: &str,
181        over: &str,
182    ) -> String {
183        format!("{function}({column}, {offset}, {default}) OVER ({over})")
184    }
185
186    /// The limit an offset alone takes, where the dialect has no bare `OFFSET`.
187    fn open_limit(&self) -> Option<&'static str> {
188        None
189    }
190
191    /// Whether an `IN (..)` subquery may carry a `LIMIT`.
192    fn limit_in_subquery(&self) -> bool {
193        true
194    }
195
196    /// Whether a window frame may count `GROUPS`.
197    fn groups_frames(&self) -> bool {
198        true
199    }
200
201    /// Whether an `UPDATE` takes `ORDER BY` and `LIMIT` itself. Where it does
202    /// not, a capped update is scoped through a primary-key subquery; the
203    /// builder renders an [`UpdateStatement`](crate::UpdateStatement)'s limit
204    /// as it is told.
205    fn update_limit(&self) -> bool {
206        false
207    }
208
209    /// `column` as a value that compares byte for byte, whatever its
210    /// collation, so two spellings a case- or accent-insensitive collation
211    /// matches stay apart.
212    fn exact_key(&self, column: &str) -> String;
213
214    /// A query's ` LIMIT n OFFSET ?`.
215    ///
216    /// The limit is written into the SQL, where SQLite 3.50+ would recompile a
217    /// statement with a bound LIMIT on every run, and the offset is bound, as a
218    /// `u64` like a select's, so paging reuses one statement.
219    fn limit_offset(&self, limit: Option<u64>, offset: Option<u64>) -> BoundSql {
220        let mut bound = match (limit, offset) {
221            (Some(limit), _) => BoundSql::sql(format!(" LIMIT {limit}")),
222            (None, Some(_)) => match self.open_limit() {
223                Some(open) => BoundSql::sql(format!(" LIMIT {open}")),
224                None => BoundSql::default(),
225            },
226            (None, None) => BoundSql::default(),
227        };
228        if let Some(offset) = offset {
229            bound.push(" OFFSET ").push(Value::from(offset));
230        }
231        bound
232    }
233
234    /// A test that `column` holds the text `literal`, preceded by anything
235    /// when `leading` and followed by anything when `trailing`: a `LIKE`
236    /// pattern with the literal's `%`, `_` and escape character escaped.
237    /// Refused when the backend cannot test `literal` as it is.
238    fn literal_match(
239        &self,
240        column: &str,
241        literal: &str,
242        leading: bool,
243        trailing: bool,
244    ) -> Result<BoundSql, RenderError> {
245        let mut pattern = String::with_capacity(literal.len() + 2);
246        if leading {
247            pattern.push('%');
248        }
249        for character in literal.chars() {
250            if matches!(character, LIKE_ESCAPE | '%' | '_') {
251                pattern.push(LIKE_ESCAPE);
252            }
253            pattern.push(character);
254        }
255        if trailing {
256            pattern.push('%');
257        }
258        Ok(bound!(
259            format!("{column} LIKE "),
260            Value::String(Some(pattern)),
261            format!(" ESCAPE '{LIKE_ESCAPE}'")
262        ))
263    }
264
265    /// `column IN values`, or `NOT IN` when `negated`. A long all-integer
266    /// list is written as literals.
267    fn in_list(&self, column: Expr, values: Vec<Value>, negated: bool) -> Expr {
268        in_list(column, values, negated)
269    }
270}
271
272/// `column IN values` (`NOT IN` when `negated`), a [`LONG_LIST`] of integers
273/// written as literals: integers carry nothing but digits and a sign.
274pub(crate) fn in_list(column: Expr, values: Vec<Value>, negated: bool) -> Expr {
275    let literals = values.len() > LONG_LIST
276        && values.iter().all(|value| {
277            matches!(
278                value,
279                Value::TinyInt(Some(_))
280                    | Value::SmallInt(Some(_))
281                    | Value::Int(Some(_))
282                    | Value::BigInt(Some(_))
283                    | Value::TinyUnsigned(Some(_))
284                    | Value::SmallUnsigned(Some(_))
285                    | Value::Unsigned(Some(_))
286                    | Value::BigUnsigned(Some(_))
287            )
288        });
289    let list = values.into_iter().map(|value| {
290        if literals {
291            Expr::Constant(value)
292        } else {
293            Expr::Value(value)
294        }
295    });
296    if negated {
297        column.is_not_in(list)
298    } else {
299        column.is_in(list)
300    }
301}
302
303/// The six [`SqlDialect`] methods a builder answers itself.
304macro_rules! builder_dialect {
305    ($builder:expr) => {
306        fn identifier_quote(&self) -> $crate::Quote {
307            $crate::QuotedBuilder::quote(&$builder)
308        }
309
310        fn marker(&self, index: usize) -> String {
311            match $crate::QueryBuilder::placeholder(&$builder) {
312                (marker, true) => format!("{marker}{index}"),
313                (marker, false) => marker.to_string(),
314            }
315        }
316
317        fn numbered_markers(&self) -> bool {
318            $crate::QueryBuilder::placeholder(&$builder).1
319        }
320
321        fn expression(
322            &self,
323            sql: String,
324            values: Vec<$crate::Value>,
325        ) -> Result<$crate::Expr, $crate::error::RenderError> {
326            $crate::Expr::cust_with_values(sql, values, &$builder)
327        }
328
329        fn inline_values(
330            &self,
331            sql: &str,
332            values: &[$crate::Value],
333        ) -> Result<String, $crate::error::RenderError> {
334            $crate::inject_parameters(sql, values, &$builder)
335        }
336
337        fn string_literal(&self, text: &str) -> String {
338            let mut literal = String::with_capacity(text.len() + 2);
339            $crate::QueryBuilder::write_string_quoted(&$builder, text, &mut literal);
340            literal
341        }
342    };
343}
344pub(crate) use builder_dialect;
345
346/// `test`, unknown for a NULL column, which matches neither a JSON test nor
347/// its negation.
348pub(crate) fn unknown_when_null(column: &str, test: BoundSql) -> BoundSql {
349    bound!(
350        format!("CASE WHEN {column} IS NOT NULL THEN "),
351        test,
352        " END"
353    )
354}
355
356/// `sql`, or its negation when `negated`.
357pub(crate) fn negated(sql: BoundSql, negated: bool) -> BoundSql {
358    if negated {
359        bound!("NOT (", sql, ")")
360    } else {
361        sql
362    }
363}
364
365/// A JSON value bound as its JSON text, for backends that parse it server-side.
366pub(crate) fn json_text(value: &serde_json::Value) -> Value {
367    Value::String(Some(value.to_string()))
368}
369
370/// The JSON document a JSON-array element binds: a JSON value as itself, SQL
371/// NULL as `null`, and anything else as its JSON reading.
372pub(crate) fn document(value: &Value) -> serde_json::Value {
373    crate::value_to_json_value(value).unwrap_or(serde_json::Value::Null)
374}
375
376/// The steps a JSON existence test follows: a key's one member, or a path's,
377/// refused when it is not a path `backend` can read.
378pub(crate) fn existence_steps(
379    existence: JsonExistence,
380    target: &str,
381    backend: &str,
382) -> Result<Vec<JsonPathStep>, RenderError> {
383    match existence {
384        JsonExistence::Key => Ok(vec![JsonPathStep::Member(target.to_string())]),
385        JsonExistence::Path => parse_json_path(target).ok_or_else(|| {
386            RenderError::Unsupported(format!(
387                "'{target}' is not a JSON path {backend} can test; write `$` followed by \
388                 `.key`, `.\"quoted key\"` or `[index]` steps"
389            ))
390        }),
391    }
392}
393
394/// Every one of the element `checks` holds: what containment of a list
395/// tests. A list of no elements is contained by every non-NULL array.
396pub(crate) fn all_elements(column: &str, checks: Vec<BoundSql>) -> BoundSql {
397    joined(checks, " AND ", &format!("{column} IS NOT NULL"))
398}
399
400/// One of the element `checks` holds: what an overlap with a list tests.
401/// Nothing overlaps a list of no elements.
402pub(crate) fn any_element(checks: Vec<BoundSql>) -> BoundSql {
403    joined(checks, " OR ", MATCH_NOTHING)
404}
405
406/// `checks` joined by `combine`, parenthesized; `empty` when there are none.
407pub(crate) fn joined(checks: Vec<BoundSql>, combine: &str, empty: &str) -> BoundSql {
408    if checks.is_empty() {
409        return BoundSql::sql(empty);
410    }
411    bound!("(", BoundSql::join(checks, combine), ")")
412}
413
414/// "Every element of `column` is in the list" over `source`, a table of its
415/// elements, of which `offending` selects those the list does not hold
416/// (`None`: every element offends).
417///
418/// A NULL column has no elements, so a bare `NOT EXISTS` is TRUE for it —
419/// where `NULL <@ ARRAY[..]` is NULL and matches nothing. The explicit
420/// `IS NOT NULL` restores that. Without it a NULL array column silently
421/// matches, which widens a SELECT and, on a mutation, the set of rows
422/// written or deleted.
423pub(crate) fn array_contained_by(
424    column: &str,
425    source: &str,
426    offending: Option<BoundSql>,
427) -> BoundSql {
428    let rows = format!("({column} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM {source}");
429    match offending {
430        None => BoundSql::sql(format!("{rows}))")),
431        Some(offending) => bound!(format!("{rows} WHERE "), offending, "))"),
432    }
433}
434
435#[cfg(test)]
436#[path = "../../tests/unit/in_list_tests.rs"]
437mod tests;