sql_builder/backend/postgres/
dialect.rs1use 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
17const 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 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 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 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 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 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
170fn jsonb(column: &str) -> String {
174 format!("({column})::jsonb")
175}
176
177fn 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
192fn 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
222fn 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;