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