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        if f.over.is_some()
235            && matches!(
236                n,
237                "row_number"
238                    | "rank"
239                    | "dense_rank"
240                    | "percent_rank"
241                    | "cume_dist"
242                    | "ntile"
243                    | "lag"
244                    | "lead"
245                    | "first_value"
246                    | "last_value"
247                    | "nth_value"
248            )
249        {
250            ctx.note(format!("fn:{n}"), Tier::Exact, "window function", None)?;
251            return Ok(generic_call(n, args, false, false));
252        }
253        match n {
254            "md5" | "sha256" | "sha1" | "sha512" | "encode" | "decode" | "convert_to"
255            | "convert_from" => {
256                return Err(ctx.refuse(
257                    &format!("fn:{n}"),
258                    "SQLite has no built-in hashing/encoding functions; the result would depend on a \
259                     host-registered function or extension, which UniSQL cannot assume",
260                    &["hash in the application", "register the function and use a raw(sqlite, ..) fragment"],
261                ));
262            }
263            "current_schema" | "current_database" | "current_user" | "session_user"
264            | "to_regclass" | "pg_backend_pid" | "set_config" | "current_setting" => {
265                return Err(ctx.refuse(
266                    &format!("fn:{n}"),
267                    "PostgreSQL catalog/session introspection has no SQLite equivalent",
268                    &["query sqlite_schema (a different, SQLite-specific statement)"],
269                ));
270            }
271            "make_interval" => {
272                return Err(ctx.refuse(
273                    "fn:make_interval.standalone",
274                    "SQLite has no interval type; only `timestamp +/- make_interval(secs|mins|hours|days|weeks => ..)` is translated",
275                    &[],
276                ));
277            }
278            "regexp_replace" | "regexp_match" | "regexp_matches" | "split_part" => {
279                return Err(ctx.refuse(
280                    &format!("fn:{n}"),
281                    "no built-in regular-expression or split function in SQLite",
282                    &[],
283                ));
284            }
285            _ => {}
286        }
287        match n {
288            "min" | "max" => {
289                ctx.note(
290                    format!("fn:{n}"),
291                    Tier::Conditional,
292                    "on text, follows the target's collation (BINARY by default)",
293                    Some(Allowance::TextCollation),
294                )?;
295                Ok(generic_call(n, args, f.distinct, f.star))
296            }
297            "count" | "sum" | "avg" | "coalesce" | "nullif" | "abs" | "length" | "replace"
298            | "trim" | "ltrim" | "rtrim" | "substr" | "ifnull" => {
299                ctx.note(format!("fn:{n}"), Tier::Exact, "", None)?;
300                Ok(generic_call(n, args, f.distinct, f.star))
301            }
302            "lower" | "upper" => {
303                ctx.note(
304                    format!("fn:{n}"),
305                    Tier::Conditional,
306                    "SQLite folds ASCII only",
307                    Some(Allowance::AsciiOnlyCaseFolding),
308                )?;
309                Ok(generic_call(n, args, false, false))
310            }
311            "btrim" => {
312                ctx.note("fn:btrim", Tier::Emulated, "-> trim(x[, chars])", None)?;
313                Ok(generic_call("trim", args, false, false))
314            }
315            "octet_length" => {
316                if args.len() != 1 {
317                    return Err(ctx.refuse(
318                        "fn:octet_length",
319                        "octet_length takes one argument",
320                        &[],
321                    ));
322                }
323                ctx.note(
324                    "fn:octet_length",
325                    Tier::Emulated,
326                    "-> length(CAST(x AS BLOB)): bytes, not characters",
327                    None,
328                )?;
329                Ok(format!("LENGTH(CAST({} AS BLOB))", args[0]))
330            }
331            "char_length" | "character_length" => {
332                ctx.note(format!("fn:{n}"), Tier::Emulated, "-> length()", None)?;
333                Ok(generic_call("length", args, false, false))
334            }
335            "string_agg" => {
336                if args.len() != 2 {
337                    return Err(ctx.refuse(
338                        "fn:string_agg",
339                        "string_agg needs exactly (value, separator)",
340                        &[],
341                    ));
342                }
343                ctx.note(
344                    "fn:string_agg",
345                    Tier::Emulated,
346                    "-> group_concat(value, separator); an ORDER BY inside needs SQLite >= 3.44",
347                    None,
348                )?;
349                let order = ctx.agg_order.take();
350                Ok(generic_call_ordered(
351                    "group_concat",
352                    args,
353                    f.distinct,
354                    false,
355                    order.as_deref(),
356                ))
357            }
358            // to_timestamp(seconds): datetime(x, 'unixepoch'), text in UTC, whole seconds.
359            "to_timestamp" if args.len() == 1 => {
360                ctx.note(
361                    "fn:to_timestamp",
362                    Tier::Conditional,
363                    "datetime(x, 'unixepoch'): text YYYY-MM-DD HH:MM:SS in UTC",
364                    Some(Allowance::TimestampAsText),
365                )?;
366                ctx.note(
367                    "fn:to_timestamp",
368                    Tier::Conditional,
369                    "a fraction of a second is dropped",
370                    Some(Allowance::TimestampWholeSeconds),
371                )?;
372                Ok(format!("datetime({}, 'unixepoch')", args[0]))
373            }
374            // date_trunc('<field>', ts): the timestamp text cut at the field.
375            "date_trunc"
376                if args.len() == 2 && unisql_core::target::date_trunc_field(f).is_some() =>
377            {
378                let field = unisql_core::target::date_trunc_field(f).unwrap_or_default();
379                let fmt = match field.as_str() {
380                    "year" => "%Y-01-01 00:00:00",
381                    "month" => "%Y-%m-01 00:00:00",
382                    "day" => "%Y-%m-%d 00:00:00",
383                    "hour" => "%Y-%m-%d %H:00:00",
384                    "minute" => "%Y-%m-%d %H:%M:00",
385                    _ => {
386                        return Err(ctx.refuse(
387                            &format!("fn:date_trunc.{field}"),
388                            &format!(
389                                "no verified mapping for date_trunc('{field}', ..) on SQLite yet"
390                            ),
391                            &["truncate in the application"],
392                        ));
393                    }
394                };
395                ctx.note(
396                    format!("fn:date_trunc.{field}"),
397                    Tier::Conditional,
398                    "strftime cuts the timestamp text; the result is text",
399                    Some(Allowance::TimestampAsText),
400                )?;
401                Ok(format!("strftime('{fmt}', {})", args[1]))
402            }
403            // Same construction as on MySQL, from randomblob(): verified over 2000 values.
404            "gen_random_uuid" => {
405                ctx.note(
406                    "fn:gen_random_uuid",
407                    Tier::Emulated,
408                    "assembled from randomblob(): version 4, variant 10xx",
409                    None,
410                )?;
411                Ok(
412                    "lower(hex(randomblob(4)) || '-' || hex(randomblob(2)) || '-4' || \
413                    substr(hex(randomblob(2)), 2) || '-' || \
414                    substr('89ab', 1 + (abs(random()) % 4), 1) || \
415                    substr(hex(randomblob(2)), 2) || '-' || hex(randomblob(6)))"
416                        .to_string(),
417                )
418            }
419            "now" => {
420                ctx.note(
421                    "fn:now",
422                    Tier::Conditional,
423                    "-> CURRENT_TIMESTAMP; text 'YYYY-MM-DD HH:MM:SS' in UTC, not a timestamptz",
424                    Some(Allowance::NowAsText),
425                )?;
426                Ok("CURRENT_TIMESTAMP".to_string())
427            }
428            other => Err(ctx.refuse(
429                &format!("fn:{other}"),
430                "no verified mapping for this function on SQLite yet",
431                &[
432                    "add a mapping with a differential test",
433                    "use a raw(sqlite, ..) fragment",
434                ],
435            )),
436        }
437    }
438
439    fn cast(&self, expr: &str, ty: &SqlType, ctx: &mut Ctx) -> R<String> {
440        let name = match ty {
441            SqlType::SmallInt | SqlType::Integer | SqlType::BigInt => "INTEGER",
442            SqlType::Real | SqlType::Double => "REAL",
443            SqlType::Numeric { .. } => "NUMERIC",
444            SqlType::Text | SqlType::Varchar(_) => "TEXT",
445            // A timestamp without zone is the text `YYYY-MM-DD HH:MM:SS` already (every timestamp
446            // is text here), so the cast keeps the text. Verified against PostgreSQL's value
447            // through its epoch on fixed timestamps.
448            SqlType::Timestamp { with_tz: false } => {
449                ctx.note(
450                    "cast.to_timestamp",
451                    Tier::Conditional,
452                    "a timestamp is text on SQLite: the cast keeps the text",
453                    Some(Allowance::TimestampAsText),
454                )?;
455                ctx.note(
456                    "cast.to_timestamp",
457                    Tier::Conditional,
458                    "SQLite casts leniently: a malformed value is kept instead of raising an error",
459                    Some(Allowance::LenientCast),
460                )?;
461                return Ok(format!("CAST({expr} AS TEXT)"));
462            }
463            other => {
464                return Err(ctx.refuse(
465                    &format!("cast.to_{}", other.leaf()),
466                    &format!("CAST to {other:?} has no SQLite equivalent that preserves meaning"),
467                    &["store as TEXT/INTEGER and convert in the application"],
468                ));
469            }
470        };
471        ctx.note(
472            format!("cast.to_{}", ty.leaf()),
473            Tier::Conditional,
474            "SQLite casts leniently: a malformed value becomes 0 or a numeric prefix instead of an error",
475            Some(Allowance::LenientCast),
476        )?;
477        Ok(format!("CAST({expr} AS {name})"))
478    }
479
480    fn distinct_on(&self, ctx: &mut Ctx) -> R<()> {
481        Err(ctx.refuse(
482            "distinct_on",
483            "SQLite has no DISTINCT ON",
484            &["rewrite with row_number() OVER (PARTITION BY ..) in a subquery (not yet emulated)"],
485        ))
486    }
487
488    fn row_lock(&self, _lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
489        Err(ctx.refuse(
490            unisql_core::target::row_lock_leaf(_lock),
491            "SQLite has no row-level locks (it locks the whole database)",
492            &["use BEGIN IMMEDIATE for a write transaction"],
493        ))
494    }
495
496    fn at_time_zone(&self, ctx: &mut Ctx) -> R<()> {
497        Err(ctx.refuse(
498            "at_time_zone",
499            "SQLite has no time zones: its datetimes are text in UTC",
500            &["convert in the application, or store UTC"],
501        ))
502    }
503
504    fn array_subquery(&self, ctx: &mut Ctx) -> R<()> {
505        Err(ctx.refuse(
506            "array_subquery",
507            "SQLite has no array type",
508            &["select the rows and collect them in the application"],
509        ))
510    }
511
512    fn null_safe_eq(&self, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
513        ctx.note(
514            "null_safe_eq",
515            Tier::Exact,
516            "SQLite `IS` compares like `<=>`",
517            None,
518        )?;
519        Ok(format!("{lhs} IS {rhs}"))
520    }
521
522    /// Verified on SQLite 3.53 against PostgreSQL's results: the fields are read from the timestamp
523    /// text with `strftime`; the epoch of a timestamp is `strftime('%s')`, whole seconds. Other fields
524    /// and the epoch of an interval have no verified mapping.
525    fn extract(&self, field: &str, expr: &str, interval: bool, ctx: &mut Ctx) -> R<String> {
526        let leaf = unisql_core::target::extract_leaf(field, interval);
527        let fmt = match field {
528            "year" => "%Y",
529            "month" => "%m",
530            "day" => "%d",
531            "hour" => "%H",
532            "minute" => "%M",
533            "epoch" if !interval => "%s",
534            _ => {
535                return Err(ctx.refuse(
536                    &leaf,
537                    &format!("SQLite: no verified mapping for EXTRACT({field} ..) yet"),
538                    &["compute the field in the application"],
539                ));
540            }
541        };
542        if fmt == "%s" {
543            ctx.note(
544                leaf,
545                Tier::Conditional,
546                "strftime('%s') gives whole seconds; PostgreSQL's epoch has the fraction",
547                Some(Allowance::EpochWholeSeconds),
548            )?;
549        } else {
550            ctx.note(
551                leaf,
552                Tier::Conditional,
553                "the field is read from the timestamp's text (YYYY-MM-DD HH:MM:SS, UTC)",
554                Some(Allowance::TimestampAsText),
555            )?;
556        }
557        Ok(format!("CAST(strftime('{fmt}', {expr}) AS INTEGER)"))
558    }
559
560    /// Whole seconds between two timestamp texts.
561    fn epoch_of_difference(&self, a: &str, b: &str, ctx: &mut Ctx) -> R<Option<String>> {
562        ctx.note(
563            "extract.epoch.interval",
564            Tier::Conditional,
565            "whole seconds between the two timestamp texts (strftime('%s'))",
566            Some(Allowance::EpochWholeSeconds),
567        )?;
568        Ok(Some(format!(
569            "(CAST(strftime('%s', {a}) AS INTEGER) - CAST(strftime('%s', {b}) AS INTEGER))"
570        )))
571    }
572
573    fn array_literal(&self, _items: &[String], ctx: &mut Ctx) -> R<String> {
574        Err(ctx.refuse(
575            "array_literal",
576            "SQLite has no array type",
577            &["use an IN (..) list, or a JSON array"],
578        ))
579    }
580
581    fn data_modifying_cte(&self, ctx: &mut Ctx) -> R<()> {
582        Err(ctx.refuse(
583            "cte.data_modifying",
584            "SQLite has no data-modifying CTE (WITH x AS (INSERT/UPDATE/DELETE ..)): probed, a syntax error",
585            &["run the statements separately in one transaction"],
586        ))
587    }
588
589    fn returning(&self, _kind: StmtKind, ctx: &mut Ctx) -> R<()> {
590        ctx.note("returning", Tier::Exact, "requires SQLite >= 3.35", None)
591    }
592
593    fn upsert_clause(
594        &self,
595        conflict_cols: &[String],
596        do_nothing: bool,
597        set: &str,
598        where_: Option<&str>,
599        _first_insert_col: &str,
600        ctx: &mut Ctx,
601    ) -> R<String> {
602        if !do_nothing && conflict_cols.is_empty() {
603            return Err(ctx.refuse(
604                "upsert.no_conflict_key",
605                "the source upsert names no conflict key (MySQL ON DUPLICATE KEY UPDATE fires on any unique key); SQLite needs the key columns",
606                &["state the conflict key columns in the statement"],
607            ));
608        }
609        ctx.note(
610            if where_.is_some() {
611                "upsert_where"
612            } else {
613                "upsert"
614            },
615            Tier::Exact,
616            "requires SQLite >= 3.24",
617            None,
618        )?;
619        let mut s = String::from(" ON CONFLICT");
620        if !conflict_cols.is_empty() {
621            s.push_str(&format!(" ({})", conflict_cols.join(", ")));
622        }
623        if do_nothing {
624            s.push_str(" DO NOTHING");
625        } else {
626            s.push_str(&format!(" DO UPDATE SET {set}"));
627            if let Some(w) = where_ {
628                s.push_str(&format!(" WHERE {w}"));
629            }
630        }
631        Ok(s)
632    }
633
634    fn limit_offset(&self, limit: Option<&str>, offset: Option<&str>, ctx: &mut Ctx) -> R<String> {
635        match (limit, offset) {
636            (None, None) => Ok(String::new()),
637            (Some(l), None) => {
638                ctx.note("limit", Tier::Exact, "", None)?;
639                Ok(format!(" LIMIT {l}"))
640            }
641            (Some(l), Some(o)) => {
642                ctx.note("limit", Tier::Exact, "", None)?;
643                ctx.note("offset", Tier::Exact, "", None)?;
644                Ok(format!(" LIMIT {l} OFFSET {o}"))
645            }
646            (None, Some(o)) => {
647                ctx.note(
648                    "offset",
649                    Tier::Emulated,
650                    "SQLite requires LIMIT with OFFSET; -1 means unlimited",
651                    None,
652                )?;
653                Ok(format!(" LIMIT -1 OFFSET {o}"))
654            }
655        }
656    }
657
658    fn array_membership(
659        &self,
660        lhs: &str,
661        ph: &str,
662        negated: bool,
663        n: u32,
664        ctx: &mut Ctx,
665    ) -> R<String> {
666        ctx.note(
667            "array_param",
668            Tier::Conditional,
669            "bind the array as JSON text; membership via json_each(). A NULL array reads as empty",
670            Some(Allowance::ArrayNullSemantics),
671        )?;
672        ctx.bind_array_param(n, ParamBinding::JsonArrayText);
673        let not = if negated { "NOT " } else { "" };
674        Ok(format!("{lhs} {not}IN (SELECT value FROM json_each({ph}))"))
675    }
676
677    fn between(&self, numeric: bool, ctx: &mut Ctx) -> R<()> {
678        if numeric {
679            return ctx.note("ordered_comparison", Tier::Exact, "numeric operand", None);
680        }
681        ctx.note(
682            "ordered_comparison",
683            Tier::Conditional,
684            "text comparison follows the target's collation (BINARY by default)",
685            Some(Allowance::TextCollation),
686        )
687    }
688
689    fn binary_op(&self, op: BinaryOp, numeric: bool, ctx: &mut Ctx) -> R<()> {
690        match op {
691            BinaryOp::IntDivide => ctx.note(
692                "division_integer",
693                Tier::Conditional,
694                "DIV becomes `/`, which is integer division only if both operands are integers",
695                Some(Allowance::IntegerDivisionAssumed),
696            ),
697            BinaryOp::Eq | BinaryOp::NotEq if !numeric && matches!(ctx.source, "mysql" | "mariadb") => ctx.note(
698                "text_comparison",
699                Tier::Conditional,
700                "text equality follows the source column collation; SQLite compares bytes (BINARY)",
701                Some(Allowance::TextCollation),
702            ),
703            BinaryOp::Divide | BinaryOp::Modulo => ctx.note(
704                "division",
705                Tier::Conditional,
706                "division/modulo by zero is NULL on SQLite (an error on PostgreSQL)",
707                Some(Allowance::DivisionByZeroIsNull),
708            ),
709            BinaryOp::Lt | BinaryOp::LtEq | BinaryOp::Gt | BinaryOp::GtEq if numeric => {
710                ctx.note("ordered_comparison", Tier::Exact, "numeric operand", None)
711            }
712            BinaryOp::Lt | BinaryOp::LtEq | BinaryOp::Gt | BinaryOp::GtEq => ctx.note(
713                "ordered_comparison",
714                Tier::Conditional,
715                "text comparison follows the target's collation (BINARY by default)",
716                Some(Allowance::TextCollation),
717            ),
718            _ => Ok(()),
719        }
720    }
721
722    fn nulls_order(&self, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
723        ctx.note(
724            "order_by",
725            Tier::Conditional,
726            "text ordering follows the target's collation (BINARY by default)",
727            Some(Allowance::TextCollation),
728        )?;
729        // SQLite default: NULLs sort as the smallest value (first ascending, last descending).
730        let default_first = !desc;
731        if nulls_first == default_first {
732            ctx.note("null_ordering", Tier::Exact, "", None)?;
733            Ok(String::new())
734        } else {
735            ctx.note(
736                "null_ordering",
737                Tier::Emulated,
738                "explicit NULLS FIRST/LAST (SQLite >= 3.30) to keep PostgreSQL's NULL order",
739                None,
740            )?;
741            Ok(if nulls_first {
742                " NULLS FIRST"
743            } else {
744                " NULLS LAST"
745            }
746            .to_string())
747        }
748    }
749}