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