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