1use unisql_core::ast::*;
9use unisql_core::report::{Allowance, ParamBinding, Tier, Untranslatable};
10use unisql_core::rewrite;
11use unisql_core::target::{
12 Ctx, DmlLimit, DmlSources, Escape, StmtKind, generic_call, generic_call_ordered,
13};
14use unisql_core::{Read, ReadError, Target};
15
16pub fn read(sql: &str) -> Result<Read, ReadError> {
18 unisql_sqlparser_adapter::read(sql, &unisql_sqlparser_adapter::SQLITE)
19}
20
21#[derive(Clone, Copy, Debug, Default)]
22pub struct Sqlite;
23
24type R<T> = Result<T, Untranslatable>;
25
26impl Target for Sqlite {
27 fn name(&self) -> &'static str {
28 "sqlite"
29 }
30
31 fn bytes_literal(&self, b: &[u8]) -> String {
32 let hex: String = b.iter().map(|x| format!("{x:02X}")).collect();
33 format!("X'{hex}'")
34 }
35
36 fn placeholder(&self, n: u32) -> String {
37 format!("?{n}")
39 }
40
41 fn bool_literal(&self, b: bool, ctx: &mut Ctx) -> R<String> {
42 ctx.note(
43 "boolean_literal",
44 Tier::Conditional,
45 "SQLite has no boolean type; TRUE/FALSE are 1/0 and results come back as integers",
46 Some(Allowance::BooleanAsInteger),
47 )?;
48 Ok(if b { "1" } else { "0" }.to_string())
49 }
50
51 fn like(
52 &self,
53 lhs: &str,
54 rhs: &str,
55 negated: bool,
56 ci: bool,
57 esc: Escape<'_>,
58 ctx: &mut Ctx,
59 ) -> R<String> {
60 let not = if negated { "NOT " } else { "" };
61 let tail = match esc {
63 Escape::None => String::new(),
64 Escape::Default => " ESCAPE '\\'".to_string(),
65 Escape::Custom(c) => format!(" ESCAPE {c}"),
66 };
67 if ci {
68 ctx.note(
70 "ilike",
71 Tier::Conditional,
72 "emulated as lower(a) LIKE lower(b) ESCAPE; lower() folds ASCII only",
73 Some(Allowance::AsciiOnlyCaseFolding),
74 )?;
75 ctx.note(
76 "ilike",
77 Tier::Conditional,
78 "the target's LIKE case sensitivity is a connection setting (PRAGMA case_sensitive_like)",
79 Some(Allowance::LikeCaseSensitivityIsConnectionSetting),
80 )?;
81 Ok(format!("lower({lhs}) {not}LIKE lower({rhs}){tail}"))
82 } else {
83 ctx.note(
84 "like",
85 Tier::Conditional,
86 "SQLite LIKE is ASCII case-insensitive unless PRAGMA case_sensitive_like=ON; \
87 an ESCAPE clause is added to match PostgreSQL's default escape character",
88 Some(Allowance::LikeCaseSensitivityIsConnectionSetting),
89 )?;
90 Ok(format!("{lhs} {not}LIKE {rhs}{tail}"))
91 }
92 }
93
94 fn regexp(&self, _lhs: &str, _rhs: &str, _negated: bool, ctx: &mut Ctx) -> R<String> {
95 Err(ctx.refuse(
98 "regexp",
99 "SQLite has no built-in regular-expression matcher (REGEXP needs an application-defined function)",
100 &["LIKE or GLOB for simple patterns"],
101 ))
102 }
103
104 fn rewrite_query(&self, q: &Query, ctx: &mut Ctx) -> R<Option<Query>> {
105 if let SetExpr::Select(s) = &q.body
106 && matches!(s.distinct, Distinct::On(_))
107 {
108 return match rewrite::distinct_on_via_window(q) {
109 Ok(q2) => {
110 ctx.note(
111 "distinct_on",
112 Tier::Emulated,
113 "row_number() OVER (PARTITION BY keys ORDER BY ..) = 1 in a derived table; \
114 without ORDER BY the surviving row per key is arbitrary on both engines",
115 None,
116 )?;
117 Ok(Some(q2))
118 }
119 Err(c) => Err(ctx.refuse(c.leaf, &c.why, &["list the columns explicitly"])),
120 };
121 }
122 Ok(None)
123 }
124
125 fn feature(&self, name: &'static str, ctx: &mut Ctx) -> R<()> {
126 let min = match name {
127 "window_function" => "requires SQLite >= 3.25",
128 "filter_clause" => "requires SQLite >= 3.30",
129 "recursive_cte" => "requires SQLite >= 3.8.3",
130 "named_arg" => {
131 return Err(ctx.refuse(
132 "named_arg",
133 "SQLite functions have no named-argument notation",
134 &["use positional arguments"],
135 ));
136 }
137 "lateral" => {
138 return Err(ctx.refuse(
139 "lateral",
140 "SQLite has no LATERAL: a subquery in FROM cannot refer to the tables to its left",
141 &["rewrite as a correlated subquery in the select list, or a window function over a join"],
142 ));
143 }
144 _ => "",
145 };
146 ctx.note(name, Tier::Exact, min, None)
147 }
148
149 fn trim(&self, side: TrimSide, expr: &str, chars: Option<&str>, ctx: &mut Ctx) -> R<String> {
150 ctx.note("trim", Tier::Exact, "", None)?;
151 let f = match side {
152 TrimSide::Both => "trim",
153 TrimSide::Leading => "ltrim",
154 TrimSide::Trailing => "rtrim",
155 };
156 Ok(match chars {
157 Some(c) => format!("{f}({expr}, {c})"),
158 None => format!("{f}({expr})"),
159 })
160 }
161
162 fn interval_arith(
163 &self,
164 minus: bool,
165 left: &str,
166 parts: &[(String, String)],
167 ctx: &mut Ctx,
168 ) -> R<Option<String>> {
169 let mut mods = Vec::new();
170 for (unit, value) in parts {
171 let (sql_unit, mult) = match unit.as_str() {
172 "secs" => ("seconds", None),
173 "mins" => ("minutes", None),
174 "hours" => ("hours", None),
175 "days" => ("days", None),
176 "weeks" => ("days", Some(7)),
177 other => {
178 return Err(ctx.refuse(
179 if matches!(other, "months" | "years") {
180 "fn:make_interval.month_year"
181 } else {
182 "fn:make_interval"
183 },
184 &format!("make_interval({other} => ..): month/year arithmetic differs between the engines"),
185 &["use secs/mins/hours/days/weeks"],
186 ));
187 }
188 };
189 let v = match mult {
190 Some(m) => format!("(({value}) * {m})"),
191 None => format!("({value})"),
192 };
193 let signed = if minus { format!("(-{v})") } else { v };
194 mods.push(format!("printf('%+f {sql_unit}', {signed})"));
195 }
196 ctx.note(
197 "interval_arithmetic",
198 Tier::Conditional,
199 "timestamp +/- make_interval(..) becomes datetime(ts, modifiers): text, whole seconds, UTC",
200 Some(Allowance::TimestampArithmeticAsText),
201 )?;
202 Ok(Some(format!("datetime({left}, {})", mods.join(", "))))
203 }
204
205 fn json_access(&self, text: bool, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
206 if text {
207 ctx.note(
208 "json_get_text",
209 Tier::Conditional,
210 "SQLite ->> keeps the scalar's type (true -> 1); cast to TEXT here, but a JSON boolean \
211 still reads '1' where PostgreSQL reads 'true'. Requires SQLite >= 3.38",
212 Some(Allowance::JsonScalarAffinity),
213 )?;
214 Ok(format!("CAST({lhs} ->> {rhs} AS TEXT)"))
215 } else {
216 ctx.note(
217 "json_get",
218 Tier::Conditional,
219 "SQLite -> returns JSON text; comparison is textual, not jsonb equality. Requires >= 3.38",
220 Some(Allowance::JsonRepresentationAsText),
221 )?;
222 Ok(format!("{lhs} -> {rhs}"))
223 }
224 }
225
226 fn function(&self, f: &Function, args: &[String], ctx: &mut Ctx) -> R<String> {
227 let n = f.name.as_str();
228 if n == "current_date" {
229 if ctx.source == "sqlite" {
230 ctx.note("fn:current_date", Tier::Exact, "", None)?;
231 } else {
232 ctx.note(
233 "fn:current_date",
234 Tier::Conditional,
235 "-> CURRENT_DATE; text 'YYYY-MM-DD' of the UTC date, not a date in the session time zone",
236 Some(Allowance::DateAsText),
237 )?;
238 }
239 return Ok("CURRENT_DATE".to_string());
240 }
241 if ctx.source == "sqlite" {
242 if n == "now" {
243 ctx.note("fn:now", Tier::Exact, "", None)?;
245 return Ok("CURRENT_TIMESTAMP".to_string());
246 }
247 if n == "strpos" && args.len() == 2 {
249 ctx.note("fn:strpos", Tier::Exact, "", None)?;
250 return Ok(format!("instr({}, {})", args[0], args[1]));
251 }
252 ctx.note(format!("fn:{n}"), Tier::Exact, "", None)?;
254 let order = ctx.agg_order.take();
255 return Ok(generic_call_ordered(
256 n,
257 args,
258 f.distinct,
259 f.star,
260 order.as_deref(),
261 ));
262 }
263 match n {
264 "utc_timestamp" => {
265 let (text, allow2) = match unisql_core::target::utc_timestamp_precision(f) {
266 Some(0) => ("datetime('now')", None),
267 Some(6) => (
268 "strftime('%Y-%m-%d %H:%M:%f', 'now')",
269 Some(Allowance::TimestampMillisecondResolution),
270 ),
271 _ => {
272 return Err(ctx.refuse(
273 "fn:utc_timestamp.precision",
274 "only UTC_TIMESTAMP() and UTC_TIMESTAMP(6) are verified",
275 &["use UTC_TIMESTAMP() or UTC_TIMESTAMP(6)"],
276 ));
277 }
278 };
279 ctx.note(
280 "fn:utc_timestamp",
281 Tier::Conditional,
282 "text 'YYYY-MM-DD HH:MM:SS[.fff]' in UTC, not a timestamp type",
283 Some(Allowance::TimestampAsText),
284 )?;
285 if let Some(a) = allow2 {
286 ctx.note(
287 "fn:utc_timestamp",
288 Tier::Conditional,
289 "SQLite's %f has millisecond resolution; MySQL's UTC_TIMESTAMP(6) has microseconds",
290 Some(a),
291 )?;
292 }
293 return Ok(text.to_string());
294 }
295 "utc_date" if args.is_empty() => {
296 ctx.note(
297 "fn:utc_date",
298 Tier::Conditional,
299 "text 'YYYY-MM-DD' of the UTC date, not a date type",
300 Some(Allowance::DateAsText),
301 )?;
302 return Ok("date('now')".to_string());
303 }
304 "datediff" if args.len() == 2 => {
305 ctx.note(
306 "fn:datediff",
307 Tier::Conditional,
308 "operands are timestamp text; whole days between their date parts",
309 Some(Allowance::TimestampAsText),
310 )?;
311 return Ok(format!(
312 "CAST(julianday(date({})) - julianday(date({})) AS INTEGER)",
313 args[0], args[1]
314 ));
315 }
316 "concat_ws" if args.len() >= 2 => {
317 ctx.note("fn:concat_ws", Tier::Exact, "requires SQLite >= 3.44", None)?;
318 return Ok(format!("concat_ws({})", args.join(", ")));
319 }
320 "left" if args.len() == 2 && unisql_core::target::literal_count(f, 1).is_some() => {
321 ctx.note("fn:left", Tier::Exact, "-> substr(s, 1, n)", None)?;
322 return Ok(format!("substr({}, 1, {})", args[0], args[1]));
323 }
324 "left" if args.len() == 2 => {
325 return Err(ctx.refuse(
326 "fn:left.length",
327 "LEFT(s, n) is mapped only for a literal n >= 0",
328 &["use a literal non-negative count"],
329 ));
330 }
331 "right" if args.len() == 2 => {
332 return match unisql_core::target::literal_count(f, 1) {
333 Some(0) => {
334 ctx.note("fn:right", Tier::Exact, "-> substr(s, 1, 0)", None)?;
335 Ok(format!("substr({}, 1, 0)", args[0]))
336 }
337 Some(_) => {
338 ctx.note("fn:right", Tier::Exact, "-> substr(s, -n)", None)?;
339 Ok(format!("substr({}, -{})", args[0], args[1]))
340 }
341 None => Err(ctx.refuse(
342 "fn:right.length",
343 "RIGHT(s, n) is mapped only for a literal n >= 0",
344 &["use a literal non-negative count"],
345 )),
346 };
347 }
348 "repeat" if args.len() == 2 && unisql_core::target::literal_count(f, 1).is_some() => {
349 ctx.note(
350 "fn:repeat",
351 Tier::Emulated,
352 "-> replace(hex(zeroblob(n)), '00', s)",
353 None,
354 )?;
355 return Ok(format!(
356 "replace(hex(zeroblob({})), '00', {})",
357 args[1], args[0]
358 ));
359 }
360 "date" if args.len() == 1 => {
361 ctx.note(
362 "fn:date",
363 Tier::Conditional,
364 "text 'YYYY-MM-DD', not a date type",
365 Some(Allowance::DateAsText),
366 )?;
367 return Ok(format!("date({})", args[0]));
368 }
369 _ => {}
370 }
371 if f.over.is_some()
372 && matches!(
373 n,
374 "row_number"
375 | "rank"
376 | "dense_rank"
377 | "percent_rank"
378 | "cume_dist"
379 | "ntile"
380 | "lag"
381 | "lead"
382 | "first_value"
383 | "last_value"
384 | "nth_value"
385 )
386 {
387 ctx.note(format!("fn:{n}"), Tier::Exact, "window function", None)?;
388 return Ok(generic_call(n, args, false, false));
389 }
390 match n {
391 "md5" | "sha256" | "sha1" | "sha512" | "encode" | "decode" | "convert_to"
392 | "convert_from" => {
393 return Err(ctx.refuse(
394 &format!("fn:{n}"),
395 "SQLite has no built-in hashing/encoding functions; the result would depend on a \
396 host-registered function or extension, which UniSQL cannot assume",
397 &["hash in the application", "register the function and use a raw(sqlite, ..) fragment"],
398 ));
399 }
400 "current_schema" | "current_database" | "current_user" | "session_user"
401 | "to_regclass" | "pg_backend_pid" | "set_config" | "current_setting" => {
402 return Err(ctx.refuse(
403 &format!("fn:{n}"),
404 "PostgreSQL catalog/session introspection has no SQLite equivalent",
405 &["query sqlite_schema (a different, SQLite-specific statement)"],
406 ));
407 }
408 "make_interval" => {
409 return Err(ctx.refuse(
410 "fn:make_interval.standalone",
411 "SQLite has no interval type; only `timestamp +/- make_interval(secs|mins|hours|days|weeks => ..)` is translated",
412 &[],
413 ));
414 }
415 "regexp_replace" | "regexp_match" | "regexp_matches" | "split_part" => {
416 return Err(ctx.refuse(
417 &format!("fn:{n}"),
418 "no built-in regular-expression or split function in SQLite",
419 &[],
420 ));
421 }
422 _ => {}
423 }
424 match n {
425 "ceil" | "floor" => Err(ctx.refuse(
428 &format!("fn:{n}"),
429 "SQLite's ceil/floor exist only when it is built with its math functions",
430 &["round in the application"],
431 )),
432 "strpos" if args.len() == 2 => {
433 ctx.note("fn:strpos", Tier::Exact, "-> instr(s, sub)", None)?;
434 Ok(format!("instr({}, {})", args[0], args[1]))
435 }
436 "min" | "max" => {
437 ctx.note(
438 format!("fn:{n}"),
439 Tier::Conditional,
440 "on text, follows the target's collation (BINARY by default)",
441 Some(Allowance::TextCollation),
442 )?;
443 Ok(generic_call(n, args, f.distinct, f.star))
444 }
445 "count" | "sum" | "avg" | "coalesce" | "nullif" | "abs" | "length" | "replace"
446 | "trim" | "ltrim" | "rtrim" | "substr" | "ifnull" => {
447 ctx.note(format!("fn:{n}"), Tier::Exact, "", None)?;
448 Ok(generic_call(n, args, f.distinct, f.star))
449 }
450 "lower" | "upper" => {
451 ctx.note(
452 format!("fn:{n}"),
453 Tier::Conditional,
454 "SQLite folds ASCII only",
455 Some(Allowance::AsciiOnlyCaseFolding),
456 )?;
457 Ok(generic_call(n, args, false, false))
458 }
459 "btrim" => {
460 ctx.note("fn:btrim", Tier::Emulated, "-> trim(x[, chars])", None)?;
461 Ok(generic_call("trim", args, false, false))
462 }
463 "octet_length" => {
464 if args.len() != 1 {
465 return Err(ctx.refuse(
466 "fn:octet_length",
467 "octet_length takes one argument",
468 &[],
469 ));
470 }
471 ctx.note(
472 "fn:octet_length",
473 Tier::Emulated,
474 "-> length(CAST(x AS BLOB)): bytes, not characters",
475 None,
476 )?;
477 Ok(format!("LENGTH(CAST({} AS BLOB))", args[0]))
478 }
479 "char_length" | "character_length" => {
480 ctx.note(format!("fn:{n}"), Tier::Emulated, "-> length()", None)?;
481 Ok(generic_call("length", args, false, false))
482 }
483 "string_agg" => {
484 if args.len() != 2 {
485 return Err(ctx.refuse(
486 "fn:string_agg",
487 "string_agg needs exactly (value, separator)",
488 &[],
489 ));
490 }
491 ctx.note(
492 "fn:string_agg",
493 Tier::Emulated,
494 "-> group_concat(value, separator); an ORDER BY inside needs SQLite >= 3.44",
495 None,
496 )?;
497 let order = ctx.agg_order.take();
498 let args = if f.distinct {
500 if args[1] != "','" {
501 return Err(ctx.refuse(
502 "fn:string_agg",
503 "SQLite group_concat(DISTINCT ..) cannot take a separator",
504 &["aggregate without DISTINCT, or use the default ',' separator"],
505 ));
506 }
507 &args[..1]
508 } else {
509 args
510 };
511 Ok(generic_call_ordered(
512 "group_concat",
513 args,
514 f.distinct,
515 false,
516 order.as_deref(),
517 ))
518 }
519 "to_timestamp" if args.len() == 1 => {
521 ctx.note(
522 "fn:to_timestamp",
523 Tier::Conditional,
524 "datetime(x, 'unixepoch'): text YYYY-MM-DD HH:MM:SS in UTC",
525 Some(Allowance::TimestampAsText),
526 )?;
527 ctx.note(
528 "fn:to_timestamp",
529 Tier::Conditional,
530 "a fraction of a second is dropped",
531 Some(Allowance::TimestampWholeSeconds),
532 )?;
533 Ok(format!("datetime({}, 'unixepoch')", args[0]))
534 }
535 "age" => Err(ctx.refuse(
538 "fn:age",
539 "age() returns a calendar interval (years, months, days); SQLite has no interval value",
540 &["compute the difference in the application, or use EXTRACT(EPOCH FROM a - b)"],
541 )),
542 "to_char"
544 if unisql_core::target::to_char_format(f, ["%Y", "%m", "%d", "%H", "%M", "%S"])
545 .is_some() =>
546 {
547 let fmt =
548 unisql_core::target::to_char_format(f, ["%Y", "%m", "%d", "%H", "%M", "%S"])
549 .unwrap_or_default();
550 ctx.note(
551 "fn:to_char",
552 Tier::Conditional,
553 "strftime formats the timestamp text; the result is text",
554 Some(Allowance::TimestampAsText),
555 )?;
556 Ok(format!("strftime('{fmt}', {})", args[0]))
557 }
558 "to_char" => Err(ctx.refuse(
559 "fn:to_char.format",
560 "to_char: only literal formats of YYYY, MM, DD, HH24, MI, SS and - / : . , space are mapped",
561 &["format in the application"],
562 )),
563 "date_trunc"
565 if args.len() == 2 && unisql_core::target::date_trunc_field(f).is_some() =>
566 {
567 let field = unisql_core::target::date_trunc_field(f).unwrap_or_default();
568 let fmt = match field.as_str() {
569 "year" => "%Y-01-01 00:00:00",
570 "month" => "%Y-%m-01 00:00:00",
571 "day" => "%Y-%m-%d 00:00:00",
572 "hour" => "%Y-%m-%d %H:00:00",
573 "minute" => "%Y-%m-%d %H:%M:00",
574 "week" | "quarter" => "",
576 _ => {
577 return Err(ctx.refuse(
578 &format!("fn:date_trunc.{field}"),
579 &format!(
580 "no verified mapping for date_trunc('{field}', ..) on SQLite yet"
581 ),
582 &["truncate in the application"],
583 ));
584 }
585 };
586 ctx.note(
587 format!("fn:date_trunc.{field}"),
588 Tier::Conditional,
589 "strftime cuts the timestamp text; the result is text",
590 Some(Allowance::TimestampAsText),
591 )?;
592 let ts = &args[1];
593 Ok(match field.as_str() {
594 "week" => format!(
595 "strftime('%Y-%m-%d 00:00:00', {ts}, '-' || ((CAST(strftime('%w', {ts}) AS INTEGER) + 6) % 7) || ' days')"
596 ),
597 "quarter" => format!(
598 "(strftime('%Y-', {ts}) || printf('%02d', (CAST(strftime('%m', {ts}) AS INTEGER) + 2) / 3 * 3 - 2) || '-01 00:00:00')"
599 ),
600 _ => format!("strftime('{fmt}', {ts})"),
601 })
602 }
603 "gen_random_uuid" => {
605 ctx.note(
606 "fn:gen_random_uuid",
607 Tier::Emulated,
608 "assembled from randomblob(): version 4, variant 10xx",
609 None,
610 )?;
611 Ok(
612 "lower(hex(randomblob(4)) || '-' || hex(randomblob(2)) || '-4' || \
613 substr(hex(randomblob(2)), 2) || '-' || \
614 substr('89ab', 1 + (abs(random()) % 4), 1) || \
615 substr(hex(randomblob(2)), 2) || '-' || hex(randomblob(6)))"
616 .to_string(),
617 )
618 }
619 "now" => {
620 ctx.note(
621 "fn:now",
622 Tier::Conditional,
623 "-> CURRENT_TIMESTAMP; text 'YYYY-MM-DD HH:MM:SS' in UTC, not a timestamptz",
624 Some(Allowance::NowAsText),
625 )?;
626 Ok("CURRENT_TIMESTAMP".to_string())
627 }
628 other => Err(ctx.refuse(
629 &format!("fn:{other}"),
630 "no verified mapping for this function on SQLite yet",
631 &[
632 "add a mapping with a differential test",
633 "use a raw(sqlite, ..) fragment",
634 ],
635 )),
636 }
637 }
638
639 fn cast(&self, expr: &str, ty: &SqlType, ctx: &mut Ctx) -> R<String> {
640 if let SqlType::Varchar(Some(n)) = ty {
642 ctx.note(
643 "cast.to_text",
644 Tier::Emulated,
645 "substr(CAST(x AS TEXT), 1, n): SQLite has no length-limited cast",
646 None,
647 )?;
648 return Ok(format!("SUBSTR(CAST({expr} AS TEXT), 1, {n})"));
649 }
650 let name = match ty {
651 SqlType::SmallInt | SqlType::Integer | SqlType::BigInt => "INTEGER",
652 SqlType::Real | SqlType::Double => "REAL",
653 SqlType::Numeric { .. } => "NUMERIC",
654 SqlType::Text | SqlType::Varchar(_) => "TEXT",
655 SqlType::Timestamp { with_tz: false } => {
659 ctx.note(
660 "cast.to_timestamp",
661 Tier::Conditional,
662 "a timestamp is text on SQLite: the cast keeps the text",
663 Some(Allowance::TimestampAsText),
664 )?;
665 ctx.note(
666 "cast.to_timestamp",
667 Tier::Conditional,
668 "SQLite casts leniently: a malformed value is kept instead of raising an error",
669 Some(Allowance::LenientCast),
670 )?;
671 return Ok(format!("CAST({expr} AS TEXT)"));
672 }
673 other => {
674 return Err(ctx.refuse(
675 &format!("cast.to_{}", other.leaf()),
676 &format!("CAST to {other:?} has no SQLite equivalent that preserves meaning"),
677 &["store as TEXT/INTEGER and convert in the application"],
678 ));
679 }
680 };
681 ctx.note(
682 format!("cast.to_{}", ty.leaf()),
683 Tier::Conditional,
684 "SQLite casts leniently: a malformed value becomes 0 or a numeric prefix instead of an error",
685 Some(Allowance::LenientCast),
686 )?;
687 Ok(format!("CAST({expr} AS {name})"))
688 }
689
690 fn group_by_rollup(&self, _keys: &[String], ctx: &mut Ctx) -> R<String> {
691 Err(ctx.refuse(
692 "group_by.rollup",
693 "SQLite has no ROLLUP",
694 &["UNION ALL one GROUP BY per key prefix (not emulated)"],
695 ))
696 }
697
698 fn distinct_on(&self, ctx: &mut Ctx) -> R<()> {
699 Err(ctx.refuse(
700 "distinct_on",
701 "SQLite has no DISTINCT ON",
702 &["rewrite with row_number() OVER (PARTITION BY ..) in a subquery (not yet emulated)"],
703 ))
704 }
705
706 fn row_lock(&self, _lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
707 Err(ctx.refuse(
708 unisql_core::target::row_lock_leaf(_lock),
709 "SQLite has no row-level locks (it locks the whole database)",
710 &["use BEGIN IMMEDIATE for a write transaction"],
711 ))
712 }
713
714 fn at_time_zone(&self, ctx: &mut Ctx) -> R<()> {
715 Err(ctx.refuse(
716 "at_time_zone",
717 "SQLite has no time zones: its datetimes are text in UTC",
718 &["convert in the application, or store UTC"],
719 ))
720 }
721
722 fn array_subquery(&self, ctx: &mut Ctx) -> R<()> {
723 Err(ctx.refuse(
724 "array_subquery",
725 "SQLite has no array type",
726 &["select the rows and collect them in the application"],
727 ))
728 }
729
730 fn null_safe_eq(&self, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
731 ctx.note(
732 "null_safe_eq",
733 Tier::Exact,
734 "SQLite `IS` compares like `<=>`",
735 None,
736 )?;
737 Ok(format!("{lhs} IS {rhs}"))
738 }
739
740 fn extract(&self, field: &str, expr: &str, interval: bool, ctx: &mut Ctx) -> R<String> {
745 let leaf = unisql_core::target::extract_leaf(field, interval);
746 let derived = match field {
747 "dow" => Some(format!("CAST(strftime('%w', {expr}) AS INTEGER)")),
748 "isodow" => Some(format!(
749 "((CAST(strftime('%w', {expr}) AS INTEGER) + 6) % 7 + 1)"
750 )),
751 "doy" => Some(format!("CAST(strftime('%j', {expr}) AS INTEGER)")),
752 "quarter" => Some(format!(
753 "((CAST(strftime('%m', {expr}) AS INTEGER) + 2) / 3)"
754 )),
755 "week" => Some(format!(
756 "((CAST(strftime('%j', date({expr}, 'weekday 0', '-3 days')) AS INTEGER) - 1) / 7 + 1)"
757 )),
758 _ => None,
759 };
760 if let Some(sql) = derived {
761 ctx.note(
762 leaf,
763 Tier::Conditional,
764 "the field is derived from the timestamp's text (YYYY-MM-DD HH:MM:SS, UTC)",
765 Some(Allowance::TimestampAsText),
766 )?;
767 return Ok(sql);
768 }
769 let fmt = match field {
770 "year" => "%Y",
771 "month" => "%m",
772 "day" => "%d",
773 "hour" => "%H",
774 "minute" => "%M",
775 "epoch" if !interval => "%s",
776 _ => {
777 return Err(ctx.refuse(
778 &leaf,
779 &format!("SQLite: no verified mapping for EXTRACT({field} ..) yet"),
780 &["compute the field in the application"],
781 ));
782 }
783 };
784 if fmt == "%s" {
785 ctx.note(
786 leaf,
787 Tier::Conditional,
788 "strftime('%s') gives whole seconds; PostgreSQL's epoch has the fraction",
789 Some(Allowance::EpochWholeSeconds),
790 )?;
791 } else {
792 ctx.note(
793 leaf,
794 Tier::Conditional,
795 "the field is read from the timestamp's text (YYYY-MM-DD HH:MM:SS, UTC)",
796 Some(Allowance::TimestampAsText),
797 )?;
798 }
799 Ok(format!("CAST(strftime('{fmt}', {expr}) AS INTEGER)"))
800 }
801
802 fn epoch_of_clock(&self, ctx: &mut Ctx) -> R<String> {
805 ctx.note(
806 "extract.epoch",
807 Tier::Conditional,
808 "unixepoch('now','subsec') needs SQLite 3.42 or later and is read once per statement, where clock_timestamp() is read at every call",
809 Some(Allowance::ClockIsStatementStart),
810 )?;
811 Ok("unixepoch('now', 'subsec')".to_string())
812 }
813
814 fn epoch_of_difference(&self, a: &str, b: &str, ctx: &mut Ctx) -> R<Option<String>> {
816 ctx.note(
817 "extract.epoch.interval",
818 Tier::Conditional,
819 "whole seconds between the two timestamp texts (strftime('%s'))",
820 Some(Allowance::EpochWholeSeconds),
821 )?;
822 Ok(Some(format!(
823 "(CAST(strftime('%s', {a}) AS INTEGER) - CAST(strftime('%s', {b}) AS INTEGER))"
824 )))
825 }
826
827 fn array_literal(&self, _items: &[String], ctx: &mut Ctx) -> R<String> {
828 Err(ctx.refuse(
829 "array_literal",
830 "SQLite has no array type",
831 &["use an IN (..) list, or a JSON array"],
832 ))
833 }
834
835 fn series_as_recursive_cte(&self) -> bool {
836 true
837 }
838
839 fn table_function(&self, name: &str, ctx: &mut Ctx) -> R<()> {
840 Err(ctx.refuse(
841 &format!("table_function.{name}"),
842 &format!("SQLite has no verified mapping for the table-valued function {name}()"),
843 &["generate the rows in the application, or use a recursive CTE for generate_series"],
844 ))
845 }
846
847 fn data_modifying_cte(&self, ctx: &mut Ctx) -> R<()> {
848 Err(ctx.refuse(
849 "cte.data_modifying",
850 "SQLite has no data-modifying CTE (WITH x AS (INSERT/UPDATE/DELETE ..)): probed, a syntax error",
851 &["run the statements separately in one transaction"],
852 ))
853 }
854
855 fn returning(&self, _kind: StmtKind, ctx: &mut Ctx) -> R<()> {
856 ctx.note("returning", Tier::Exact, "requires SQLite >= 3.35", None)
857 }
858
859 fn replace_keyword(&self) -> Option<&'static str> {
860 Some("INSERT OR REPLACE INTO")
861 }
862
863 fn upsert_clause(
864 &self,
865 conflict_cols: &[String],
866 do_nothing: bool,
867 set: &str,
868 where_: Option<&str>,
869 _first_insert_col: &str,
870 ctx: &mut Ctx,
871 ) -> R<String> {
872 if !do_nothing && conflict_cols.is_empty() {
873 return Err(ctx.refuse(
874 "upsert.no_conflict_key",
875 "the source upsert names no conflict key (MySQL ON DUPLICATE KEY UPDATE fires on any unique key); SQLite needs the key columns, and the schema does not state exactly one unique key for the table",
876 &["state the conflict key columns in the statement", "or give the schema the table's unique key (Schema::with_unique_key, or schema_from_ddl)"],
877 ));
878 }
879 ctx.note(
880 if where_.is_some() {
881 "upsert_where"
882 } else {
883 "upsert"
884 },
885 Tier::Exact,
886 "requires SQLite >= 3.24",
887 None,
888 )?;
889 let mut s = String::from(" ON CONFLICT");
890 if !conflict_cols.is_empty() {
891 s.push_str(&format!(" ({})", conflict_cols.join(", ")));
892 }
893 if do_nothing {
894 s.push_str(" DO NOTHING");
895 } else {
896 s.push_str(&format!(" DO UPDATE SET {set}"));
897 if let Some(w) = where_ {
898 s.push_str(&format!(" WHERE {w}"));
899 }
900 }
901 Ok(s)
902 }
903
904 fn dml_limit(&self) -> DmlLimit {
905 DmlLimit::RowIdSubquery("rowid")
906 }
907
908 fn dml_sources(&self) -> DmlSources {
909 DmlSources::UpdateFromOnly
910 }
911
912 fn limit_offset(&self, limit: Option<&str>, offset: Option<&str>, ctx: &mut Ctx) -> R<String> {
913 match (limit, offset) {
914 (None, None) => Ok(String::new()),
915 (Some(l), None) => {
916 ctx.note("limit", Tier::Exact, "", None)?;
917 Ok(format!(" LIMIT {l}"))
918 }
919 (Some(l), Some(o)) => {
920 ctx.note("limit", Tier::Exact, "", None)?;
921 ctx.note("offset", Tier::Exact, "", None)?;
922 Ok(format!(" LIMIT {l} OFFSET {o}"))
923 }
924 (None, Some(o)) => {
925 ctx.note(
926 "offset",
927 Tier::Emulated,
928 "SQLite requires LIMIT with OFFSET; -1 means unlimited",
929 None,
930 )?;
931 Ok(format!(" LIMIT -1 OFFSET {o}"))
932 }
933 }
934 }
935
936 fn array_membership(
937 &self,
938 lhs: &str,
939 ph: &str,
940 negated: bool,
941 n: u32,
942 ctx: &mut Ctx,
943 ) -> R<String> {
944 ctx.note(
945 "array_param",
946 Tier::Conditional,
947 "bind the array as JSON text; membership via json_each(). A NULL array reads as empty",
948 Some(Allowance::ArrayNullSemantics),
949 )?;
950 ctx.bind_array_param(n, ParamBinding::JsonArrayText);
951 let not = if negated { "NOT " } else { "" };
952 Ok(format!("{lhs} {not}IN (SELECT value FROM json_each({ph}))"))
953 }
954
955 fn between(&self, numeric: bool, ctx: &mut Ctx) -> R<()> {
956 if numeric {
957 return ctx.note("ordered_comparison", Tier::Exact, "numeric operand", None);
958 }
959 ctx.note(
960 "ordered_comparison",
961 Tier::Conditional,
962 "text comparison follows the target's collation (BINARY by default)",
963 Some(Allowance::TextCollation),
964 )
965 }
966
967 fn binary_op(&self, op: BinaryOp, numeric: bool, ctx: &mut Ctx) -> R<()> {
968 if matches!(
969 op,
970 BinaryOp::BitAnd
971 | BinaryOp::BitOr
972 | BinaryOp::BitXor
973 | BinaryOp::ShiftLeft
974 | BinaryOp::ShiftRight
975 ) {
976 if ctx.source == "sqlite" {
977 return ctx.note("bitwise", Tier::Exact, "", None);
978 }
979 if op == BinaryOp::BitXor {
980 return Err(ctx.refuse(
981 "bitwise.xor",
982 "SQLite has no bitwise XOR operator (it would need the operands written twice)",
983 &["(a | b) - (a & b) with simple operands"],
984 ));
985 }
986 return ctx.note(
987 "bitwise",
988 Tier::Conditional,
989 "MySQL bitwise operators work on unsigned 64-bit integers, PostgreSQL and SQLite on signed ones: exact only for non-negative operands and shift counts below the integer width",
990 Some(Allowance::BitwiseNonNegativeIntegers),
991 );
992 }
993 if op == BinaryOp::Xor {
994 return ctx.note(
995 "xor",
996 Tier::Conditional,
997 "XOR is written as <>, which compares truth values only when both operands are booleans or 0/1 comparison results",
998 Some(Allowance::XorOperandsBoolean),
999 );
1000 }
1001 match op {
1002 BinaryOp::IntDivide => ctx.note(
1003 "division_integer",
1004 Tier::Conditional,
1005 "DIV becomes `/`, which is integer division only if both operands are integers",
1006 Some(Allowance::IntegerDivisionAssumed),
1007 ),
1008 BinaryOp::Eq | BinaryOp::NotEq if !numeric && matches!(ctx.source, "mysql" | "mariadb") => ctx.note(
1009 "text_comparison",
1010 Tier::Conditional,
1011 "text equality follows the source column collation; SQLite compares bytes (BINARY)",
1012 Some(Allowance::TextCollation),
1013 ),
1014 BinaryOp::Divide | BinaryOp::Modulo => ctx.note(
1015 "division",
1016 Tier::Conditional,
1017 "division/modulo by zero is NULL on SQLite (an error on PostgreSQL)",
1018 Some(Allowance::DivisionByZeroIsNull),
1019 ),
1020 BinaryOp::Lt | BinaryOp::LtEq | BinaryOp::Gt | BinaryOp::GtEq if numeric => {
1021 ctx.note("ordered_comparison", Tier::Exact, "numeric operand", None)
1022 }
1023 BinaryOp::Lt | BinaryOp::LtEq | BinaryOp::Gt | BinaryOp::GtEq => ctx.note(
1024 "ordered_comparison",
1025 Tier::Conditional,
1026 "text comparison follows the target's collation (BINARY by default)",
1027 Some(Allowance::TextCollation),
1028 ),
1029 _ => Ok(()),
1030 }
1031 }
1032
1033 fn nulls_order(&self, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
1034 if ctx.order_non_text {
1035 ctx.note("order_by", Tier::Exact, "non-text column", None)?;
1036 } else {
1037 ctx.note(
1038 "order_by",
1039 Tier::Conditional,
1040 "text ordering follows the target's collation (BINARY by default)",
1041 Some(Allowance::TextCollation),
1042 )?;
1043 }
1044 let default_first = !desc;
1046 if nulls_first == default_first {
1047 ctx.note("null_ordering", Tier::Exact, "", None)?;
1048 Ok(String::new())
1049 } else {
1050 ctx.note(
1051 "null_ordering",
1052 Tier::Emulated,
1053 "explicit NULLS FIRST/LAST (SQLite >= 3.30) to keep PostgreSQL's NULL order",
1054 None,
1055 )?;
1056 Ok(if nulls_first {
1057 " NULLS FIRST"
1058 } else {
1059 " NULLS LAST"
1060 }
1061 .to_string())
1062 }
1063 }
1064}