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    fn in_list(&self, column: Expr, values: Vec<Value>, negated: bool) -> Expr {
35        if values.len() > LONG_LIST
36            && let Some(array_type) = shared_array_type(&values)
37        {
38            let array = Expr::val(Value::Array(array_type, Some(Box::new(values))));
39            return if negated {
40                column.ne(PgFunc::all(array))
41            } else {
42                column.eq(PgFunc::any(array))
43            };
44        }
45        in_list(column, values, negated)
46    }
47
48    /// The `json` type has no `=` at all, so the column is read as `jsonb`.
49    fn json_equals(&self, column: &str, value: &serde_json::Value, negated: bool) -> BoundSql {
50        let operator = if negated { " <> " } else { " = " };
51        bound!(jsonb(column), operator, Value::from(value.clone()))
52    }
53
54    fn json_containment(
55        &self,
56        column: &str,
57        value: &serde_json::Value,
58        containment: JsonContainment,
59    ) -> BoundSql {
60        let operator = match containment {
61            JsonContainment::Contains => " @> ",
62            JsonContainment::ContainedBy => " <@ ",
63        };
64        bound!(jsonb(column), operator, Value::from(value.clone()))
65    }
66
67    /// A key is tested with `?`, which also finds a string element of an
68    /// array, so the document must be an object first; a path with `@?` in
69    /// `strict` mode, where the default `lax` mode would look into arrays and
70    /// read a scalar as an array of one. A path the other backends cannot
71    /// express is read as the JSONPath written.
72    fn json_exists(
73        &self,
74        column: &str,
75        existence: JsonExistence,
76        target: &str,
77        negate: bool,
78    ) -> Result<BoundSql, RenderError> {
79        let jsonb = jsonb(column);
80        let text = |text: String| Value::String(Some(text));
81        let sql = match existence {
82            JsonExistence::Key => unknown_when_null(
83                column,
84                bound!(
85                    format!("(jsonb_typeof({jsonb}) = 'object' AND {jsonb} ? "),
86                    text(target.to_string()),
87                    ")"
88                ),
89            ),
90            // A step strict mode refuses is suppressed by `@?`, which then
91            // reports no answer; it is a missing member.
92            JsonExistence::Path => match parse_json_path(target) {
93                Some(steps) => unknown_when_null(
94                    column,
95                    bound!(
96                        format!("COALESCE({jsonb} @? ("),
97                        text(format!("strict {}", json_path_text(&steps))),
98                        "::jsonpath), FALSE)"
99                    ),
100                ),
101                None => bound!(
102                    format!("{jsonb} @? ("),
103                    text(target.to_string()),
104                    "::jsonpath)"
105                ),
106            },
107        };
108        Ok(negated(sql, negate))
109    }
110
111    fn array_predicate(
112        &self,
113        column: &str,
114        operator: ArrayOperator,
115        elements: Vec<Value>,
116        null_allowed: bool,
117    ) -> BoundSql {
118        let checks = || {
119            elements
120                .iter()
121                .map(|element| bound!(element.clone(), format!(" = ANY({column})")))
122                .collect()
123        };
124        match operator {
125            ArrayOperator::Contains => all_elements(column, checks()),
126            ArrayOperator::Overlaps => any_element(checks()),
127            ArrayOperator::ContainedBy => contained_by(column, elements, null_allowed),
128        }
129    }
130
131    fn array_append(&self, column: &str, element: Value) -> BoundSql {
132        bound!(format!("array_append({column}, "), element, ")")
133    }
134
135    fn array_remove(&self, column: &str, _source: &str, element: Value) -> BoundSql {
136        bound!(format!("array_remove({column}, "), element, ")")
137    }
138
139    /// `jsonb_set` reads an index step of an object as a key and fails the
140    /// statement on a member step of an array, so each step's parent is
141    /// checked to be the object or array the step needs first.
142    fn json_set(&self, column: &str, path: &[JsonPathStep], value: &serde_json::Value) -> BoundSql {
143        let jsonb = jsonb(column);
144        if path.is_empty() {
145            return BoundSql::sql(jsonb);
146        }
147        let guards = path.iter().enumerate().map(|(index, step)| {
148            let kind = match step {
149                JsonPathStep::Member(_) => "object",
150                JsonPathStep::Element(_) => "array",
151            };
152            bound!(
153                format!("jsonb_typeof({jsonb} #> "),
154                Value::String(Some(path_array(&path[..index]))),
155                format!("::text[]) = '{kind}'")
156            )
157        });
158        bound!(
159            "CASE WHEN ",
160            BoundSql::join(guards, " AND "),
161            format!(" THEN jsonb_set({jsonb}, "),
162            Value::String(Some(path_array(path))),
163            "::text[], CAST(",
164            json_text(value),
165            format!(" AS jsonb)) ELSE {jsonb} END")
166        )
167    }
168}
169
170/// `column` as `jsonb`, which PostgreSQL's JSON operators require: a `json`
171/// column has none of them. On a `jsonb` column the cast is dropped at
172/// planning, so its indexes still apply.
173fn jsonb(column: &str) -> String {
174    format!("({column})::jsonb")
175}
176
177/// A JSON path as the `text[]` literal `jsonb_set` takes.
178fn path_array(steps: &[JsonPathStep]) -> String {
179    let elements: Vec<String> = steps
180        .iter()
181        .map(|step| {
182            let text = match step {
183                JsonPathStep::Member(key) => key.clone(),
184                JsonPathStep::Element(index) => index.to_string(),
185            };
186            format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
187        })
188        .collect();
189    format!("{{{}}}", elements.join(","))
190}
191
192/// `column <@ ARRAY[..]`, `elements` being the list's non-NULL values and
193/// `null_allowed` whether the list also holds a NULL.
194///
195/// An empty list leaves only the empty array contained, and a NULL element is
196/// contained only when the list holds a NULL. A NULL *element* makes
197/// `element NOT IN (..)` evaluate to NULL rather than TRUE, so the offending
198/// row would not be counted; `element IS NULL OR ..` counts it instead. A NULL
199/// in the list is left out of `NOT IN` for the same reason: it would make
200/// every element look contained.
201fn contained_by(column: &str, elements: Vec<Value>, null_allowed: bool) -> BoundSql {
202    let element = format!("{ARRAY_ELEMENT}.element");
203    let empty = elements.is_empty();
204    let list = bound!(
205        format!("{element} NOT IN ("),
206        BoundSql::join(elements.into_iter().map(|value| bound!(value)), ", "),
207        ")"
208    );
209    let offending = match (empty, null_allowed) {
210        (true, false) => None,
211        (true, true) => Some(BoundSql::sql(format!("{element} IS NOT NULL"))),
212        (false, false) => Some(bound!(format!("{element} IS NULL OR "), list)),
213        (false, true) => Some(list),
214    };
215    array_contained_by(
216        column,
217        &format!("unnest({column}) AS {ARRAY_ELEMENT}(element)"),
218        offending,
219    )
220}
221
222/// The array type of `values`, when they share one.
223fn shared_array_type(values: &[Value]) -> Option<ArrayType> {
224    let array_type = values.first()?.array_type();
225    values
226        .iter()
227        .all(|value| value.array_type() == array_type)
228        .then_some(array_type)
229}
230
231#[cfg(test)]
232#[path = "../../../tests/unit/postgres_dialect_tests.rs"]
233mod tests;