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 json_path_access(&self, text: bool, _lhs: &str, _rhs: &str, ctx: &mut Ctx) -> R<String> {
227 let leaf = if text { "json_path_text" } else { "json_path" };
228 Err(ctx.refuse(
229 leaf,
230 "SQLite has no text-array path operator; its -> takes a '$.a.b' path, not a PostgreSQL '{a,b}' array",
231 &["chain -> with literal keys: doc -> 'a' -> 'b'"],
232 ))
233 }
234
235 fn function(&self, f: &Function, args: &[String], ctx: &mut Ctx) -> R<String> {
236 let n = f.name.as_str();
237 if n == "current_date" {
238 if ctx.source == "sqlite" {
239 ctx.note("fn:current_date", Tier::Exact, "", None)?;
240 } else {
241 ctx.note(
242 "fn:current_date",
243 Tier::Conditional,
244 "-> CURRENT_DATE; text 'YYYY-MM-DD' of the UTC date, not a date in the session time zone",
245 Some(Allowance::DateAsText),
246 )?;
247 }
248 return Ok("CURRENT_DATE".to_string());
249 }
250 if ctx.source == "sqlite" {
251 if n == "now" {
252 ctx.note("fn:now", Tier::Exact, "", None)?;
254 return Ok("CURRENT_TIMESTAMP".to_string());
255 }
256 if n == "strpos" && args.len() == 2 {
258 ctx.note("fn:strpos", Tier::Exact, "", None)?;
259 return Ok(format!("instr({}, {})", args[0], args[1]));
260 }
261 ctx.note(format!("fn:{n}"), Tier::Exact, "", None)?;
263 let order = ctx.agg_order.take();
264 return Ok(generic_call_ordered(
265 n,
266 args,
267 f.distinct,
268 f.star,
269 order.as_deref(),
270 ));
271 }
272 match n {
273 "utc_timestamp" => {
274 let (text, allow2) = match unisql_core::target::utc_timestamp_precision(f) {
275 Some(0) => ("datetime('now')", None),
276 Some(6) => (
277 "strftime('%Y-%m-%d %H:%M:%f', 'now')",
278 Some(Allowance::TimestampMillisecondResolution),
279 ),
280 _ => {
281 return Err(ctx.refuse(
282 "fn:utc_timestamp.precision",
283 "only UTC_TIMESTAMP() and UTC_TIMESTAMP(6) are verified",
284 &["use UTC_TIMESTAMP() or UTC_TIMESTAMP(6)"],
285 ));
286 }
287 };
288 ctx.note(
289 "fn:utc_timestamp",
290 Tier::Conditional,
291 "text 'YYYY-MM-DD HH:MM:SS[.fff]' in UTC, not a timestamp type",
292 Some(Allowance::TimestampAsText),
293 )?;
294 if let Some(a) = allow2 {
295 ctx.note(
296 "fn:utc_timestamp",
297 Tier::Conditional,
298 "SQLite's %f has millisecond resolution; MySQL's UTC_TIMESTAMP(6) has microseconds",
299 Some(a),
300 )?;
301 }
302 return Ok(text.to_string());
303 }
304 "utc_date" if args.is_empty() => {
305 ctx.note(
306 "fn:utc_date",
307 Tier::Conditional,
308 "text 'YYYY-MM-DD' of the UTC date, not a date type",
309 Some(Allowance::DateAsText),
310 )?;
311 return Ok("date('now')".to_string());
312 }
313 "datediff" if args.len() == 2 => {
314 ctx.note(
315 "fn:datediff",
316 Tier::Conditional,
317 "operands are timestamp text; whole days between their date parts",
318 Some(Allowance::TimestampAsText),
319 )?;
320 return Ok(format!(
321 "CAST(julianday(date({})) - julianday(date({})) AS INTEGER)",
322 args[0], args[1]
323 ));
324 }
325 "concat_ws" if args.len() >= 2 => {
326 ctx.note("fn:concat_ws", Tier::Exact, "requires SQLite >= 3.44", None)?;
327 return Ok(format!("concat_ws({})", args.join(", ")));
328 }
329 "left" if args.len() == 2 && unisql_core::target::literal_count(f, 1).is_some() => {
330 ctx.note("fn:left", Tier::Exact, "-> substr(s, 1, n)", None)?;
331 return Ok(format!("substr({}, 1, {})", args[0], args[1]));
332 }
333 "left" if args.len() == 2 => {
334 return Err(ctx.refuse(
335 "fn:left.length",
336 "LEFT(s, n) is mapped only for a literal n >= 0",
337 &["use a literal non-negative count"],
338 ));
339 }
340 "right" if args.len() == 2 => {
341 return match unisql_core::target::literal_count(f, 1) {
342 Some(0) => {
343 ctx.note("fn:right", Tier::Exact, "-> substr(s, 1, 0)", None)?;
344 Ok(format!("substr({}, 1, 0)", args[0]))
345 }
346 Some(_) => {
347 ctx.note("fn:right", Tier::Exact, "-> substr(s, -n)", None)?;
348 Ok(format!("substr({}, -{})", args[0], args[1]))
349 }
350 None => Err(ctx.refuse(
351 "fn:right.length",
352 "RIGHT(s, n) is mapped only for a literal n >= 0",
353 &["use a literal non-negative count"],
354 )),
355 };
356 }
357 "repeat" if args.len() == 2 && unisql_core::target::literal_count(f, 1).is_some() => {
358 ctx.note(
359 "fn:repeat",
360 Tier::Emulated,
361 "-> replace(hex(zeroblob(n)), '00', s)",
362 None,
363 )?;
364 return Ok(format!(
365 "replace(hex(zeroblob({})), '00', {})",
366 args[1], args[0]
367 ));
368 }
369 "date" if args.len() == 1 => {
370 ctx.note(
371 "fn:date",
372 Tier::Conditional,
373 "text 'YYYY-MM-DD', not a date type",
374 Some(Allowance::DateAsText),
375 )?;
376 return Ok(format!("date({})", args[0]));
377 }
378 _ => {}
379 }
380 if f.over.is_some()
381 && matches!(
382 n,
383 "row_number"
384 | "rank"
385 | "dense_rank"
386 | "percent_rank"
387 | "cume_dist"
388 | "ntile"
389 | "lag"
390 | "lead"
391 | "first_value"
392 | "last_value"
393 | "nth_value"
394 )
395 {
396 ctx.note(format!("fn:{n}"), Tier::Exact, "window function", None)?;
397 return Ok(generic_call(n, args, false, false));
398 }
399 match n {
400 "md5" | "sha256" | "sha1" | "sha512" | "encode" | "decode" | "convert_to"
401 | "convert_from" => {
402 return Err(ctx.refuse(
403 &format!("fn:{n}"),
404 "SQLite has no built-in hashing/encoding functions; the result would depend on a \
405 host-registered function or extension, which UniSQL cannot assume",
406 &["hash in the application", "register the function and use a raw(sqlite, ..) fragment"],
407 ));
408 }
409 "current_schema" | "current_database" | "current_user" | "session_user"
410 | "to_regclass" | "pg_backend_pid" | "set_config" | "current_setting" => {
411 return Err(ctx.refuse(
412 &format!("fn:{n}"),
413 "PostgreSQL catalog/session introspection has no SQLite equivalent",
414 &["query sqlite_schema (a different, SQLite-specific statement)"],
415 ));
416 }
417 "make_interval" => {
418 return Err(ctx.refuse(
419 "fn:make_interval.standalone",
420 "SQLite has no interval type; only `timestamp +/- make_interval(secs|mins|hours|days|weeks => ..)` is translated",
421 &[],
422 ));
423 }
424 "regexp_replace" | "regexp_match" | "regexp_matches" | "split_part" => {
425 return Err(ctx.refuse(
426 &format!("fn:{n}"),
427 "no built-in regular-expression or split function in SQLite",
428 &[],
429 ));
430 }
431 _ => {}
432 }
433 match n {
434 "ceil" | "floor" => Err(ctx.refuse(
437 &format!("fn:{n}"),
438 "SQLite's ceil/floor exist only when it is built with its math functions",
439 &["round in the application"],
440 )),
441 "strpos" if args.len() == 2 => {
442 ctx.note("fn:strpos", Tier::Exact, "-> instr(s, sub)", None)?;
443 Ok(format!("instr({}, {})", args[0], args[1]))
444 }
445 "min" | "max" => {
446 ctx.note(
447 format!("fn:{n}"),
448 Tier::Conditional,
449 "on text, follows the target's collation (BINARY by default)",
450 Some(Allowance::TextCollation),
451 )?;
452 Ok(generic_call(n, args, f.distinct, f.star))
453 }
454 "count" | "sum" | "avg" | "coalesce" | "nullif" | "abs" | "length" | "replace"
455 | "trim" | "ltrim" | "rtrim" | "substr" | "ifnull" => {
456 ctx.note(format!("fn:{n}"), Tier::Exact, "", None)?;
457 Ok(generic_call(n, args, f.distinct, f.star))
458 }
459 "lower" | "upper" => {
460 ctx.note(
461 format!("fn:{n}"),
462 Tier::Conditional,
463 "SQLite folds ASCII only",
464 Some(Allowance::AsciiOnlyCaseFolding),
465 )?;
466 Ok(generic_call(n, args, false, false))
467 }
468 "btrim" => {
469 ctx.note("fn:btrim", Tier::Emulated, "-> trim(x[, chars])", None)?;
470 Ok(generic_call("trim", args, false, false))
471 }
472 "octet_length" => {
473 if args.len() != 1 {
474 return Err(ctx.refuse(
475 "fn:octet_length",
476 "octet_length takes one argument",
477 &[],
478 ));
479 }
480 ctx.note(
481 "fn:octet_length",
482 Tier::Emulated,
483 "-> length(CAST(x AS BLOB)): bytes, not characters",
484 None,
485 )?;
486 Ok(format!("LENGTH(CAST({} AS BLOB))", args[0]))
487 }
488 "char_length" | "character_length" => {
489 ctx.note(format!("fn:{n}"), Tier::Emulated, "-> length()", None)?;
490 Ok(generic_call("length", args, false, false))
491 }
492 "string_agg" => {
493 if args.len() != 2 {
494 return Err(ctx.refuse(
495 "fn:string_agg",
496 "string_agg needs exactly (value, separator)",
497 &[],
498 ));
499 }
500 ctx.note(
501 "fn:string_agg",
502 Tier::Emulated,
503 "-> group_concat(value, separator); an ORDER BY inside needs SQLite >= 3.44",
504 None,
505 )?;
506 let order = ctx.agg_order.take();
507 let args = if f.distinct {
509 if args[1] != "','" {
510 return Err(ctx.refuse(
511 "fn:string_agg",
512 "SQLite group_concat(DISTINCT ..) cannot take a separator",
513 &["aggregate without DISTINCT, or use the default ',' separator"],
514 ));
515 }
516 &args[..1]
517 } else {
518 args
519 };
520 Ok(generic_call_ordered(
521 "group_concat",
522 args,
523 f.distinct,
524 false,
525 order.as_deref(),
526 ))
527 }
528 "to_timestamp" if args.len() == 1 => {
530 ctx.note(
531 "fn:to_timestamp",
532 Tier::Conditional,
533 "datetime(x, 'unixepoch'): text YYYY-MM-DD HH:MM:SS in UTC",
534 Some(Allowance::TimestampAsText),
535 )?;
536 ctx.note(
537 "fn:to_timestamp",
538 Tier::Conditional,
539 "a fraction of a second is dropped",
540 Some(Allowance::TimestampWholeSeconds),
541 )?;
542 Ok(format!("datetime({}, 'unixepoch')", args[0]))
543 }
544 "age" => Err(ctx.refuse(
547 "fn:age",
548 "age() returns a calendar interval (years, months, days); SQLite has no interval value",
549 &["compute the difference in the application, or use EXTRACT(EPOCH FROM a - b)"],
550 )),
551 "to_char"
553 if unisql_core::target::to_char_format(f, ["%Y", "%m", "%d", "%H", "%M", "%S"])
554 .is_some() =>
555 {
556 let fmt =
557 unisql_core::target::to_char_format(f, ["%Y", "%m", "%d", "%H", "%M", "%S"])
558 .unwrap_or_default();
559 ctx.note(
560 "fn:to_char",
561 Tier::Conditional,
562 "strftime formats the timestamp text; the result is text",
563 Some(Allowance::TimestampAsText),
564 )?;
565 Ok(format!("strftime('{fmt}', {})", args[0]))
566 }
567 "to_char" => Err(ctx.refuse(
568 "fn:to_char.format",
569 "to_char: only literal formats of YYYY, MM, DD, HH24, MI, SS and - / : . , space are mapped",
570 &["format in the application"],
571 )),
572 "date_trunc"
574 if args.len() == 2 && unisql_core::target::date_trunc_field(f).is_some() =>
575 {
576 let field = unisql_core::target::date_trunc_field(f).unwrap_or_default();
577 let fmt = match field.as_str() {
578 "year" => "%Y-01-01 00:00:00",
579 "month" => "%Y-%m-01 00:00:00",
580 "day" => "%Y-%m-%d 00:00:00",
581 "hour" => "%Y-%m-%d %H:00:00",
582 "minute" => "%Y-%m-%d %H:%M:00",
583 "week" | "quarter" => "",
585 _ => {
586 return Err(ctx.refuse(
587 &format!("fn:date_trunc.{field}"),
588 &format!(
589 "no verified mapping for date_trunc('{field}', ..) on SQLite yet"
590 ),
591 &["truncate in the application"],
592 ));
593 }
594 };
595 ctx.note(
596 format!("fn:date_trunc.{field}"),
597 Tier::Conditional,
598 "strftime cuts the timestamp text; the result is text",
599 Some(Allowance::TimestampAsText),
600 )?;
601 let ts = &args[1];
602 Ok(match field.as_str() {
603 "week" => format!(
604 "strftime('%Y-%m-%d 00:00:00', {ts}, '-' || ((CAST(strftime('%w', {ts}) AS INTEGER) + 6) % 7) || ' days')"
605 ),
606 "quarter" => format!(
607 "(strftime('%Y-', {ts}) || printf('%02d', (CAST(strftime('%m', {ts}) AS INTEGER) + 2) / 3 * 3 - 2) || '-01 00:00:00')"
608 ),
609 _ => format!("strftime('{fmt}', {ts})"),
610 })
611 }
612 "gen_random_uuid" => {
614 ctx.note(
615 "fn:gen_random_uuid",
616 Tier::Emulated,
617 "assembled from randomblob(): version 4, variant 10xx",
618 None,
619 )?;
620 Ok(
621 "lower(hex(randomblob(4)) || '-' || hex(randomblob(2)) || '-4' || \
622 substr(hex(randomblob(2)), 2) || '-' || \
623 substr('89ab', 1 + (abs(random()) % 4), 1) || \
624 substr(hex(randomblob(2)), 2) || '-' || hex(randomblob(6)))"
625 .to_string(),
626 )
627 }
628 "now" => {
629 ctx.note(
630 "fn:now",
631 Tier::Conditional,
632 "-> CURRENT_TIMESTAMP; text 'YYYY-MM-DD HH:MM:SS' in UTC, not a timestamptz",
633 Some(Allowance::NowAsText),
634 )?;
635 Ok("CURRENT_TIMESTAMP".to_string())
636 }
637 other => Err(ctx.refuse(
638 &format!("fn:{other}"),
639 "no verified mapping for this function on SQLite yet",
640 &[
641 "add a mapping with a differential test",
642 "use a raw(sqlite, ..) fragment",
643 ],
644 )),
645 }
646 }
647
648 fn cast(&self, expr: &str, ty: &SqlType, ctx: &mut Ctx) -> R<String> {
649 if let SqlType::Varchar(Some(n)) = ty {
651 ctx.note(
652 "cast.to_text",
653 Tier::Emulated,
654 "substr(CAST(x AS TEXT), 1, n): SQLite has no length-limited cast",
655 None,
656 )?;
657 return Ok(format!("SUBSTR(CAST({expr} AS TEXT), 1, {n})"));
658 }
659 let name = match ty {
660 SqlType::SmallInt | SqlType::Integer | SqlType::BigInt => "INTEGER",
661 SqlType::Real | SqlType::Double => "REAL",
662 SqlType::Numeric { .. } => "NUMERIC",
663 SqlType::Text | SqlType::Varchar(_) => "TEXT",
664 SqlType::Timestamp { with_tz: false } => {
668 ctx.note(
669 "cast.to_timestamp",
670 Tier::Conditional,
671 "a timestamp is text on SQLite: the cast keeps the text",
672 Some(Allowance::TimestampAsText),
673 )?;
674 ctx.note(
675 "cast.to_timestamp",
676 Tier::Conditional,
677 "SQLite casts leniently: a malformed value is kept instead of raising an error",
678 Some(Allowance::LenientCast),
679 )?;
680 return Ok(format!("CAST({expr} AS TEXT)"));
681 }
682 other => {
683 return Err(ctx.refuse(
684 &format!("cast.to_{}", other.leaf()),
685 &format!("CAST to {other:?} has no SQLite equivalent that preserves meaning"),
686 &["store as TEXT/INTEGER and convert in the application"],
687 ));
688 }
689 };
690 ctx.note(
691 format!("cast.to_{}", ty.leaf()),
692 Tier::Conditional,
693 "SQLite casts leniently: a malformed value becomes 0 or a numeric prefix instead of an error",
694 Some(Allowance::LenientCast),
695 )?;
696 Ok(format!("CAST({expr} AS {name})"))
697 }
698
699 fn group_by_rollup(&self, _keys: &[String], ctx: &mut Ctx) -> R<String> {
700 Err(ctx.refuse(
701 "group_by.rollup",
702 "SQLite has no ROLLUP",
703 &["UNION ALL one GROUP BY per key prefix (not emulated)"],
704 ))
705 }
706
707 fn distinct_on(&self, ctx: &mut Ctx) -> R<()> {
708 Err(ctx.refuse(
709 "distinct_on",
710 "SQLite has no DISTINCT ON",
711 &["rewrite with row_number() OVER (PARTITION BY ..) in a subquery (not yet emulated)"],
712 ))
713 }
714
715 fn row_lock(&self, _lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
716 Err(ctx.refuse(
717 unisql_core::target::row_lock_leaf(_lock),
718 "SQLite has no row-level locks (it locks the whole database)",
719 &["use BEGIN IMMEDIATE for a write transaction"],
720 ))
721 }
722
723 fn at_time_zone(&self, ctx: &mut Ctx) -> R<()> {
724 Err(ctx.refuse(
725 "at_time_zone",
726 "SQLite has no time zones: its datetimes are text in UTC",
727 &["convert in the application, or store UTC"],
728 ))
729 }
730
731 fn array_subquery(&self, ctx: &mut Ctx) -> R<()> {
732 Err(ctx.refuse(
733 "array_subquery",
734 "SQLite has no array type",
735 &["select the rows and collect them in the application"],
736 ))
737 }
738
739 fn null_safe_eq(&self, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
740 ctx.note(
741 "null_safe_eq",
742 Tier::Exact,
743 "SQLite `IS` compares like `<=>`",
744 None,
745 )?;
746 Ok(format!("{lhs} IS {rhs}"))
747 }
748
749 fn extract(&self, field: &str, expr: &str, interval: bool, ctx: &mut Ctx) -> R<String> {
754 let leaf = unisql_core::target::extract_leaf(field, interval);
755 let derived = match field {
756 "dow" => Some(format!("CAST(strftime('%w', {expr}) AS INTEGER)")),
757 "isodow" => Some(format!(
758 "((CAST(strftime('%w', {expr}) AS INTEGER) + 6) % 7 + 1)"
759 )),
760 "doy" => Some(format!("CAST(strftime('%j', {expr}) AS INTEGER)")),
761 "quarter" => Some(format!(
762 "((CAST(strftime('%m', {expr}) AS INTEGER) + 2) / 3)"
763 )),
764 "week" => Some(format!(
765 "((CAST(strftime('%j', date({expr}, 'weekday 0', '-3 days')) AS INTEGER) - 1) / 7 + 1)"
766 )),
767 _ => None,
768 };
769 if let Some(sql) = derived {
770 ctx.note(
771 leaf,
772 Tier::Conditional,
773 "the field is derived from the timestamp's text (YYYY-MM-DD HH:MM:SS, UTC)",
774 Some(Allowance::TimestampAsText),
775 )?;
776 return Ok(sql);
777 }
778 let fmt = match field {
779 "year" => "%Y",
780 "month" => "%m",
781 "day" => "%d",
782 "hour" => "%H",
783 "minute" => "%M",
784 "epoch" if !interval => "%s",
785 _ => {
786 return Err(ctx.refuse(
787 &leaf,
788 &format!("SQLite: no verified mapping for EXTRACT({field} ..) yet"),
789 &["compute the field in the application"],
790 ));
791 }
792 };
793 if fmt == "%s" {
794 ctx.note(
795 leaf,
796 Tier::Conditional,
797 "strftime('%s') gives whole seconds; PostgreSQL's epoch has the fraction",
798 Some(Allowance::EpochWholeSeconds),
799 )?;
800 } else {
801 ctx.note(
802 leaf,
803 Tier::Conditional,
804 "the field is read from the timestamp's text (YYYY-MM-DD HH:MM:SS, UTC)",
805 Some(Allowance::TimestampAsText),
806 )?;
807 }
808 Ok(format!("CAST(strftime('{fmt}', {expr}) AS INTEGER)"))
809 }
810
811 fn epoch_of_clock(&self, ctx: &mut Ctx) -> R<String> {
814 ctx.note(
815 "extract.epoch",
816 Tier::Conditional,
817 "unixepoch('now','subsec') needs SQLite 3.42 or later and is read once per statement, where clock_timestamp() is read at every call",
818 Some(Allowance::ClockIsStatementStart),
819 )?;
820 Ok("unixepoch('now', 'subsec')".to_string())
821 }
822
823 fn epoch_of_difference(&self, a: &str, b: &str, ctx: &mut Ctx) -> R<Option<String>> {
825 ctx.note(
826 "extract.epoch.interval",
827 Tier::Conditional,
828 "whole seconds between the two timestamp texts (strftime('%s'))",
829 Some(Allowance::EpochWholeSeconds),
830 )?;
831 Ok(Some(format!(
832 "(CAST(strftime('%s', {a}) AS INTEGER) - CAST(strftime('%s', {b}) AS INTEGER))"
833 )))
834 }
835
836 fn array_literal(&self, _items: &[String], ctx: &mut Ctx) -> R<String> {
837 Err(ctx.refuse(
838 "array_literal",
839 "SQLite has no array type",
840 &["use an IN (..) list, or a JSON array"],
841 ))
842 }
843
844 fn series_as_recursive_cte(&self) -> bool {
845 true
846 }
847
848 fn table_function(&self, name: &str, ctx: &mut Ctx) -> R<()> {
849 Err(ctx.refuse(
850 &format!("table_function.{name}"),
851 &format!("SQLite has no verified mapping for the table-valued function {name}()"),
852 &["generate the rows in the application, or use a recursive CTE for generate_series"],
853 ))
854 }
855
856 fn data_modifying_cte(&self, ctx: &mut Ctx) -> R<()> {
857 Err(ctx.refuse(
858 "cte.data_modifying",
859 "SQLite has no data-modifying CTE (WITH x AS (INSERT/UPDATE/DELETE ..)): probed, a syntax error",
860 &["run the statements separately in one transaction"],
861 ))
862 }
863
864 fn returning(&self, _kind: StmtKind, ctx: &mut Ctx) -> R<()> {
865 ctx.note("returning", Tier::Exact, "requires SQLite >= 3.35", None)
866 }
867
868 fn replace_keyword(&self) -> Option<&'static str> {
869 Some("INSERT OR REPLACE INTO")
870 }
871
872 fn upsert_clause(
873 &self,
874 conflict_cols: &[String],
875 do_nothing: bool,
876 set: &str,
877 where_: Option<&str>,
878 _first_insert_col: &str,
879 ctx: &mut Ctx,
880 ) -> R<String> {
881 if !do_nothing && conflict_cols.is_empty() {
882 return Err(ctx.refuse(
883 "upsert.no_conflict_key",
884 "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",
885 &["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)"],
886 ));
887 }
888 ctx.note(
889 if where_.is_some() {
890 "upsert_where"
891 } else {
892 "upsert"
893 },
894 Tier::Exact,
895 "requires SQLite >= 3.24",
896 None,
897 )?;
898 let mut s = String::from(" ON CONFLICT");
899 if !conflict_cols.is_empty() {
900 s.push_str(&format!(" ({})", conflict_cols.join(", ")));
901 }
902 if do_nothing {
903 s.push_str(" DO NOTHING");
904 } else {
905 s.push_str(&format!(" DO UPDATE SET {set}"));
906 if let Some(w) = where_ {
907 s.push_str(&format!(" WHERE {w}"));
908 }
909 }
910 Ok(s)
911 }
912
913 fn dml_limit(&self) -> DmlLimit {
914 DmlLimit::RowIdSubquery("rowid")
915 }
916
917 fn dml_sources(&self) -> DmlSources {
918 DmlSources::UpdateFromOnly
919 }
920
921 fn limit_offset(&self, limit: Option<&str>, offset: Option<&str>, ctx: &mut Ctx) -> R<String> {
922 match (limit, offset) {
923 (None, None) => Ok(String::new()),
924 (Some(l), None) => {
925 ctx.note("limit", Tier::Exact, "", None)?;
926 Ok(format!(" LIMIT {l}"))
927 }
928 (Some(l), Some(o)) => {
929 ctx.note("limit", Tier::Exact, "", None)?;
930 ctx.note("offset", Tier::Exact, "", None)?;
931 Ok(format!(" LIMIT {l} OFFSET {o}"))
932 }
933 (None, Some(o)) => {
934 ctx.note(
935 "offset",
936 Tier::Emulated,
937 "SQLite requires LIMIT with OFFSET; -1 means unlimited",
938 None,
939 )?;
940 Ok(format!(" LIMIT -1 OFFSET {o}"))
941 }
942 }
943 }
944
945 fn array_membership(
946 &self,
947 lhs: &str,
948 ph: &str,
949 negated: bool,
950 n: u32,
951 ctx: &mut Ctx,
952 ) -> R<String> {
953 ctx.note(
954 "array_param",
955 Tier::Conditional,
956 "bind the array as JSON text; membership via json_each(). A NULL array reads as empty",
957 Some(Allowance::ArrayNullSemantics),
958 )?;
959 ctx.bind_array_param(n, ParamBinding::JsonArrayText);
960 let not = if negated { "NOT " } else { "" };
961 Ok(format!("{lhs} {not}IN (SELECT value FROM json_each({ph}))"))
962 }
963
964 fn between(&self, numeric: bool, ctx: &mut Ctx) -> R<()> {
965 if numeric {
966 return ctx.note("ordered_comparison", Tier::Exact, "numeric operand", None);
967 }
968 ctx.note(
969 "ordered_comparison",
970 Tier::Conditional,
971 "text comparison follows the target's collation (BINARY by default)",
972 Some(Allowance::TextCollation),
973 )
974 }
975
976 fn binary_op(&self, op: BinaryOp, numeric: bool, ctx: &mut Ctx) -> R<()> {
977 if matches!(
978 op,
979 BinaryOp::BitAnd
980 | BinaryOp::BitOr
981 | BinaryOp::BitXor
982 | BinaryOp::ShiftLeft
983 | BinaryOp::ShiftRight
984 ) {
985 if ctx.source == "sqlite" {
986 return ctx.note("bitwise", Tier::Exact, "", None);
987 }
988 if op == BinaryOp::BitXor {
989 return Err(ctx.refuse(
990 "bitwise.xor",
991 "SQLite has no bitwise XOR operator (it would need the operands written twice)",
992 &["(a | b) - (a & b) with simple operands"],
993 ));
994 }
995 return ctx.note(
996 "bitwise",
997 Tier::Conditional,
998 "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",
999 Some(Allowance::BitwiseNonNegativeIntegers),
1000 );
1001 }
1002 if op == BinaryOp::Xor {
1003 return ctx.note(
1004 "xor",
1005 Tier::Conditional,
1006 "XOR is written as <>, which compares truth values only when both operands are booleans or 0/1 comparison results",
1007 Some(Allowance::XorOperandsBoolean),
1008 );
1009 }
1010 match op {
1011 BinaryOp::IntDivide => ctx.note(
1012 "division_integer",
1013 Tier::Conditional,
1014 "DIV becomes `/`, which is integer division only if both operands are integers",
1015 Some(Allowance::IntegerDivisionAssumed),
1016 ),
1017 BinaryOp::Eq | BinaryOp::NotEq if !numeric && matches!(ctx.source, "mysql" | "mariadb") => ctx.note(
1018 "text_comparison",
1019 Tier::Conditional,
1020 "text equality follows the source column collation; SQLite compares bytes (BINARY)",
1021 Some(Allowance::TextCollation),
1022 ),
1023 BinaryOp::Divide | BinaryOp::Modulo => ctx.note(
1024 "division",
1025 Tier::Conditional,
1026 "division/modulo by zero is NULL on SQLite (an error on PostgreSQL)",
1027 Some(Allowance::DivisionByZeroIsNull),
1028 ),
1029 BinaryOp::Lt | BinaryOp::LtEq | BinaryOp::Gt | BinaryOp::GtEq if numeric => {
1030 ctx.note("ordered_comparison", Tier::Exact, "numeric operand", None)
1031 }
1032 BinaryOp::Lt | BinaryOp::LtEq | BinaryOp::Gt | BinaryOp::GtEq => ctx.note(
1033 "ordered_comparison",
1034 Tier::Conditional,
1035 "text comparison follows the target's collation (BINARY by default)",
1036 Some(Allowance::TextCollation),
1037 ),
1038 _ => Ok(()),
1039 }
1040 }
1041
1042 fn nulls_order(&self, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
1043 if ctx.order_non_text {
1044 ctx.note("order_by", Tier::Exact, "non-text column", None)?;
1045 } else {
1046 ctx.note(
1047 "order_by",
1048 Tier::Conditional,
1049 "text ordering follows the target's collation (BINARY by default)",
1050 Some(Allowance::TextCollation),
1051 )?;
1052 }
1053 let default_first = !desc;
1055 if nulls_first == default_first {
1056 ctx.note("null_ordering", Tier::Exact, "", None)?;
1057 Ok(String::new())
1058 } else {
1059 ctx.note(
1060 "null_ordering",
1061 Tier::Emulated,
1062 "explicit NULLS FIRST/LAST (SQLite >= 3.30) to keep PostgreSQL's NULL order",
1063 None,
1064 )?;
1065 Ok(if nulls_first {
1066 " NULLS FIRST"
1067 } else {
1068 " NULLS LAST"
1069 }
1070 .to_string())
1071 }
1072 }
1073}