1use crate::builder::core::{Builder, Dialect, quote_bytes};
8use crate::builder::feature::{
9 BitwiseAggregates, ConditionalAggregates, CrossJoins, InsertOrIgnore, Json, Locking, RawSql, StatisticalAggregates,
10 StringAggregates, Transactions, Upsert, UpsertSelect,
11};
12use crate::builder::mysql::conflict_clause;
13use crate::builder::postgresql::{json_binding, json_path_parts, on_conflict_header};
14use crate::builder::sql::{self, SqlDialect};
15use crate::builder::types::{Condition, Statement};
16use crate::error::{Error, Result};
17use crate::method::Method;
18use crate::query::Query;
19use crate::value::{self, Array, Value};
20
21pub type Sqlite = Builder<SqliteDialect>;
50
51#[derive(Debug, Clone, Default)]
53pub struct SqliteDialect;
54
55fn json_each_conditions(b: &mut Builder<SqliteDialect>, attribute: &str, values: &Array, glue: &str) -> String {
58 let items = match values.get(&php_std::ArrayKey::Int(0)) {
59 Some(Value::Array(items) | Value::Object(items)) => items.values().cloned().collect(),
60 Some(Value::Null) | None => Vec::new(),
61 Some(other) => vec![other.clone()],
62 };
63 let mut conditions = Vec::with_capacity(items.len());
64 for item in &items {
65 b.add_binding(json_binding(item), None);
66 conditions.push(format!("EXISTS (SELECT 1 FROM json_each({attribute}) WHERE json_each.value = json(?))"));
67 }
68 format!("({})", conditions.join(glue))
69}
70
71impl Dialect for SqliteDialect {
72 const CLASS: &'static str = "Utopia\\Query\\Builder\\SQLite";
73 const DECLARES_LIKE_ESCAPE: bool = true;
74 const IMPLICIT_LIKE_ESCAPE: Option<u8> = None;
75 const LITERAL: crate::StringLiteral = crate::StringLiteral::Standard;
76
77 fn base_step(
78 b: &mut Builder<Self>,
79 step: crate::builder::Step,
80 arguments: &[crate::builder::Arg<'_>],
81 ) -> Option<Result<crate::builder::Ret>> {
82 sql::sql_base_step(b, step, arguments)
83 .or_else(|| crate::builder::feature::aggregates_base_step::<Self>(step, arguments))
84 }
85
86 fn quote_string(value: &[u8]) -> Vec<u8> {
87 quote_bytes(value, false)
88 }
89
90 fn compile_random(_b: &Builder<Self>) -> String {
91 "RANDOM()".into()
92 }
93
94 fn compile_regex(b: &mut Builder<Self>, attribute: &str, values: &Array, column: Option<&str>) -> Result<String> {
95 if b.core.flavor.sqlite.is_none() {
96 return Err(Error::Unsupported("REGEXP is not natively supported in SQLite.".into()));
97 }
98 b.add_binding(crate::builder::core::first(values), column);
99 Ok(format!("{attribute} REGEXP ?"))
100 }
101
102 fn compile_like(
103 b: &mut Builder<Self>,
104 attribute: &str,
105 values: &Array,
106 prefix: &str,
107 suffix: &str,
108 not: bool,
109 column: Option<&str>,
110 ) -> Result<String> {
111 if b.core.flavor.sqlite.is_none() {
112 return b.base_compile_like(attribute, values, prefix, suffix, not, column);
113 }
114 b.sqlite_like(attribute, values, prefix, suffix, not, column)
115 }
116
117 fn compile_contains(
118 b: &mut Builder<Self>,
119 attribute: &str,
120 values: &Array,
121 column: Option<&str>,
122 ) -> Result<String> {
123 if b.core.flavor.sqlite.is_none() {
124 return b.base_compile_contains(attribute, values, column);
125 }
126 let predicates = b.sqlite_substrings(attribute, values, false, column)?;
127 Ok(if predicates.len() == 1 { predicates[0].clone() } else { format!("({})", predicates.join(" OR ")) })
128 }
129
130 fn compile_contains_all(
131 b: &mut Builder<Self>,
132 attribute: &str,
133 values: &Array,
134 column: Option<&str>,
135 ) -> Result<String> {
136 if b.core.flavor.sqlite.is_none() {
137 return b.base_compile_contains_all(attribute, values, column);
138 }
139 Ok(format!("({})", b.sqlite_substrings(attribute, values, false, column)?.join(" AND ")))
140 }
141
142 fn compile_not_contains(
143 b: &mut Builder<Self>,
144 attribute: &str,
145 values: &Array,
146 column: Option<&str>,
147 ) -> Result<String> {
148 if b.core.flavor.sqlite.is_none() {
149 return b.base_compile_not_contains(attribute, values, column);
150 }
151 let predicates = b.sqlite_substrings(attribute, values, true, column)?;
152 Ok(if predicates.len() == 1 { predicates[0].clone() } else { format!("({})", predicates.join(" AND ")) })
153 }
154
155 fn compile_filter(b: &mut Builder<Self>, query: &Query) -> Result<String> {
156 sql::sql_compile_filter(b, query)
157 }
158
159 fn wrap_union_member(_b: &Builder<Self>, sql: &str) -> String {
160 sql.to_owned()
162 }
163
164 fn update(b: &mut Builder<Self>) -> Result<Statement> {
165 for (column, condition) in b.core.json_sets.0.clone() {
166 b.core.raw_sets.set(column.clone(), condition.expression);
167 b.core.raw_set_bindings.set(column, condition.bindings);
168 }
169 let result = b.base_update()?;
170 b.core.json_sets.clear();
171 Ok(result)
172 }
173
174 fn reset(b: &mut Builder<Self>) {
175 b.core.json_sets.clear();
176 }
177
178 fn ast_dialect() -> crate::builder::AstDialect {
179 crate::builder::AstDialect::Sqlite
180 }
181}
182
183impl SqlDialect for SqliteDialect {
184 fn compile_search_expression(
185 _b: &mut Builder<Self>,
186 _attribute: &str,
187 _values: &Array,
188 _not: bool,
189 ) -> Result<String> {
190 Err(Error::Unsupported("Full-text search is not supported in the SQLite query builder.".into()))
191 }
192
193 fn compile_spatial_distance(
194 _b: &mut Builder<Self>,
195 _method: Method,
196 _attribute: &str,
197 _values: &Array,
198 ) -> Result<String> {
199 Err(Error::Unsupported("Spatial distance queries are not supported in SQLite.".into()))
200 }
201
202 fn compile_spatial_predicate(
203 _b: &mut Builder<Self>,
204 _function: &str,
205 _attribute: &str,
206 _values: &Array,
207 _not: bool,
208 ) -> Result<String> {
209 Err(Error::Unsupported("Spatial predicates are not supported in SQLite.".into()))
210 }
211
212 fn compile_spatial_covers_predicate(
213 _b: &mut Builder<Self>,
214 _attribute: &str,
215 _values: &Array,
216 _not: bool,
217 ) -> Result<String> {
218 Err(Error::Unsupported("Spatial covers predicates are not supported in SQLite.".into()))
219 }
220
221 fn compile_json_contains_expression(
222 b: &mut Builder<Self>,
223 attribute: &str,
224 values: &Array,
225 not: bool,
226 ) -> Result<String> {
227 if b.core.flavor.sqlite.is_some() {
228 let needles = crate::builder::core::first(values);
229 let expression = format!("({})", b.sqlite_element_matches(attribute, &needles)?.join(" AND "));
230 return Ok(if not { format!("({attribute} IS NOT NULL AND NOT {expression})") } else { expression });
231 }
232 let expression = json_each_conditions(b, attribute, values, " AND ");
233 Ok(if not { format!("NOT {expression}") } else { expression })
234 }
235
236 fn compile_json_overlaps_expression(b: &mut Builder<Self>, attribute: &str, values: &Array) -> Result<String> {
237 if b.core.flavor.sqlite.is_some() {
238 let needles = crate::builder::core::first(values);
239 return Ok(format!("({})", b.sqlite_element_matches(attribute, &needles)?.join(" OR ")));
240 }
241 Ok(json_each_conditions(b, attribute, values, " OR "))
242 }
243
244 fn compile_array_filter(b: &mut Builder<Self>, method: Method, attribute: &str, query: &Query) -> Result<String> {
245 if b.core.flavor.sqlite.is_some() && method == Method::NotContains {
246 let wrapped = value::list([Value::Array(query.values().clone())]);
247 let overlaps = b.step_string(
248 crate::builder::Step::CompileJsonOverlapsExpression,
249 &[crate::builder::Arg::Str(attribute), crate::builder::Arg::Values(&wrapped)],
250 )?;
251 return Ok(format!("({attribute} IS NOT NULL AND NOT {overlaps})"));
252 }
253 sql::sql_compile_array_filter(b, method, attribute, query)
254 }
255
256 fn compile_json_path_expression(b: &mut Builder<Self>, attribute: &str, values: &Array) -> Result<String> {
257 let (path, operator) = json_path_parts(b, values)?;
258 Ok(format!("json_extract({attribute}, '$.{path}') {operator} ?"))
259 }
260
261 fn compile_conflict_header(b: &mut Builder<Self>) -> Result<String> {
262 on_conflict_header(b)
263 }
264
265 fn compile_conflict_assignment(wrapped: &str) -> String {
266 format!("excluded.{wrapped}")
267 }
268}
269
270impl Locking for SqliteDialect {}
271impl Transactions for SqliteDialect {}
272impl StatisticalAggregates for SqliteDialect {}
273impl BitwiseAggregates for SqliteDialect {}
274impl RawSql for SqliteDialect {}
275impl CrossJoins for SqliteDialect {}
276impl ConditionalAggregates for SqliteDialect {}
277
278impl StringAggregates for SqliteDialect {
279 fn group_concat_expr(column: &str, order_by: &str) -> String {
280 if order_by.is_empty() {
281 format!("GROUP_CONCAT({column}, ?)")
282 } else {
283 format!("GROUP_CONCAT({column} {order_by}, ?)")
284 }
285 }
286 fn json_array_agg_expr(column: &str) -> String {
287 format!("json_group_array({column})")
288 }
289 fn json_object_agg_expr(key: &str, value: &str) -> String {
290 format!("json_group_object({key}, {value})")
291 }
292}
293
294impl Upsert for SqliteDialect {
295 fn upsert(b: &mut Builder<Self>) -> Result<Statement> {
296 b.compile_upsert(conflict_clause)
297 }
298}
299
300impl UpsertSelect for SqliteDialect {
301 fn upsert_select(b: &mut Builder<Self>) -> Result<Statement> {
302 b.compile_upsert_select(conflict_clause)
303 }
304}
305
306impl InsertOrIgnore for SqliteDialect {
307 fn insert_or_ignore(b: &mut Builder<Self>) -> Result<Statement> {
308 b.core.bindings.clear();
309 let (sql, bindings) = b.compile_insert_body()?;
310 b.add_bindings(bindings);
311 let sql = match sql.strip_prefix("INSERT INTO") {
312 Some(rest) => format!("INSERT OR IGNORE INTO{rest}"),
313 None => sql,
314 };
315 Ok(b.statement(sql))
316 }
317}
318
319impl Json for SqliteDialect {
320 fn set_json_append(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
321 let wrapped = b.resolve_and_wrap(column)?;
322 b.core.json_sets.set(
323 column,
324 Condition::new(
325 format!(
326 "json_group_array(value) FROM (SELECT value FROM json_each(IFNULL({wrapped}, '[]')) UNION ALL SELECT value FROM json_each(?))"
327 ),
328 vec![json_binding(&Value::Array(values.clone()))],
329 ),
330 );
331 Ok(())
332 }
333
334 fn set_json_prepend(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
335 let wrapped = b.resolve_and_wrap(column)?;
336 b.core.json_sets.set(
337 column,
338 Condition::new(
339 format!(
340 "json_group_array(value) FROM (SELECT value FROM json_each(?) UNION ALL SELECT value FROM json_each(IFNULL({wrapped}, '[]')))"
341 ),
342 vec![json_binding(&Value::Array(values.clone()))],
343 ),
344 );
345 Ok(())
346 }
347
348 fn set_json_insert(b: &mut Builder<Self>, column: &str, index: i64, value: Value) -> Result<()> {
349 let wrapped = b.resolve_and_wrap(column)?;
350 b.core.json_sets.set(
351 column,
352 Condition::new(format!("json_insert({wrapped}, '$[{index}]', json(?))"), vec![json_binding(&value)]),
353 );
354 Ok(())
355 }
356
357 fn set_json_remove(b: &mut Builder<Self>, column: &str, value: Value) -> Result<()> {
358 let wrapped = b.resolve_and_wrap(column)?;
359 b.core.json_sets.set(
360 column,
361 Condition::new(
362 format!("(SELECT json_group_array(value) FROM json_each({wrapped}) WHERE value != json(?))"),
363 vec![json_binding(&value)],
364 ),
365 );
366 Ok(())
367 }
368
369 fn set_json_intersect(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
370 let wrapped = b.resolve_and_wrap(column)?;
371 b.set_raw(
372 column,
373 format!(
374 "(SELECT json_group_array(value) FROM json_each(IFNULL({wrapped}, '[]')) WHERE value IN (SELECT value FROM json_each(?)))"
375 ),
376 vec![json_binding(&Value::Array(values.clone()))],
377 );
378 Ok(())
379 }
380
381 fn set_json_diff(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
382 let wrapped = b.resolve_and_wrap(column)?;
383 b.set_raw(
384 column,
385 format!(
386 "(SELECT json_group_array(value) FROM json_each(IFNULL({wrapped}, '[]')) WHERE value NOT IN (SELECT value FROM json_each(?)))"
387 ),
388 vec![json_binding(&Value::Array(values.clone()))],
389 );
390 Ok(())
391 }
392
393 fn set_json_unique(b: &mut Builder<Self>, column: &str) -> Result<()> {
394 let wrapped = b.resolve_and_wrap(column)?;
395 b.set_raw(
396 column,
397 format!("(SELECT json_group_array(DISTINCT value) FROM json_each(IFNULL({wrapped}, '[]')))"),
398 Vec::<Value>::new(),
399 );
400 Ok(())
401 }
402
403 fn set_json_path(b: &mut Builder<Self>, column: &str, path: &str, value: Value) -> Result<()> {
404 if !path.starts_with('$') {
405 return Err(Error::Validation(format!("JSON path must start with '$': {path}")));
406 }
407 let wrapped = b.resolve_and_wrap(column)?;
408 b.core
409 .json_sets
410 .set(column, Condition::new(format!("json_set({wrapped}, ?, ?)"), vec![value::string(path), value]));
411 Ok(())
412 }
413}