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            "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                // The reader normalised CURRENT_TIMESTAMP to now(); SQLite spells it back.
253                ctx.note("fn:now", Tier::Exact, "", None)?;
254                return Ok("CURRENT_TIMESTAMP".to_string());
255            }
256            // The reader normalised `instr` to `strpos`; SQLite spells it back.
257            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            // Same dialect in and out: the reader accepted the name, so this is the identity.
262            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            // Math functions are a compile-time option of SQLite (the bundled build used by the
435            // differential suites has none), so a mapping cannot be verified.
436            "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                // SQLite: a DISTINCT aggregate takes exactly one argument (the separator is ',').
508                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(seconds): datetime(x, 'unixepoch'), text in UTC, whole seconds.
529            "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(a, b) is an interval of years, months and days (calendar-relative); the target has
545            // no interval type to hold it, and the month-end rules differ.
546            "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(ts, 'YYYY-MM-DD HH24:MI:SS' and the like): strftime with the same pieces.
552            "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('<field>', ts): the timestamp text cut at the field.
573            "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                    // The Monday of the ISO week, then the day cut; the first month of the quarter.
584                    "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            // Same construction as on MySQL, from randomblob(): verified over 2000 values.
613            "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" if ctx.epoch_now => {
629                ctx.note(
630                    "fn:now",
631                    Tier::Conditional,
632                    "-> unixepoch(): whole seconds, read at statement start rather than transaction start",
633                    Some(Allowance::EpochNowIsStatementStart),
634                )?;
635                Ok("unixepoch()".to_string())
636            }
637            "now" => {
638                ctx.note(
639                    "fn:now",
640                    Tier::Conditional,
641                    "-> CURRENT_TIMESTAMP; text 'YYYY-MM-DD HH:MM:SS' in UTC, not a timestamptz",
642                    Some(Allowance::NowAsText),
643                )?;
644                Ok("CURRENT_TIMESTAMP".to_string())
645            }
646            other => Err(ctx.refuse(
647                &format!("fn:{other}"),
648                "no verified mapping for this function on SQLite yet",
649                &[
650                    "add a mapping with a differential test",
651                    "use a raw(sqlite, ..) fragment",
652                ],
653            )),
654        }
655    }
656
657    fn cast(&self, expr: &str, ty: &SqlType, ctx: &mut Ctx) -> R<String> {
658        // `CAST(x AS VARCHAR(n))` truncates to n characters; SQLite's TEXT affinity does not.
659        if let SqlType::Varchar(Some(n)) = ty {
660            ctx.note(
661                "cast.to_text",
662                Tier::Emulated,
663                "substr(CAST(x AS TEXT), 1, n): SQLite has no length-limited cast",
664                None,
665            )?;
666            return Ok(format!("SUBSTR(CAST({expr} AS TEXT), 1, {n})"));
667        }
668        let name = match ty {
669            SqlType::SmallInt | SqlType::Integer | SqlType::BigInt => "INTEGER",
670            SqlType::Real | SqlType::Double => "REAL",
671            SqlType::Numeric { .. } => "NUMERIC",
672            SqlType::Text | SqlType::Varchar(_) => "TEXT",
673            // A timestamp without zone is the text `YYYY-MM-DD HH:MM:SS` already (every timestamp
674            // is text here), so the cast keeps the text. Verified against PostgreSQL's value
675            // through its epoch on fixed timestamps.
676            SqlType::Timestamp { with_tz: false } => {
677                ctx.note(
678                    "cast.to_timestamp",
679                    Tier::Conditional,
680                    "a timestamp is text on SQLite: the cast keeps the text",
681                    Some(Allowance::TimestampAsText),
682                )?;
683                ctx.note(
684                    "cast.to_timestamp",
685                    Tier::Conditional,
686                    "SQLite casts leniently: a malformed value is kept instead of raising an error",
687                    Some(Allowance::LenientCast),
688                )?;
689                return Ok(format!("CAST({expr} AS TEXT)"));
690            }
691            other => {
692                return Err(ctx.refuse(
693                    &format!("cast.to_{}", other.leaf()),
694                    &format!("CAST to {other:?} has no SQLite equivalent that preserves meaning"),
695                    &["store as TEXT/INTEGER and convert in the application"],
696                ));
697            }
698        };
699        ctx.note(
700            format!("cast.to_{}", ty.leaf()),
701            Tier::Conditional,
702            "SQLite casts leniently: a malformed value becomes 0 or a numeric prefix instead of an error",
703            Some(Allowance::LenientCast),
704        )?;
705        Ok(format!("CAST({expr} AS {name})"))
706    }
707
708    fn group_by_rollup(&self, _keys: &[String], ctx: &mut Ctx) -> R<String> {
709        Err(ctx.refuse(
710            "group_by.rollup",
711            "SQLite has no ROLLUP",
712            &["UNION ALL one GROUP BY per key prefix (not emulated)"],
713        ))
714    }
715
716    fn distinct_on(&self, ctx: &mut Ctx) -> R<()> {
717        Err(ctx.refuse(
718            "distinct_on",
719            "SQLite has no DISTINCT ON",
720            &["rewrite with row_number() OVER (PARTITION BY ..) in a subquery (not yet emulated)"],
721        ))
722    }
723
724    fn row_lock(&self, _lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
725        Err(ctx.refuse(
726            unisql_core::target::row_lock_leaf(_lock),
727            "SQLite has no row-level locks (it locks the whole database)",
728            &["use BEGIN IMMEDIATE for a write transaction"],
729        ))
730    }
731
732    fn at_time_zone(&self, ctx: &mut Ctx) -> R<()> {
733        Err(ctx.refuse(
734            "at_time_zone",
735            "SQLite has no time zones: its datetimes are text in UTC",
736            &["convert in the application, or store UTC"],
737        ))
738    }
739
740    fn array_subquery(&self, ctx: &mut Ctx) -> R<()> {
741        Err(ctx.refuse(
742            "array_subquery",
743            "SQLite has no array type",
744            &["select the rows and collect them in the application"],
745        ))
746    }
747
748    fn null_safe_eq(&self, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
749        ctx.note(
750            "null_safe_eq",
751            Tier::Exact,
752            "SQLite `IS` compares like `<=>`",
753            None,
754        )?;
755        Ok(format!("{lhs} IS {rhs}"))
756    }
757
758    /// Verified on SQLite 3.53 against PostgreSQL's results: the fields are read from the timestamp
759    /// text with `strftime`; the epoch of a timestamp is `strftime('%s')`, whole seconds. `dow`,
760    /// `isodow`, `doy`, `quarter` and the ISO `week` are derived from the same text (the week from the
761    /// Thursday of its ISO week). Other fields and the epoch of an interval have no verified mapping.
762    fn extract(&self, field: &str, expr: &str, interval: bool, ctx: &mut Ctx) -> R<String> {
763        let leaf = unisql_core::target::extract_leaf(field, interval);
764        let derived = match field {
765            "dow" => Some(format!("CAST(strftime('%w', {expr}) AS INTEGER)")),
766            "isodow" => Some(format!(
767                "((CAST(strftime('%w', {expr}) AS INTEGER) + 6) % 7 + 1)"
768            )),
769            "doy" => Some(format!("CAST(strftime('%j', {expr}) AS INTEGER)")),
770            "quarter" => Some(format!(
771                "((CAST(strftime('%m', {expr}) AS INTEGER) + 2) / 3)"
772            )),
773            "week" => Some(format!(
774                "((CAST(strftime('%j', date({expr}, 'weekday 0', '-3 days')) AS INTEGER) - 1) / 7 + 1)"
775            )),
776            _ => None,
777        };
778        if let Some(sql) = derived {
779            ctx.note(
780                leaf,
781                Tier::Conditional,
782                "the field is derived from the timestamp's text (YYYY-MM-DD HH:MM:SS, UTC)",
783                Some(Allowance::TimestampAsText),
784            )?;
785            return Ok(sql);
786        }
787        let fmt = match field {
788            "year" => "%Y",
789            "month" => "%m",
790            "day" => "%d",
791            "hour" => "%H",
792            "minute" => "%M",
793            "epoch" if !interval => "%s",
794            _ => {
795                return Err(ctx.refuse(
796                    &leaf,
797                    &format!("SQLite: no verified mapping for EXTRACT({field} ..) yet"),
798                    &["compute the field in the application"],
799                ));
800            }
801        };
802        if fmt == "%s" {
803            ctx.note(
804                leaf,
805                Tier::Conditional,
806                "strftime('%s') gives whole seconds; PostgreSQL's epoch has the fraction",
807                Some(Allowance::EpochWholeSeconds),
808            )?;
809        } else {
810            ctx.note(
811                leaf,
812                Tier::Conditional,
813                "the field is read from the timestamp's text (YYYY-MM-DD HH:MM:SS, UTC)",
814                Some(Allowance::TimestampAsText),
815            )?;
816        }
817        Ok(format!("CAST(strftime('{fmt}', {expr}) AS INTEGER)"))
818    }
819
820    /// `unixepoch('now', 'subsec')` (SQLite 3.42+) is the epoch with milliseconds, read once per
821    /// statement.
822    fn epoch_of_clock(&self, ctx: &mut Ctx) -> R<String> {
823        ctx.note(
824            "extract.epoch",
825            Tier::Conditional,
826            "unixepoch('now','subsec') needs SQLite 3.42 or later and is read once per statement,              where clock_timestamp() is read at every call",
827            Some(Allowance::ClockIsStatementStart),
828        )?;
829        Ok("unixepoch('now', 'subsec')".to_string())
830    }
831
832    /// Whole seconds between two timestamp texts.
833    fn epoch_of_difference(&self, a: &str, b: &str, ctx: &mut Ctx) -> R<Option<String>> {
834        ctx.note(
835            "extract.epoch.interval",
836            Tier::Conditional,
837            "whole seconds between the two timestamp texts (strftime('%s'))",
838            Some(Allowance::EpochWholeSeconds),
839        )?;
840        Ok(Some(format!(
841            "(CAST(strftime('%s', {a}) AS INTEGER) - CAST(strftime('%s', {b}) AS INTEGER))"
842        )))
843    }
844
845    fn array_literal(&self, _items: &[String], ctx: &mut Ctx) -> R<String> {
846        Err(ctx.refuse(
847            "array_literal",
848            "SQLite has no array type",
849            &["use an IN (..) list, or a JSON array"],
850        ))
851    }
852
853    fn series_as_recursive_cte(&self) -> bool {
854        true
855    }
856
857    fn table_function(&self, name: &str, ctx: &mut Ctx) -> R<()> {
858        Err(ctx.refuse(
859            &format!("table_function.{name}"),
860            &format!("SQLite has no verified mapping for the table-valued function {name}()"),
861            &["generate the rows in the application, or use a recursive CTE for generate_series"],
862        ))
863    }
864
865    fn data_modifying_cte(&self, ctx: &mut Ctx) -> R<()> {
866        Err(ctx.refuse(
867            "cte.data_modifying",
868            "SQLite has no data-modifying CTE (WITH x AS (INSERT/UPDATE/DELETE ..)): probed, a syntax error",
869            &["run the statements separately in one transaction"],
870        ))
871    }
872
873    fn returning(&self, _kind: StmtKind, ctx: &mut Ctx) -> R<()> {
874        ctx.note("returning", Tier::Exact, "requires SQLite >= 3.35", None)
875    }
876
877    fn replace_keyword(&self) -> Option<&'static str> {
878        Some("INSERT OR REPLACE INTO")
879    }
880
881    fn upsert_clause(
882        &self,
883        conflict_cols: &[String],
884        do_nothing: bool,
885        set: &str,
886        where_: Option<&str>,
887        _first_insert_col: &str,
888        ctx: &mut Ctx,
889    ) -> R<String> {
890        if !do_nothing && conflict_cols.is_empty() {
891            return Err(ctx.refuse(
892                "upsert.no_conflict_key",
893                "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",
894                &["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)"],
895            ));
896        }
897        ctx.note(
898            if where_.is_some() {
899                "upsert_where"
900            } else {
901                "upsert"
902            },
903            Tier::Exact,
904            "requires SQLite >= 3.24",
905            None,
906        )?;
907        let mut s = String::from(" ON CONFLICT");
908        if !conflict_cols.is_empty() {
909            s.push_str(&format!(" ({})", conflict_cols.join(", ")));
910        }
911        if do_nothing {
912            s.push_str(" DO NOTHING");
913        } else {
914            s.push_str(&format!(" DO UPDATE SET {set}"));
915            if let Some(w) = where_ {
916                s.push_str(&format!(" WHERE {w}"));
917            }
918        }
919        Ok(s)
920    }
921
922    fn dml_limit(&self) -> DmlLimit {
923        DmlLimit::RowIdSubquery("rowid")
924    }
925
926    fn dml_sources(&self) -> DmlSources {
927        DmlSources::UpdateFromOnly
928    }
929
930    fn limit_offset(&self, limit: Option<&str>, offset: Option<&str>, ctx: &mut Ctx) -> R<String> {
931        match (limit, offset) {
932            (None, None) => Ok(String::new()),
933            (Some(l), None) => {
934                ctx.note("limit", Tier::Exact, "", None)?;
935                Ok(format!(" LIMIT {l}"))
936            }
937            (Some(l), Some(o)) => {
938                ctx.note("limit", Tier::Exact, "", None)?;
939                ctx.note("offset", Tier::Exact, "", None)?;
940                Ok(format!(" LIMIT {l} OFFSET {o}"))
941            }
942            (None, Some(o)) => {
943                ctx.note(
944                    "offset",
945                    Tier::Emulated,
946                    "SQLite requires LIMIT with OFFSET; -1 means unlimited",
947                    None,
948                )?;
949                Ok(format!(" LIMIT -1 OFFSET {o}"))
950            }
951        }
952    }
953
954    fn array_membership(
955        &self,
956        lhs: &str,
957        ph: &str,
958        negated: bool,
959        n: u32,
960        ctx: &mut Ctx,
961    ) -> R<String> {
962        ctx.note(
963            "array_param",
964            Tier::Conditional,
965            "bind the array as JSON text; membership via json_each(). A NULL array reads as empty",
966            Some(Allowance::ArrayNullSemantics),
967        )?;
968        ctx.bind_array_param(n, ParamBinding::JsonArrayText);
969        let not = if negated { "NOT " } else { "" };
970        Ok(format!("{lhs} {not}IN (SELECT value FROM json_each({ph}))"))
971    }
972
973    fn between(&self, numeric: bool, ctx: &mut Ctx) -> R<()> {
974        if numeric {
975            return ctx.note("ordered_comparison", Tier::Exact, "numeric operand", None);
976        }
977        ctx.note(
978            "ordered_comparison",
979            Tier::Conditional,
980            "text comparison follows the target's collation (BINARY by default)",
981            Some(Allowance::TextCollation),
982        )
983    }
984
985    fn binary_op(&self, op: BinaryOp, numeric: bool, ctx: &mut Ctx) -> R<()> {
986        if matches!(
987            op,
988            BinaryOp::BitAnd
989                | BinaryOp::BitOr
990                | BinaryOp::BitXor
991                | BinaryOp::ShiftLeft
992                | BinaryOp::ShiftRight
993        ) {
994            if ctx.source == "sqlite" {
995                return ctx.note("bitwise", Tier::Exact, "", None);
996            }
997            if op == BinaryOp::BitXor {
998                return Err(ctx.refuse(
999                    "bitwise.xor",
1000                    "SQLite has no bitwise XOR operator (it would need the operands written twice)",
1001                    &["(a | b) - (a & b) with simple operands"],
1002                ));
1003            }
1004            return ctx.note(
1005                "bitwise",
1006                Tier::Conditional,
1007                "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",
1008                Some(Allowance::BitwiseNonNegativeIntegers),
1009            );
1010        }
1011        if op == BinaryOp::Xor {
1012            return ctx.note(
1013                "xor",
1014                Tier::Conditional,
1015                "XOR is written as <>, which compares truth values only when both operands are booleans or 0/1 comparison results",
1016                Some(Allowance::XorOperandsBoolean),
1017            );
1018        }
1019        match op {
1020            BinaryOp::IntDivide => ctx.note(
1021                "division_integer",
1022                Tier::Conditional,
1023                "DIV becomes `/`, which is integer division only if both operands are integers",
1024                Some(Allowance::IntegerDivisionAssumed),
1025            ),
1026            BinaryOp::Eq | BinaryOp::NotEq if !numeric && matches!(ctx.source, "mysql" | "mariadb") => ctx.note(
1027                "text_comparison",
1028                Tier::Conditional,
1029                "text equality follows the source column collation; SQLite compares bytes (BINARY)",
1030                Some(Allowance::TextCollation),
1031            ),
1032            BinaryOp::Divide | BinaryOp::Modulo => ctx.note(
1033                "division",
1034                Tier::Conditional,
1035                "division/modulo by zero is NULL on SQLite (an error on PostgreSQL)",
1036                Some(Allowance::DivisionByZeroIsNull),
1037            ),
1038            BinaryOp::Lt | BinaryOp::LtEq | BinaryOp::Gt | BinaryOp::GtEq if numeric => {
1039                ctx.note("ordered_comparison", Tier::Exact, "numeric operand", None)
1040            }
1041            BinaryOp::Lt | BinaryOp::LtEq | BinaryOp::Gt | BinaryOp::GtEq => ctx.note(
1042                "ordered_comparison",
1043                Tier::Conditional,
1044                "text comparison follows the target's collation (BINARY by default)",
1045                Some(Allowance::TextCollation),
1046            ),
1047            _ => Ok(()),
1048        }
1049    }
1050
1051    fn nulls_order(&self, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
1052        if ctx.order_non_text {
1053            ctx.note("order_by", Tier::Exact, "non-text column", None)?;
1054        } else {
1055            ctx.note(
1056                "order_by",
1057                Tier::Conditional,
1058                "text ordering follows the target's collation (BINARY by default)",
1059                Some(Allowance::TextCollation),
1060            )?;
1061        }
1062        // SQLite default: NULLs sort as the smallest value (first ascending, last descending).
1063        let default_first = !desc;
1064        if nulls_first == default_first {
1065            ctx.note("null_ordering", Tier::Exact, "", None)?;
1066            Ok(String::new())
1067        } else {
1068            ctx.note(
1069                "null_ordering",
1070                Tier::Emulated,
1071                "explicit NULLS FIRST/LAST (SQLite >= 3.30) to keep PostgreSQL's NULL order",
1072                None,
1073            )?;
1074            Ok(if nulls_first {
1075                " NULLS FIRST"
1076            } else {
1077                " NULLS LAST"
1078            }
1079            .to_string())
1080        }
1081    }
1082}