Skip to main content

unisql_dialect_sqlite/
lib.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! SQLite dialect module: a reader (text -> IR) and a writer (the [`Sqlite`] target).
3//!
4//! Every deviation from PostgreSQL semantics is a named [`Allowance`] or a refusal; the
5//! differential tests in `unisql-differential` are what justify each tier. Minimum engine
6//! version assumed by the tiers: SQLite 3.35 (`RETURNING`), noted per construct.
7
8use 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
16/// Read exactly one SQLite statement.
17pub 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        // Numbered, so a source `$2, $1` or a reused `$1` binds without reordering.
38        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        // SQLite has no default escape character, so the IR's choice is always stated explicitly.
62        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            // PostgreSQL's default LIKE escape is a backslash; SQLite has none, so state it.
69            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        // SQLite parses `REGEXP` but ships no implementation: it calls an application-defined
96        // function that a plain connection does not have, so the statement would fail at run time.
97        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            _ => "",
138        };
139        ctx.note(name, Tier::Exact, min, None)
140    }
141
142    fn trim(&self, side: TrimSide, expr: &str, chars: Option<&str>, ctx: &mut Ctx) -> R<String> {
143        ctx.note("trim", Tier::Exact, "", None)?;
144        let f = match side {
145            TrimSide::Both => "trim",
146            TrimSide::Leading => "ltrim",
147            TrimSide::Trailing => "rtrim",
148        };
149        Ok(match chars {
150            Some(c) => format!("{f}({expr}, {c})"),
151            None => format!("{f}({expr})"),
152        })
153    }
154
155    fn interval_arith(
156        &self,
157        minus: bool,
158        left: &str,
159        parts: &[(String, String)],
160        ctx: &mut Ctx,
161    ) -> R<Option<String>> {
162        let mut mods = Vec::new();
163        for (unit, value) in parts {
164            let (sql_unit, mult) = match unit.as_str() {
165                "secs" => ("seconds", None),
166                "mins" => ("minutes", None),
167                "hours" => ("hours", None),
168                "days" => ("days", None),
169                "weeks" => ("days", Some(7)),
170                other => {
171                    return Err(ctx.refuse(
172                        if matches!(other, "months" | "years") {
173                            "fn:make_interval.month_year"
174                        } else {
175                            "fn:make_interval"
176                        },
177                        &format!("make_interval({other} => ..): month/year arithmetic differs between the engines"),
178                        &["use secs/mins/hours/days/weeks"],
179                    ));
180                }
181            };
182            let v = match mult {
183                Some(m) => format!("(({value}) * {m})"),
184                None => format!("({value})"),
185            };
186            let signed = if minus { format!("(-{v})") } else { v };
187            mods.push(format!("printf('%+f {sql_unit}', {signed})"));
188        }
189        ctx.note(
190            "interval_arithmetic",
191            Tier::Conditional,
192            "timestamp +/- make_interval(..) becomes datetime(ts, modifiers): text, whole seconds, UTC",
193            Some(Allowance::TimestampArithmeticAsText),
194        )?;
195        Ok(Some(format!("datetime({left}, {})", mods.join(", "))))
196    }
197
198    fn json_access(&self, text: bool, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
199        if text {
200            ctx.note(
201                "json_get_text",
202                Tier::Conditional,
203                "SQLite ->> keeps the scalar's type (true -> 1); cast to TEXT here, but a JSON boolean \
204                 still reads '1' where PostgreSQL reads 'true'. Requires SQLite >= 3.38",
205                Some(Allowance::JsonScalarAffinity),
206            )?;
207            Ok(format!("CAST({lhs} ->> {rhs} AS TEXT)"))
208        } else {
209            ctx.note(
210                "json_get",
211                Tier::Conditional,
212                "SQLite -> returns JSON text; comparison is textual, not jsonb equality. Requires >= 3.38",
213                Some(Allowance::JsonRepresentationAsText),
214            )?;
215            Ok(format!("{lhs} -> {rhs}"))
216        }
217    }
218
219    fn function(&self, f: &Function, args: &[String], ctx: &mut Ctx) -> R<String> {
220        let n = f.name.as_str();
221        if n == "current_date" {
222            if ctx.source == "sqlite" {
223                ctx.note("fn:current_date", Tier::Exact, "", None)?;
224            } else {
225                ctx.note(
226                    "fn:current_date",
227                    Tier::Conditional,
228                    "-> CURRENT_DATE; text 'YYYY-MM-DD' of the UTC date, not a date in the session time zone",
229                    Some(Allowance::DateAsText),
230                )?;
231            }
232            return Ok("CURRENT_DATE".to_string());
233        }
234        if ctx.source == "sqlite" {
235            if n == "now" {
236                // The reader normalised CURRENT_TIMESTAMP to now(); SQLite spells it back.
237                ctx.note("fn:now", Tier::Exact, "", None)?;
238                return Ok("CURRENT_TIMESTAMP".to_string());
239            }
240            // The reader normalised `instr` to `strpos`; SQLite spells it back.
241            if n == "strpos" && args.len() == 2 {
242                ctx.note("fn:strpos", Tier::Exact, "", None)?;
243                return Ok(format!("instr({}, {})", args[0], args[1]));
244            }
245            // Same dialect in and out: the reader accepted the name, so this is the identity.
246            ctx.note(format!("fn:{n}"), Tier::Exact, "", None)?;
247            let order = ctx.agg_order.take();
248            return Ok(generic_call_ordered(
249                n,
250                args,
251                f.distinct,
252                f.star,
253                order.as_deref(),
254            ));
255        }
256        match n {
257            "utc_timestamp" => {
258                let (text, allow2) = match unisql_core::target::utc_timestamp_precision(f) {
259                    Some(0) => ("datetime('now')", None),
260                    Some(6) => (
261                        "strftime('%Y-%m-%d %H:%M:%f', 'now')",
262                        Some(Allowance::TimestampMillisecondResolution),
263                    ),
264                    _ => {
265                        return Err(ctx.refuse(
266                            "fn:utc_timestamp.precision",
267                            "only UTC_TIMESTAMP() and UTC_TIMESTAMP(6) are verified",
268                            &["use UTC_TIMESTAMP() or UTC_TIMESTAMP(6)"],
269                        ));
270                    }
271                };
272                ctx.note(
273                    "fn:utc_timestamp",
274                    Tier::Conditional,
275                    "text 'YYYY-MM-DD HH:MM:SS[.fff]' in UTC, not a timestamp type",
276                    Some(Allowance::TimestampAsText),
277                )?;
278                if let Some(a) = allow2 {
279                    ctx.note(
280                        "fn:utc_timestamp",
281                        Tier::Conditional,
282                        "SQLite's %f has millisecond resolution; MySQL's UTC_TIMESTAMP(6) has microseconds",
283                        Some(a),
284                    )?;
285                }
286                return Ok(text.to_string());
287            }
288            "utc_date" if args.is_empty() => {
289                ctx.note(
290                    "fn:utc_date",
291                    Tier::Conditional,
292                    "text 'YYYY-MM-DD' of the UTC date, not a date type",
293                    Some(Allowance::DateAsText),
294                )?;
295                return Ok("date('now')".to_string());
296            }
297            "datediff" if args.len() == 2 => {
298                ctx.note(
299                    "fn:datediff",
300                    Tier::Conditional,
301                    "operands are timestamp text; whole days between their date parts",
302                    Some(Allowance::TimestampAsText),
303                )?;
304                return Ok(format!(
305                    "CAST(julianday(date({})) - julianday(date({})) AS INTEGER)",
306                    args[0], args[1]
307                ));
308            }
309            "concat_ws" if args.len() >= 2 => {
310                ctx.note("fn:concat_ws", Tier::Exact, "requires SQLite >= 3.44", None)?;
311                return Ok(format!("concat_ws({})", args.join(", ")));
312            }
313            "left" if args.len() == 2 && unisql_core::target::literal_count(f, 1).is_some() => {
314                ctx.note("fn:left", Tier::Exact, "-> substr(s, 1, n)", None)?;
315                return Ok(format!("substr({}, 1, {})", args[0], args[1]));
316            }
317            "left" if args.len() == 2 => {
318                return Err(ctx.refuse(
319                    "fn:left.length",
320                    "LEFT(s, n) is mapped only for a literal n >= 0",
321                    &["use a literal non-negative count"],
322                ));
323            }
324            "right" if args.len() == 2 => {
325                return match unisql_core::target::literal_count(f, 1) {
326                    Some(0) => {
327                        ctx.note("fn:right", Tier::Exact, "-> substr(s, 1, 0)", None)?;
328                        Ok(format!("substr({}, 1, 0)", args[0]))
329                    }
330                    Some(_) => {
331                        ctx.note("fn:right", Tier::Exact, "-> substr(s, -n)", None)?;
332                        Ok(format!("substr({}, -{})", args[0], args[1]))
333                    }
334                    None => Err(ctx.refuse(
335                        "fn:right.length",
336                        "RIGHT(s, n) is mapped only for a literal n >= 0",
337                        &["use a literal non-negative count"],
338                    )),
339                };
340            }
341            "repeat" if args.len() == 2 && unisql_core::target::literal_count(f, 1).is_some() => {
342                ctx.note(
343                    "fn:repeat",
344                    Tier::Emulated,
345                    "-> replace(hex(zeroblob(n)), '00', s)",
346                    None,
347                )?;
348                return Ok(format!(
349                    "replace(hex(zeroblob({})), '00', {})",
350                    args[1], args[0]
351                ));
352            }
353            "date" if args.len() == 1 => {
354                ctx.note(
355                    "fn:date",
356                    Tier::Conditional,
357                    "text 'YYYY-MM-DD', not a date type",
358                    Some(Allowance::DateAsText),
359                )?;
360                return Ok(format!("date({})", args[0]));
361            }
362            _ => {}
363        }
364        if f.over.is_some()
365            && matches!(
366                n,
367                "row_number"
368                    | "rank"
369                    | "dense_rank"
370                    | "percent_rank"
371                    | "cume_dist"
372                    | "ntile"
373                    | "lag"
374                    | "lead"
375                    | "first_value"
376                    | "last_value"
377                    | "nth_value"
378            )
379        {
380            ctx.note(format!("fn:{n}"), Tier::Exact, "window function", None)?;
381            return Ok(generic_call(n, args, false, false));
382        }
383        match n {
384            "md5" | "sha256" | "sha1" | "sha512" | "encode" | "decode" | "convert_to"
385            | "convert_from" => {
386                return Err(ctx.refuse(
387                    &format!("fn:{n}"),
388                    "SQLite has no built-in hashing/encoding functions; the result would depend on a \
389                     host-registered function or extension, which UniSQL cannot assume",
390                    &["hash in the application", "register the function and use a raw(sqlite, ..) fragment"],
391                ));
392            }
393            "current_schema" | "current_database" | "current_user" | "session_user"
394            | "to_regclass" | "pg_backend_pid" | "set_config" | "current_setting" => {
395                return Err(ctx.refuse(
396                    &format!("fn:{n}"),
397                    "PostgreSQL catalog/session introspection has no SQLite equivalent",
398                    &["query sqlite_schema (a different, SQLite-specific statement)"],
399                ));
400            }
401            "make_interval" => {
402                return Err(ctx.refuse(
403                    "fn:make_interval.standalone",
404                    "SQLite has no interval type; only `timestamp +/- make_interval(secs|mins|hours|days|weeks => ..)` is translated",
405                    &[],
406                ));
407            }
408            "regexp_replace" | "regexp_match" | "regexp_matches" | "split_part" => {
409                return Err(ctx.refuse(
410                    &format!("fn:{n}"),
411                    "no built-in regular-expression or split function in SQLite",
412                    &[],
413                ));
414            }
415            _ => {}
416        }
417        match n {
418            // Math functions are a compile-time option of SQLite (the bundled build used by the
419            // differential suites has none), so a mapping cannot be verified.
420            "ceil" | "floor" => Err(ctx.refuse(
421                &format!("fn:{n}"),
422                "SQLite's ceil/floor exist only when it is built with its math functions",
423                &["round in the application"],
424            )),
425            "strpos" if args.len() == 2 => {
426                ctx.note("fn:strpos", Tier::Exact, "-> instr(s, sub)", None)?;
427                Ok(format!("instr({}, {})", args[0], args[1]))
428            }
429            "min" | "max" => {
430                ctx.note(
431                    format!("fn:{n}"),
432                    Tier::Conditional,
433                    "on text, follows the target's collation (BINARY by default)",
434                    Some(Allowance::TextCollation),
435                )?;
436                Ok(generic_call(n, args, f.distinct, f.star))
437            }
438            "count" | "sum" | "avg" | "coalesce" | "nullif" | "abs" | "length" | "replace"
439            | "trim" | "ltrim" | "rtrim" | "substr" | "ifnull" => {
440                ctx.note(format!("fn:{n}"), Tier::Exact, "", None)?;
441                Ok(generic_call(n, args, f.distinct, f.star))
442            }
443            "lower" | "upper" => {
444                ctx.note(
445                    format!("fn:{n}"),
446                    Tier::Conditional,
447                    "SQLite folds ASCII only",
448                    Some(Allowance::AsciiOnlyCaseFolding),
449                )?;
450                Ok(generic_call(n, args, false, false))
451            }
452            "btrim" => {
453                ctx.note("fn:btrim", Tier::Emulated, "-> trim(x[, chars])", None)?;
454                Ok(generic_call("trim", args, false, false))
455            }
456            "octet_length" => {
457                if args.len() != 1 {
458                    return Err(ctx.refuse(
459                        "fn:octet_length",
460                        "octet_length takes one argument",
461                        &[],
462                    ));
463                }
464                ctx.note(
465                    "fn:octet_length",
466                    Tier::Emulated,
467                    "-> length(CAST(x AS BLOB)): bytes, not characters",
468                    None,
469                )?;
470                Ok(format!("LENGTH(CAST({} AS BLOB))", args[0]))
471            }
472            "char_length" | "character_length" => {
473                ctx.note(format!("fn:{n}"), Tier::Emulated, "-> length()", None)?;
474                Ok(generic_call("length", args, false, false))
475            }
476            "string_agg" => {
477                if args.len() != 2 {
478                    return Err(ctx.refuse(
479                        "fn:string_agg",
480                        "string_agg needs exactly (value, separator)",
481                        &[],
482                    ));
483                }
484                ctx.note(
485                    "fn:string_agg",
486                    Tier::Emulated,
487                    "-> group_concat(value, separator); an ORDER BY inside needs SQLite >= 3.44",
488                    None,
489                )?;
490                let order = ctx.agg_order.take();
491                // SQLite: a DISTINCT aggregate takes exactly one argument (the separator is ',').
492                let args = if f.distinct {
493                    if args[1] != "','" {
494                        return Err(ctx.refuse(
495                            "fn:string_agg",
496                            "SQLite group_concat(DISTINCT ..) cannot take a separator",
497                            &["aggregate without DISTINCT, or use the default ',' separator"],
498                        ));
499                    }
500                    &args[..1]
501                } else {
502                    args
503                };
504                Ok(generic_call_ordered(
505                    "group_concat",
506                    args,
507                    f.distinct,
508                    false,
509                    order.as_deref(),
510                ))
511            }
512            // to_timestamp(seconds): datetime(x, 'unixepoch'), text in UTC, whole seconds.
513            "to_timestamp" if args.len() == 1 => {
514                ctx.note(
515                    "fn:to_timestamp",
516                    Tier::Conditional,
517                    "datetime(x, 'unixepoch'): text YYYY-MM-DD HH:MM:SS in UTC",
518                    Some(Allowance::TimestampAsText),
519                )?;
520                ctx.note(
521                    "fn:to_timestamp",
522                    Tier::Conditional,
523                    "a fraction of a second is dropped",
524                    Some(Allowance::TimestampWholeSeconds),
525                )?;
526                Ok(format!("datetime({}, 'unixepoch')", args[0]))
527            }
528            // date_trunc('<field>', ts): the timestamp text cut at the field.
529            "date_trunc"
530                if args.len() == 2 && unisql_core::target::date_trunc_field(f).is_some() =>
531            {
532                let field = unisql_core::target::date_trunc_field(f).unwrap_or_default();
533                let fmt = match field.as_str() {
534                    "year" => "%Y-01-01 00:00:00",
535                    "month" => "%Y-%m-01 00:00:00",
536                    "day" => "%Y-%m-%d 00:00:00",
537                    "hour" => "%Y-%m-%d %H:00:00",
538                    "minute" => "%Y-%m-%d %H:%M:00",
539                    _ => {
540                        return Err(ctx.refuse(
541                            &format!("fn:date_trunc.{field}"),
542                            &format!(
543                                "no verified mapping for date_trunc('{field}', ..) on SQLite yet"
544                            ),
545                            &["truncate in the application"],
546                        ));
547                    }
548                };
549                ctx.note(
550                    format!("fn:date_trunc.{field}"),
551                    Tier::Conditional,
552                    "strftime cuts the timestamp text; the result is text",
553                    Some(Allowance::TimestampAsText),
554                )?;
555                Ok(format!("strftime('{fmt}', {})", args[1]))
556            }
557            // Same construction as on MySQL, from randomblob(): verified over 2000 values.
558            "gen_random_uuid" => {
559                ctx.note(
560                    "fn:gen_random_uuid",
561                    Tier::Emulated,
562                    "assembled from randomblob(): version 4, variant 10xx",
563                    None,
564                )?;
565                Ok(
566                    "lower(hex(randomblob(4)) || '-' || hex(randomblob(2)) || '-4' || \
567                    substr(hex(randomblob(2)), 2) || '-' || \
568                    substr('89ab', 1 + (abs(random()) % 4), 1) || \
569                    substr(hex(randomblob(2)), 2) || '-' || hex(randomblob(6)))"
570                        .to_string(),
571                )
572            }
573            "now" => {
574                ctx.note(
575                    "fn:now",
576                    Tier::Conditional,
577                    "-> CURRENT_TIMESTAMP; text 'YYYY-MM-DD HH:MM:SS' in UTC, not a timestamptz",
578                    Some(Allowance::NowAsText),
579                )?;
580                Ok("CURRENT_TIMESTAMP".to_string())
581            }
582            other => Err(ctx.refuse(
583                &format!("fn:{other}"),
584                "no verified mapping for this function on SQLite yet",
585                &[
586                    "add a mapping with a differential test",
587                    "use a raw(sqlite, ..) fragment",
588                ],
589            )),
590        }
591    }
592
593    fn cast(&self, expr: &str, ty: &SqlType, ctx: &mut Ctx) -> R<String> {
594        // `CAST(x AS VARCHAR(n))` truncates to n characters; SQLite's TEXT affinity does not.
595        if let SqlType::Varchar(Some(n)) = ty {
596            ctx.note(
597                "cast.to_text",
598                Tier::Emulated,
599                "substr(CAST(x AS TEXT), 1, n): SQLite has no length-limited cast",
600                None,
601            )?;
602            return Ok(format!("SUBSTR(CAST({expr} AS TEXT), 1, {n})"));
603        }
604        let name = match ty {
605            SqlType::SmallInt | SqlType::Integer | SqlType::BigInt => "INTEGER",
606            SqlType::Real | SqlType::Double => "REAL",
607            SqlType::Numeric { .. } => "NUMERIC",
608            SqlType::Text | SqlType::Varchar(_) => "TEXT",
609            // A timestamp without zone is the text `YYYY-MM-DD HH:MM:SS` already (every timestamp
610            // is text here), so the cast keeps the text. Verified against PostgreSQL's value
611            // through its epoch on fixed timestamps.
612            SqlType::Timestamp { with_tz: false } => {
613                ctx.note(
614                    "cast.to_timestamp",
615                    Tier::Conditional,
616                    "a timestamp is text on SQLite: the cast keeps the text",
617                    Some(Allowance::TimestampAsText),
618                )?;
619                ctx.note(
620                    "cast.to_timestamp",
621                    Tier::Conditional,
622                    "SQLite casts leniently: a malformed value is kept instead of raising an error",
623                    Some(Allowance::LenientCast),
624                )?;
625                return Ok(format!("CAST({expr} AS TEXT)"));
626            }
627            other => {
628                return Err(ctx.refuse(
629                    &format!("cast.to_{}", other.leaf()),
630                    &format!("CAST to {other:?} has no SQLite equivalent that preserves meaning"),
631                    &["store as TEXT/INTEGER and convert in the application"],
632                ));
633            }
634        };
635        ctx.note(
636            format!("cast.to_{}", ty.leaf()),
637            Tier::Conditional,
638            "SQLite casts leniently: a malformed value becomes 0 or a numeric prefix instead of an error",
639            Some(Allowance::LenientCast),
640        )?;
641        Ok(format!("CAST({expr} AS {name})"))
642    }
643
644    fn group_by_rollup(&self, _keys: &[String], ctx: &mut Ctx) -> R<String> {
645        Err(ctx.refuse(
646            "group_by.rollup",
647            "SQLite has no ROLLUP",
648            &["UNION ALL one GROUP BY per key prefix (not emulated)"],
649        ))
650    }
651
652    fn distinct_on(&self, ctx: &mut Ctx) -> R<()> {
653        Err(ctx.refuse(
654            "distinct_on",
655            "SQLite has no DISTINCT ON",
656            &["rewrite with row_number() OVER (PARTITION BY ..) in a subquery (not yet emulated)"],
657        ))
658    }
659
660    fn row_lock(&self, _lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
661        Err(ctx.refuse(
662            unisql_core::target::row_lock_leaf(_lock),
663            "SQLite has no row-level locks (it locks the whole database)",
664            &["use BEGIN IMMEDIATE for a write transaction"],
665        ))
666    }
667
668    fn at_time_zone(&self, ctx: &mut Ctx) -> R<()> {
669        Err(ctx.refuse(
670            "at_time_zone",
671            "SQLite has no time zones: its datetimes are text in UTC",
672            &["convert in the application, or store UTC"],
673        ))
674    }
675
676    fn array_subquery(&self, ctx: &mut Ctx) -> R<()> {
677        Err(ctx.refuse(
678            "array_subquery",
679            "SQLite has no array type",
680            &["select the rows and collect them in the application"],
681        ))
682    }
683
684    fn null_safe_eq(&self, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
685        ctx.note(
686            "null_safe_eq",
687            Tier::Exact,
688            "SQLite `IS` compares like `<=>`",
689            None,
690        )?;
691        Ok(format!("{lhs} IS {rhs}"))
692    }
693
694    /// Verified on SQLite 3.53 against PostgreSQL's results: the fields are read from the timestamp
695    /// text with `strftime`; the epoch of a timestamp is `strftime('%s')`, whole seconds. Other fields
696    /// and the epoch of an interval have no verified mapping.
697    fn extract(&self, field: &str, expr: &str, interval: bool, ctx: &mut Ctx) -> R<String> {
698        let leaf = unisql_core::target::extract_leaf(field, interval);
699        let fmt = match field {
700            "year" => "%Y",
701            "month" => "%m",
702            "day" => "%d",
703            "hour" => "%H",
704            "minute" => "%M",
705            "epoch" if !interval => "%s",
706            _ => {
707                return Err(ctx.refuse(
708                    &leaf,
709                    &format!("SQLite: no verified mapping for EXTRACT({field} ..) yet"),
710                    &["compute the field in the application"],
711                ));
712            }
713        };
714        if fmt == "%s" {
715            ctx.note(
716                leaf,
717                Tier::Conditional,
718                "strftime('%s') gives whole seconds; PostgreSQL's epoch has the fraction",
719                Some(Allowance::EpochWholeSeconds),
720            )?;
721        } else {
722            ctx.note(
723                leaf,
724                Tier::Conditional,
725                "the field is read from the timestamp's text (YYYY-MM-DD HH:MM:SS, UTC)",
726                Some(Allowance::TimestampAsText),
727            )?;
728        }
729        Ok(format!("CAST(strftime('{fmt}', {expr}) AS INTEGER)"))
730    }
731
732    /// `unixepoch('now', 'subsec')` (SQLite 3.42+) is the epoch with milliseconds, read once per
733    /// statement.
734    fn epoch_of_clock(&self, ctx: &mut Ctx) -> R<String> {
735        ctx.note(
736            "extract.epoch",
737            Tier::Conditional,
738            "unixepoch('now','subsec') needs SQLite 3.42 or later and is read once per statement,              where clock_timestamp() is read at every call",
739            Some(Allowance::ClockIsStatementStart),
740        )?;
741        Ok("unixepoch('now', 'subsec')".to_string())
742    }
743
744    /// Whole seconds between two timestamp texts.
745    fn epoch_of_difference(&self, a: &str, b: &str, ctx: &mut Ctx) -> R<Option<String>> {
746        ctx.note(
747            "extract.epoch.interval",
748            Tier::Conditional,
749            "whole seconds between the two timestamp texts (strftime('%s'))",
750            Some(Allowance::EpochWholeSeconds),
751        )?;
752        Ok(Some(format!(
753            "(CAST(strftime('%s', {a}) AS INTEGER) - CAST(strftime('%s', {b}) AS INTEGER))"
754        )))
755    }
756
757    fn array_literal(&self, _items: &[String], ctx: &mut Ctx) -> R<String> {
758        Err(ctx.refuse(
759            "array_literal",
760            "SQLite has no array type",
761            &["use an IN (..) list, or a JSON array"],
762        ))
763    }
764
765    fn series_as_recursive_cte(&self) -> bool {
766        true
767    }
768
769    fn table_function(&self, name: &str, ctx: &mut Ctx) -> R<()> {
770        Err(ctx.refuse(
771            &format!("table_function.{name}"),
772            &format!("SQLite has no verified mapping for the table-valued function {name}()"),
773            &["generate the rows in the application, or use a recursive CTE for generate_series"],
774        ))
775    }
776
777    fn data_modifying_cte(&self, ctx: &mut Ctx) -> R<()> {
778        Err(ctx.refuse(
779            "cte.data_modifying",
780            "SQLite has no data-modifying CTE (WITH x AS (INSERT/UPDATE/DELETE ..)): probed, a syntax error",
781            &["run the statements separately in one transaction"],
782        ))
783    }
784
785    fn returning(&self, _kind: StmtKind, ctx: &mut Ctx) -> R<()> {
786        ctx.note("returning", Tier::Exact, "requires SQLite >= 3.35", None)
787    }
788
789    fn replace_keyword(&self) -> Option<&'static str> {
790        Some("INSERT OR REPLACE INTO")
791    }
792
793    fn upsert_clause(
794        &self,
795        conflict_cols: &[String],
796        do_nothing: bool,
797        set: &str,
798        where_: Option<&str>,
799        _first_insert_col: &str,
800        ctx: &mut Ctx,
801    ) -> R<String> {
802        if !do_nothing && conflict_cols.is_empty() {
803            return Err(ctx.refuse(
804                "upsert.no_conflict_key",
805                "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",
806                &["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)"],
807            ));
808        }
809        ctx.note(
810            if where_.is_some() {
811                "upsert_where"
812            } else {
813                "upsert"
814            },
815            Tier::Exact,
816            "requires SQLite >= 3.24",
817            None,
818        )?;
819        let mut s = String::from(" ON CONFLICT");
820        if !conflict_cols.is_empty() {
821            s.push_str(&format!(" ({})", conflict_cols.join(", ")));
822        }
823        if do_nothing {
824            s.push_str(" DO NOTHING");
825        } else {
826            s.push_str(&format!(" DO UPDATE SET {set}"));
827            if let Some(w) = where_ {
828                s.push_str(&format!(" WHERE {w}"));
829            }
830        }
831        Ok(s)
832    }
833
834    fn dml_limit(&self) -> DmlLimit {
835        DmlLimit::RowIdSubquery("rowid")
836    }
837
838    fn dml_sources(&self) -> DmlSources {
839        DmlSources::UpdateFromOnly
840    }
841
842    fn limit_offset(&self, limit: Option<&str>, offset: Option<&str>, ctx: &mut Ctx) -> R<String> {
843        match (limit, offset) {
844            (None, None) => Ok(String::new()),
845            (Some(l), None) => {
846                ctx.note("limit", Tier::Exact, "", None)?;
847                Ok(format!(" LIMIT {l}"))
848            }
849            (Some(l), Some(o)) => {
850                ctx.note("limit", Tier::Exact, "", None)?;
851                ctx.note("offset", Tier::Exact, "", None)?;
852                Ok(format!(" LIMIT {l} OFFSET {o}"))
853            }
854            (None, Some(o)) => {
855                ctx.note(
856                    "offset",
857                    Tier::Emulated,
858                    "SQLite requires LIMIT with OFFSET; -1 means unlimited",
859                    None,
860                )?;
861                Ok(format!(" LIMIT -1 OFFSET {o}"))
862            }
863        }
864    }
865
866    fn array_membership(
867        &self,
868        lhs: &str,
869        ph: &str,
870        negated: bool,
871        n: u32,
872        ctx: &mut Ctx,
873    ) -> R<String> {
874        ctx.note(
875            "array_param",
876            Tier::Conditional,
877            "bind the array as JSON text; membership via json_each(). A NULL array reads as empty",
878            Some(Allowance::ArrayNullSemantics),
879        )?;
880        ctx.bind_array_param(n, ParamBinding::JsonArrayText);
881        let not = if negated { "NOT " } else { "" };
882        Ok(format!("{lhs} {not}IN (SELECT value FROM json_each({ph}))"))
883    }
884
885    fn between(&self, numeric: bool, ctx: &mut Ctx) -> R<()> {
886        if numeric {
887            return ctx.note("ordered_comparison", Tier::Exact, "numeric operand", None);
888        }
889        ctx.note(
890            "ordered_comparison",
891            Tier::Conditional,
892            "text comparison follows the target's collation (BINARY by default)",
893            Some(Allowance::TextCollation),
894        )
895    }
896
897    fn binary_op(&self, op: BinaryOp, numeric: bool, ctx: &mut Ctx) -> R<()> {
898        if matches!(
899            op,
900            BinaryOp::BitAnd
901                | BinaryOp::BitOr
902                | BinaryOp::BitXor
903                | BinaryOp::ShiftLeft
904                | BinaryOp::ShiftRight
905        ) {
906            if ctx.source == "sqlite" {
907                return ctx.note("bitwise", Tier::Exact, "", None);
908            }
909            if op == BinaryOp::BitXor {
910                return Err(ctx.refuse(
911                    "bitwise.xor",
912                    "SQLite has no bitwise XOR operator (it would need the operands written twice)",
913                    &["(a | b) - (a & b) with simple operands"],
914                ));
915            }
916            return ctx.note(
917                "bitwise",
918                Tier::Conditional,
919                "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",
920                Some(Allowance::BitwiseNonNegativeIntegers),
921            );
922        }
923        if op == BinaryOp::Xor {
924            return ctx.note(
925                "xor",
926                Tier::Conditional,
927                "XOR is written as <>, which compares truth values only when both operands are booleans or 0/1 comparison results",
928                Some(Allowance::XorOperandsBoolean),
929            );
930        }
931        match op {
932            BinaryOp::IntDivide => ctx.note(
933                "division_integer",
934                Tier::Conditional,
935                "DIV becomes `/`, which is integer division only if both operands are integers",
936                Some(Allowance::IntegerDivisionAssumed),
937            ),
938            BinaryOp::Eq | BinaryOp::NotEq if !numeric && matches!(ctx.source, "mysql" | "mariadb") => ctx.note(
939                "text_comparison",
940                Tier::Conditional,
941                "text equality follows the source column collation; SQLite compares bytes (BINARY)",
942                Some(Allowance::TextCollation),
943            ),
944            BinaryOp::Divide | BinaryOp::Modulo => ctx.note(
945                "division",
946                Tier::Conditional,
947                "division/modulo by zero is NULL on SQLite (an error on PostgreSQL)",
948                Some(Allowance::DivisionByZeroIsNull),
949            ),
950            BinaryOp::Lt | BinaryOp::LtEq | BinaryOp::Gt | BinaryOp::GtEq if numeric => {
951                ctx.note("ordered_comparison", Tier::Exact, "numeric operand", None)
952            }
953            BinaryOp::Lt | BinaryOp::LtEq | BinaryOp::Gt | BinaryOp::GtEq => ctx.note(
954                "ordered_comparison",
955                Tier::Conditional,
956                "text comparison follows the target's collation (BINARY by default)",
957                Some(Allowance::TextCollation),
958            ),
959            _ => Ok(()),
960        }
961    }
962
963    fn nulls_order(&self, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
964        if ctx.order_non_text {
965            ctx.note("order_by", Tier::Exact, "non-text column", None)?;
966        } else {
967            ctx.note(
968                "order_by",
969                Tier::Conditional,
970                "text ordering follows the target's collation (BINARY by default)",
971                Some(Allowance::TextCollation),
972            )?;
973        }
974        // SQLite default: NULLs sort as the smallest value (first ascending, last descending).
975        let default_first = !desc;
976        if nulls_first == default_first {
977            ctx.note("null_ordering", Tier::Exact, "", None)?;
978            Ok(String::new())
979        } else {
980            ctx.note(
981                "null_ordering",
982                Tier::Emulated,
983                "explicit NULLS FIRST/LAST (SQLite >= 3.30) to keep PostgreSQL's NULL order",
984                None,
985            )?;
986            Ok(if nulls_first {
987                " NULLS FIRST"
988            } else {
989                " NULLS LAST"
990            }
991            .to_string())
992        }
993    }
994}