Skip to main content

sql_builder/backend/postgres/
dialect.rs

1//! PostgreSQL's dialect: `jsonb` operators, native arrays and numbered markers.
2//!
3//! Array predicates test each value with `value = ANY(column)` rather than
4//! against an `ARRAY[..]` of them, which lets PostgreSQL infer each
5//! parameter's type from the column's element type.
6
7use super::PostgresQueryBuilder;
8use crate::backend::bound_sql::bound;
9use crate::backend::dialect::{
10    ArrayOperator, BoundSql, JsonContainment, JsonExistence, JsonPathStep, LONG_LIST, SqlDialect,
11    all_elements, any_element, array_contained_by, builder_dialect, in_list, json_path_text,
12    json_text, negated, parse_json_path, unknown_when_null,
13};
14use crate::extension::postgres::PgFunc;
15use crate::{ArrayType, Expr, ExprTrait, Value, error::RenderError};
16
17/// The alias of the `unnest(..)` derived table in the contained-by test,
18/// together with the name of its single column.
19const ARRAY_ELEMENT: &str = "tideorm_array_element";
20
21impl SqlDialect for PostgresQueryBuilder {
22    builder_dialect!(PostgresQueryBuilder);
23
24    fn native_arrays(&self) -> bool {
25        true
26    }
27
28    fn exact_key(&self, column: &str) -> String {
29        format!("CAST({column} AS TEXT) COLLATE \"C\"")
30    }
31
32    /// A long list of one type is one array parameter, so any length fits in
33    /// a statement and every length shares one prepared statement.
34    ///
35    /// A decimal is cast to `NUMERIC`: CockroachDB reads each value of a list
36    /// as the column's type, so against an integer column it would round
37    /// `5.4` to `5`, or fail past `i64::MAX`, where PostgreSQL compares
38    /// decimals.
39    fn in_list(&self, column: Expr, values: Vec<Value>, negated: bool) -> Expr {
40        if values.len() > LONG_LIST
41            && let Some(array_type) = shared_array_type(&values)
42        {
43            let decimals = array_type == ArrayType::Decimal;
44            let mut array = Expr::val(Value::Array(array_type, Some(Box::new(values))));
45            if decimals {
46                array = array.cast_as("NUMERIC[]");
47            }
48            return if negated {
49                column.ne(PgFunc::all(array))
50            } else {
51                column.eq(PgFunc::any(array))
52            };
53        }
54        if values
55            .iter()
56            .any(|value| matches!(value, Value::Decimal(Some(_))))
57        {
58            let list = values.into_iter().map(|value| match value {
59                Value::Decimal(Some(_)) => Expr::val(value).cast_as("NUMERIC"),
60                value => Expr::val(value),
61            });
62            return if negated {
63                column.is_not_in(list)
64            } else {
65                column.is_in(list)
66            };
67        }
68        in_list(column, values, negated)
69    }
70
71    /// The `json` type has no `=` at all, so the column is read as `jsonb`.
72    fn json_equals(&self, column: &str, value: &serde_json::Value, negated: bool) -> BoundSql {
73        let operator = if negated { " <> " } else { " = " };
74        bound!(jsonb(column), operator, Value::from(value.clone()))
75    }
76
77    fn json_containment(
78        &self,
79        column: &str,
80        value: &serde_json::Value,
81        containment: JsonContainment,
82    ) -> BoundSql {
83        let operator = match containment {
84            JsonContainment::Contains => " @> ",
85            JsonContainment::ContainedBy => " <@ ",
86        };
87        bound!(jsonb(column), operator, Value::from(value.clone()))
88    }
89
90    /// A key is tested with `?`, which also finds a string element of an
91    /// array, so the document must be an object first; a path with
92    /// `jsonb_path_exists` in `strict` mode, where the default `lax` mode
93    /// would look into arrays and read a scalar as an array of one. A path the
94    /// other backends cannot express is read as the JSONPath written, with
95    /// `@?`, which a GIN index serves (CockroachDB has no `@?`).
96    fn json_exists(
97        &self,
98        column: &str,
99        existence: JsonExistence,
100        target: &str,
101        negate: bool,
102    ) -> Result<BoundSql, RenderError> {
103        let jsonb = jsonb(column);
104        let text = |text: String| Value::String(Some(text));
105        let sql = match existence {
106            JsonExistence::Key => unknown_when_null(
107                column,
108                bound!(
109                    format!("(jsonb_typeof({jsonb}) = 'object' AND {jsonb} ? "),
110                    text(target.to_string()),
111                    ")"
112                ),
113            ),
114            // A step strict mode refuses is suppressed by the silent
115            // `jsonb_path_exists`, which then reports no answer (PostgreSQL)
116            // or false (CockroachDB, which has no `@?`); it is a missing member.
117            JsonExistence::Path => match parse_json_path(target) {
118                Some(steps) => unknown_when_null(
119                    column,
120                    bound!(
121                        format!("COALESCE(jsonb_path_exists({jsonb}, ("),
122                        text(format!("strict {}", json_path_text(&steps))),
123                        "::jsonpath), '{}', TRUE), FALSE)"
124                    ),
125                ),
126                None => bound!(
127                    format!("{jsonb} @? ("),
128                    text(target.to_string()),
129                    "::jsonpath)"
130                ),
131            },
132        };
133        Ok(negated(sql, negate))
134    }
135
136    fn array_predicate(
137        &self,
138        column: &str,
139        operator: ArrayOperator,
140        elements: Vec<Value>,
141        null_allowed: bool,
142    ) -> BoundSql {
143        let checks = || {
144            elements
145                .iter()
146                .map(|element| bound!(element.clone(), format!(" = ANY({column})")))
147                .collect()
148        };
149        match operator {
150            ArrayOperator::Contains => all_elements(column, checks()),
151            ArrayOperator::Overlaps => any_element(checks()),
152            ArrayOperator::ContainedBy => contained_by(column, elements, null_allowed),
153        }
154    }
155
156    fn array_append(&self, column: &str, element: Value) -> BoundSql {
157        bound!(format!("array_append({column}, "), element, ")")
158    }
159
160    fn array_remove(&self, column: &str, _source: &str, element: Value) -> BoundSql {
161        bound!(format!("array_remove({column}, "), element, ")")
162    }
163
164    /// `jsonb_set` reads an index step of an object as a key and fails the
165    /// statement on a member step of an array, so each step's parent is
166    /// checked to be the object or array the step needs first.
167    fn json_set(&self, column: &str, path: &[JsonPathStep], value: &serde_json::Value) -> BoundSql {
168        let jsonb = jsonb(column);
169        if path.is_empty() {
170            return BoundSql::sql(jsonb);
171        }
172        let guards = path.iter().enumerate().map(|(index, step)| {
173            let kind = match step {
174                JsonPathStep::Member(_) => "object",
175                JsonPathStep::Element(_) => "array",
176            };
177            bound!(
178                format!("jsonb_typeof({jsonb} #> "),
179                Value::String(Some(path_array(&path[..index]))),
180                format!("::text[]) = '{kind}'")
181            )
182        });
183        bound!(
184            "CASE WHEN ",
185            BoundSql::join(guards, " AND "),
186            format!(" THEN jsonb_set({jsonb}, "),
187            Value::String(Some(path_array(path))),
188            "::text[], CAST(",
189            json_text(value),
190            format!(" AS jsonb)) ELSE {jsonb} END")
191        )
192    }
193}
194
195/// `column` as `jsonb`, which PostgreSQL's JSON operators require: a `json`
196/// column has none of them. On a `jsonb` column the cast is dropped at
197/// planning, so its indexes still apply.
198fn jsonb(column: &str) -> String {
199    format!("({column})::jsonb")
200}
201
202/// A JSON path as the `text[]` literal `jsonb_set` takes.
203fn path_array(steps: &[JsonPathStep]) -> String {
204    let elements: Vec<String> = steps
205        .iter()
206        .map(|step| {
207            let text = match step {
208                JsonPathStep::Member(key) => key.clone(),
209                JsonPathStep::Element(index) => index.to_string(),
210            };
211            format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
212        })
213        .collect();
214    format!("{{{}}}", elements.join(","))
215}
216
217/// `column <@ ARRAY[..]`, `elements` being the list's non-NULL values and
218/// `null_allowed` whether the list also holds a NULL.
219///
220/// An empty list leaves only the empty array contained, and a NULL element is
221/// contained only when the list holds a NULL. A NULL *element* makes
222/// `element NOT IN (..)` evaluate to NULL rather than TRUE, so the offending
223/// row would not be counted; `element IS NULL OR ..` counts it instead. A NULL
224/// in the list is left out of `NOT IN` for the same reason: it would make
225/// every element look contained.
226fn contained_by(column: &str, elements: Vec<Value>, null_allowed: bool) -> BoundSql {
227    let element = format!("{ARRAY_ELEMENT}.element");
228    let empty = elements.is_empty();
229    let list = bound!(
230        format!("{element} NOT IN ("),
231        BoundSql::join(elements.into_iter().map(|value| bound!(value)), ", "),
232        ")"
233    );
234    let offending = match (empty, null_allowed) {
235        (true, false) => None,
236        (true, true) => Some(BoundSql::sql(format!("{element} IS NOT NULL"))),
237        (false, false) => Some(bound!(format!("{element} IS NULL OR "), list)),
238        (false, true) => Some(list),
239    };
240    array_contained_by(
241        column,
242        &format!("unnest({column}) AS {ARRAY_ELEMENT}(element)"),
243        offending,
244    )
245}
246
247/// The array type of `values`, when they share one.
248fn shared_array_type(values: &[Value]) -> Option<ArrayType> {
249    let array_type = values.first()?.array_type();
250    values
251        .iter()
252        .all(|value| value.array_type() == array_type)
253        .then_some(array_type)
254}
255
256#[cfg(test)]
257#[path = "../../../tests/unit/postgres_dialect_tests.rs"]
258mod tests;