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 {
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 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 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 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 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
195fn jsonb(column: &str) -> String {
199 format!("({column})::jsonb")
200}
201
202fn 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
217fn 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
247fn 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;