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