sql_builder/backend/sqlite/
dialect.rs1use super::{SqliteQueryBuilder, json};
5use crate::backend::bound_sql::bound;
6use crate::backend::dialect::{
7 ArrayOperator, BoundSql, JsonContainment, JsonExistence, JsonPathStep, LONG_LIST, SqlDialect,
8 all_elements, any_element, array_contained_by, builder_dialect, document, existence_steps,
9 in_list, json_path_text, json_text, negated, unknown_when_null,
10};
11use crate::{Expr, Value, error::RenderError};
12
13const ELEMENT: &str = "tideorm_element";
15
16impl SqlDialect for SqliteQueryBuilder {
17 builder_dialect!(SqliteQueryBuilder);
18
19 fn json_equals(&self, column: &str, value: &serde_json::Value, negate: bool) -> BoundSql {
23 let equal = json::sqlite_json_equals(column, value);
24 if negate {
25 bound!(format!("({column} IS NOT NULL AND NOT "), equal, ")")
26 } else {
27 equal
28 }
29 }
30
31 fn json_containment(
32 &self,
33 column: &str,
34 value: &serde_json::Value,
35 containment: JsonContainment,
36 ) -> BoundSql {
37 match containment {
38 JsonContainment::Contains => json::sqlite_json_contains(column, value),
39 JsonContainment::ContainedBy => json::sqlite_json_contained_by(column, value),
40 }
41 }
42
43 fn json_exists(
46 &self,
47 column: &str,
48 existence: JsonExistence,
49 target: &str,
50 negate: bool,
51 ) -> Result<BoundSql, RenderError> {
52 let steps = existence_steps(existence, target, "SQLite")?;
53 let sql = unknown_when_null(
54 column,
55 bound!(
56 format!("json_type({column}, "),
57 Value::String(Some(json_path_text(&steps))),
58 ") IS NOT NULL"
59 ),
60 );
61 Ok(negated(sql, negate))
62 }
63
64 fn array_predicate(
70 &self,
71 column: &str,
72 operator: ArrayOperator,
73 elements: Vec<Value>,
74 _null_allowed: bool,
75 ) -> BoundSql {
76 let checks: Vec<BoundSql> = elements
77 .iter()
78 .map(|element| json::sqlite_json_element_equals(ELEMENT, &document(element)))
79 .collect();
80 let rows = format!("json_each({column}) AS {ELEMENT}");
81 let has_elements = |checks: Vec<BoundSql>| {
82 checks
83 .into_iter()
84 .map(|equal| bound!(format!("EXISTS (SELECT 1 FROM {rows} WHERE "), equal, ")"))
85 .collect()
86 };
87 let sql = match operator {
88 ArrayOperator::Contains => all_elements(column, has_elements(checks)),
89 ArrayOperator::Overlaps => any_element(has_elements(checks)),
90 ArrayOperator::ContainedBy => {
91 let offending = (!checks.is_empty())
92 .then(|| bound!("NOT (", BoundSql::join(checks, " OR "), ")"));
93 array_contained_by(column, &rows, offending)
94 }
95 };
96 bound!(format!("(json_type({column}) = 'array' AND ("), sql, "))")
99 }
100
101 fn array_append(&self, column: &str, element: Value) -> BoundSql {
104 let text = json_text(&document(&element));
105 bound!(
106 format!("CASE WHEN {column} IS NULL THEN json_array(json("),
107 text.clone(),
108 format!(
109 ")) WHEN json_type({column}) = 'array' THEN json_insert({column}, '$[#]', json("
110 ),
111 text.clone(),
112 format!(")) ELSE json_array(json({column}), json("),
113 text,
114 ")) END"
115 )
116 }
117
118 fn array_remove(&self, column: &str, source: &str, element: Value) -> BoundSql {
122 let equal = json::sqlite_json_element_equals(ELEMENT, &document(&element));
123 let kept = format!("json({ELEMENT}.json -> {ELEMENT}.fullkey)");
124 bound!(
125 format!(
126 "CASE WHEN {column} IS NULL THEN NULL WHEN json_type({column}) <> 'array' THEN {column} \
127 ELSE (SELECT json_group_array({kept} ORDER BY {ELEMENT}.key) \
128 FROM json_each({source}) AS {ELEMENT} WHERE NOT "
129 ),
130 equal,
131 ") END"
132 )
133 }
134
135 fn json_set(&self, column: &str, path: &[JsonPathStep], value: &serde_json::Value) -> BoundSql {
139 let text = |steps: &[JsonPathStep], suffix: &str| {
140 Value::String(Some(format!("{}{suffix}", json_path_text(steps))))
141 };
142 let Some((last, parent)) = path.split_last() else {
143 return BoundSql::sql(column);
144 };
145 let document = json_text(value);
146 match last {
147 JsonPathStep::Member(_) => bound!(
148 format!("CASE WHEN json_type({column}, "),
149 text(parent, ""),
150 format!(") IS NOT 'object' THEN {column} ELSE json_set({column}, "),
151 text(path, ""),
152 ", json(",
153 document,
154 ")) END"
155 ),
156 JsonPathStep::Element(index) => bound!(
157 format!("CASE WHEN json_type({column}, "),
158 text(parent, ""),
159 format!(") IS NOT 'array' THEN {column} WHEN json_array_length({column}, "),
160 text(parent, ""),
161 format!(") > {index} THEN json_set({column}, "),
162 text(path, ""),
163 ", json(",
164 document.clone(),
165 format!(")) ELSE json_insert({column}, "),
166 text(parent, "[#]"),
167 ", json(",
168 document,
169 ")) END"
170 ),
171 }
172 }
173
174 fn open_limit(&self) -> Option<&'static str> {
175 Some("-1")
176 }
177
178 fn exact_key(&self, column: &str) -> String {
179 format!("CAST({column} AS BLOB)")
180 }
181
182 fn literal_match(
186 &self,
187 column: &str,
188 literal: &str,
189 leading: bool,
190 trailing: bool,
191 ) -> Result<BoundSql, RenderError> {
192 if literal.contains('\0') {
193 return Err(RenderError::Unsupported(
194 "SQLite literal text filters cannot represent a NUL character".into(),
195 ));
196 }
197 let test = match (leading, trailing) {
198 (true, true) => "instr(hay, needle) > 0",
199 (false, true) => "substr(hay, 1, length(needle)) = needle",
200 (true, false) => "length(needle) = 0 OR substr(hay, -length(needle)) = needle",
201 (false, false) => "hay = needle",
202 };
203 Ok(bound!(
204 format!(
205 "(SELECT CASE WHEN hay IS NOT NULL THEN ({test}) END FROM \
206 (SELECT CAST(CASE WHEN 'a' LIKE 'A' THEN lower(raw_hay) ELSE raw_hay END AS BLOB) AS hay, \
207 CAST(CASE WHEN 'a' LIKE 'A' THEN lower(raw_needle) ELSE raw_needle END AS BLOB) AS needle \
208 FROM (SELECT {column} AS raw_hay, "
209 ),
210 Value::String(Some(literal.to_owned())),
211 " AS raw_needle)))"
212 ))
213 }
214
215 fn in_list(&self, column: Expr, values: Vec<Value>, negated: bool) -> Expr {
219 if values.len() > LONG_LIST
220 && let Some(texts) = values
221 .iter()
222 .map(|value| match value {
223 Value::String(Some(text)) => Some(text.as_str()),
224 _ => None,
225 })
226 .collect::<Option<Vec<_>>>()
227 {
228 let operator = if negated { " NOT IN" } else { " IN" };
229 return bound!(
230 format!("{operator} (SELECT value FROM json_each("),
231 Value::String(Some(serde_json::to_string(&texts).unwrap_or_default())),
232 "))"
233 )
234 .following(column);
235 }
236 in_list(column, values, negated)
237 }
238}