Skip to main content

unisql_core/
target.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! The writer side of a dialect: a [`Target`] supplies *differences*; the shared printer in
3//! [`crate::print`] does the rest. Defaults describe PostgreSQL, the first source dialect, so a
4//! Postgres target is nearly empty and every other target overrides only what it must.
5
6use crate::ast::*;
7use crate::report::{Allowance, Entry, Options, ParamBinding, Report, Tier, Untranslatable};
8
9/// Per-translation state handed to every hook.
10pub struct Ctx<'a> {
11    pub report: Report,
12    pub opts: &'a Options,
13    /// The tables in scope while printing, for column classes from `opts.schema`.
14    pub scopes: crate::schema::Scopes<'a>,
15    pub source: &'a str,
16    pub target: &'a str,
17    pub max_param: u32,
18    pub param_order: Vec<u32>,
19    /// True while printing the SET list of an upsert (so `excluded.c` can be spelled per target).
20    pub in_upsert: bool,
21    /// The printed (last-part) name of the INSERT's table while `in_upsert`: an unqualified column in
22    /// a MySQL-written SET list names the existing row, which PostgreSQL (ambiguous with `EXCLUDED`)
23    /// needs spelled `table.col`.
24    pub(crate) upsert_table: Option<String>,
25    /// Printed `ORDER BY` of the aggregate call being printed, for the function hook to consume.
26    /// A hook that does not `take()` it cannot honour the order, and the printer then refuses.
27    pub agg_order: Option<String>,
28    /// True while the ORDER BY item being printed is a column the schema says is not text (bytes,
29    /// numbers, dates): its ordering involves no text collation, so the target hook notes it `Exact`.
30    pub order_non_text: bool,
31    /// True while a `make_interval(unit => n)` call is printed as the right side of `ts +/- ..`: the
32    /// named notation is then only how PostgreSQL spells the interval, not a `named_arg` need.
33    pub interval_notation: bool,
34    /// True when the statement's `now()` calls are all compared with an epoch-seconds column, so the
35    /// target must give integer seconds.
36    pub epoch_now: bool,
37    /// Parameters used as arrays, with the binding the target requires.
38    pub array_params: std::collections::BTreeMap<u32, ParamBinding>,
39    /// Parameters used as plain values (a parameter must not be both).
40    pub scalar_params: std::collections::BTreeSet<u32>,
41}
42
43impl<'a> Ctx<'a> {
44    pub fn new(opts: &'a Options, source: &'a str, target: &'a str) -> Self {
45        Ctx {
46            report: Report::default(),
47            opts,
48            scopes: crate::schema::Scopes::new(opts.schema.as_ref()),
49            source,
50            target,
51            max_param: 0,
52            param_order: Vec::new(),
53            in_upsert: false,
54            upsert_table: None,
55            agg_order: None,
56            order_non_text: false,
57            interval_notation: false,
58            epoch_now: false,
59            array_params: Default::default(),
60            scalar_params: Default::default(),
61        }
62    }
63
64    /// Record how the target gives `construct`. `Refused` and an *ungranted* `Conditional` return an
65    /// error, so the caller `?`s and no SQL text is ever produced for them.
66    pub fn note(
67        &mut self,
68        construct: impl Into<String>,
69        tier: Tier,
70        note: impl Into<String>,
71        allowance: Option<Allowance>,
72    ) -> Result<(), Untranslatable> {
73        let construct = construct.into();
74        let note = note.into();
75        match tier {
76            Tier::Refused => Err(self.refuse(&construct, &note, &[])),
77            Tier::Conditional => {
78                let a = allowance.expect("a Conditional note must name its Allowance");
79                // Same dialect in and out is the identity: no assumption changes, so none is gated.
80                if self.source != self.target && !self.opts.allow.contains(&a) {
81                    return Err(self.refuse(
82                        &construct,
83                        &format!("conditional: needs allowance `{}`: {}", a.name(), note),
84                        &[],
85                    ));
86                }
87                self.report.push(Entry {
88                    construct,
89                    tier,
90                    note,
91                    allowance: Some(a),
92                });
93                Ok(())
94            }
95            _ => {
96                self.report.push(Entry {
97                    construct,
98                    tier,
99                    note,
100                    allowance,
101                });
102                Ok(())
103            }
104        }
105    }
106
107    /// Record that source parameter `n` is an array that the caller must bind as `binding`.
108    pub fn bind_array_param(&mut self, n: u32, binding: ParamBinding) {
109        self.array_params.insert(n, binding);
110    }
111
112    /// True for sources whose casts, division and comparisons are lenient or collation-dependent
113    /// in ways PostgreSQL's are not.
114    pub fn lenient_source(&self) -> bool {
115        matches!(self.source, "sqlite" | "mysql" | "mariadb")
116    }
117
118    pub fn refuse(&self, construct: &str, reason: &str, alternatives: &[&str]) -> Untranslatable {
119        Untranslatable {
120            construct: construct.to_string(),
121            source: self.source.to_string(),
122            target: self.target.to_string(),
123            reason: reason.to_string(),
124            alternatives: alternatives.iter().map(|s| s.to_string()).collect(),
125        }
126    }
127}
128
129type R<T> = Result<T, Untranslatable>;
130
131/// The kind of statement a clause belongs to (some clauses exist only for some kinds).
132#[derive(Clone, Copy, Debug, PartialEq, Eq)]
133pub enum StmtKind {
134    Insert,
135    Update,
136    Delete,
137}
138
139/// The escape character of a `LIKE`, as the IR states it.
140#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141pub enum Escape<'a> {
142    /// No escape character at all (the SQLite default).
143    None,
144    /// A backslash (the PostgreSQL default).
145    Default,
146    /// An explicit printed expression.
147    Custom(&'a str),
148}
149
150/// What a target dialect supplies. Every method has a PostgreSQL default.
151/// A target's way of writing `UPDATE|DELETE .. ORDER BY .. LIMIT n`.
152#[derive(Clone, Copy, Debug, PartialEq, Eq)]
153pub enum DmlLimit {
154    /// Trailing `ORDER BY .. LIMIT n` on the statement itself.
155    Native,
156    /// `WHERE <row id> IN (SELECT <row id> FROM t WHERE .. ORDER BY .. LIMIT n)`.
157    RowIdSubquery(&'static str),
158}
159
160/// A target's way of writing the extra tables of a multi-table `UPDATE` or `DELETE`.
161#[derive(Clone, Copy, Debug, PartialEq, Eq)]
162pub enum DmlSources {
163    /// `UPDATE t SET .. FROM f WHERE ..` and `DELETE FROM t USING f WHERE ..` (PostgreSQL).
164    FromClause,
165    /// `UPDATE t, f SET .. WHERE ..` and `DELETE t FROM t, f WHERE ..` (MySQL).
166    Join,
167    /// `UPDATE .. FROM` only; no `DELETE .. USING` (SQLite).
168    UpdateFromOnly,
169}
170
171pub trait Target {
172    fn name(&self) -> &'static str;
173
174    fn quote_ident(&self, s: &str) -> String {
175        format!("\"{}\"", s.replace('"', "\"\""))
176    }
177
178    fn string_literal(&self, s: &str) -> String {
179        format!("'{}'", s.replace('\'', "''"))
180    }
181
182    /// A byte-string literal. PostgreSQL has no hex literal of this type, so it casts an escape string.
183    fn bytes_literal(&self, b: &[u8]) -> String {
184        let hex: String = b.iter().map(|x| format!("{x:02x}")).collect();
185        format!("'\\x{hex}'::bytea")
186    }
187
188    /// Placeholder text for the 1-based parameter `n`.
189    fn placeholder(&self, n: u32) -> String {
190        format!("${n}")
191    }
192
193    fn bool_literal(&self, b: bool, _ctx: &mut Ctx) -> R<String> {
194        Ok(if b { "TRUE" } else { "FALSE" }.to_string())
195    }
196
197    /// `lhs [NOT] LIKE rhs` / `ILIKE`, operands already printed.
198    fn like(
199        &self,
200        lhs: &str,
201        rhs: &str,
202        negated: bool,
203        ci: bool,
204        esc: Escape<'_>,
205        ctx: &mut Ctx,
206    ) -> R<String> {
207        let kw = if ci { "ILIKE" } else { "LIKE" };
208        ctx.note(if ci { "ilike" } else { "like" }, Tier::Exact, "", None)?;
209        let tail = match esc {
210            Escape::Default => String::new(), // PostgreSQL's default escape is a backslash
211            Escape::None => " ESCAPE ''".to_string(),
212            Escape::Custom(c) => format!(" ESCAPE {c}"),
213        };
214        Ok(format!(
215            "{lhs} {}{kw} {rhs}{tail}",
216            if negated { "NOT " } else { "" }
217        ))
218    }
219
220    /// `lhs [NOT] REGEXP rhs`, operands already printed. The default is PostgreSQL's `~` / `!~`.
221    fn regexp(&self, lhs: &str, rhs: &str, negated: bool, ctx: &mut Ctx) -> R<String> {
222        ctx.note(
223            "regexp",
224            Tier::Conditional,
225            "regular-expression syntax and case sensitivity differ between engines; exact only for \
226             patterns in the common subset",
227            Some(Allowance::RegexpFlavor),
228        )?;
229        Ok(format!("{lhs} {} {rhs}", if negated { "!~" } else { "~" }))
230    }
231
232    /// A function call with arguments already printed. Return the full call text.
233    fn function(&self, f: &Function, args: &[String], ctx: &mut Ctx) -> R<String> {
234        // Same dialect in and out is the identity: the reader accepted the name. Otherwise the name
235        // must be on this target's verified list; a foreign function name is never passed through.
236        if ctx.source != self.name() && !PORTABLE_FUNCTIONS.contains(&f.name.as_str()) {
237            return Err(ctx.refuse(
238                &format!("fn:{}", f.name),
239                "no verified mapping for this function on this target yet",
240                &[],
241            ));
242        }
243        ctx.note(format!("fn:{}", f.name), Tier::Exact, "", None)?;
244        let order = ctx.agg_order.take();
245        Ok(generic_call_ordered(
246            &f.name,
247            args,
248            f.distinct,
249            f.star,
250            order.as_deref(),
251        ))
252    }
253
254    fn cast(&self, expr: &str, ty: &SqlType, ctx: &mut Ctx) -> R<String> {
255        if ctx.lenient_source() {
256            ctx.note(
257                format!("cast.to_{}", ty.leaf()),
258                Tier::Conditional,
259                "the source casts leniently (a malformed value becomes 0); the target raises an error",
260                Some(Allowance::LenientCast),
261            )?;
262        } else {
263            ctx.note(format!("cast.to_{}", ty.leaf()), Tier::Exact, "", None)?;
264        }
265        Ok(format!("CAST({expr} AS {})", pg_type_name(ty)))
266    }
267
268    fn distinct_on(&self, ctx: &mut Ctx) -> R<()> {
269        ctx.note("distinct_on", Tier::Exact, "", None)
270    }
271
272    /// The body of a `GROUP BY` with `WITH ROLLUP`, keys printed. Default (PostgreSQL):
273    /// `ROLLUP (a, b)`, exact.
274    fn group_by_rollup(&self, keys: &[String], ctx: &mut Ctx) -> R<String> {
275        ctx.note("group_by.rollup", Tier::Exact, "", None)?;
276        Ok(format!("ROLLUP ({})", keys.join(", ")))
277    }
278
279    /// `a <=> b` (null-safe equality), operands printed. Default (PostgreSQL): `IS NOT DISTINCT FROM`.
280    fn null_safe_eq(&self, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
281        ctx.note("null_safe_eq", Tier::Exact, "", None)?;
282        Ok(format!("{lhs} IS NOT DISTINCT FROM {rhs}"))
283    }
284
285    /// `EXTRACT(field FROM expr)`, operand printed. Default (PostgreSQL): exact, one leaf per field
286    /// (`extract.year`, `extract.epoch`, ...): a target maps a field only once it is verified.
287    fn extract(&self, field: &str, expr: &str, interval: bool, ctx: &mut Ctx) -> R<String> {
288        ctx.note(extract_leaf(field, interval), Tier::Exact, "", None)?;
289        Ok(format!("EXTRACT({} FROM {expr})", field.to_uppercase()))
290    }
291
292    /// `EXTRACT(EPOCH FROM a - b)`, operands printed: the seconds between two timestamps.
293    /// `None` (the default) means "no verified mapping": the printer then goes the generic way and
294    /// the `extract` hook decides (PostgreSQL writes it back, the others refuse).
295    fn epoch_of_difference(&self, _a: &str, _b: &str, _ctx: &mut Ctx) -> R<Option<String>> {
296        Ok(None)
297    }
298
299    /// `EXTRACT(EPOCH FROM clock_timestamp())`: the wall clock at the call, in seconds since the epoch
300    /// with the fraction. The default refuses; each target states how it reads its clock.
301    fn epoch_of_clock(&self, ctx: &mut Ctx) -> R<String> {
302        Err(ctx.refuse(
303            "extract.epoch",
304            "no mapping for the per-call wall clock",
305            &["bind the time as a parameter"],
306        ))
307    }
308
309    /// `ARRAY[..]`, elements printed. Default (PostgreSQL): exact; a target without an array type
310    /// refuses the leaf `array_literal`.
311    fn array_literal(&self, items: &[String], ctx: &mut Ctx) -> R<String> {
312        ctx.note("array_literal", Tier::Exact, "", None)?;
313        Ok(format!("ARRAY[{}]", items.join(", ")))
314    }
315
316    /// A table-valued function in FROM (`generate_series`, `jsonb_object_keys`, `unnest`, ...). Default
317    /// (PostgreSQL): exact, one leaf per function (`table_function.<name>`). A target that has not
318    /// verified the function refuses that leaf.
319    fn table_function(&self, name: &str, ctx: &mut Ctx) -> R<()> {
320        ctx.note(format!("table_function.{name}"), Tier::Exact, "", None)
321    }
322
323    /// Whether `FROM generate_series(a, b[, step])` with integer literal arguments and an alias may be
324    /// written as a derived table over a recursive CTE. Default (PostgreSQL): no, it is native there.
325    fn series_as_recursive_cte(&self) -> bool {
326        false
327    }
328
329    /// `expr AT TIME ZONE zone`. Default (PostgreSQL): exact. A target without it refuses the leaf
330    /// `at_time_zone`.
331    fn at_time_zone(&self, ctx: &mut Ctx) -> R<()> {
332        ctx.note("at_time_zone", Tier::Exact, "", None)
333    }
334
335    /// `ARRAY(SELECT ..)`. Default (PostgreSQL): exact. A target without an array type refuses the
336    /// leaf `array_subquery`.
337    fn array_subquery(&self, ctx: &mut Ctx) -> R<()> {
338        ctx.note("array_subquery", Tier::Exact, "", None)
339    }
340
341    /// `WITH .. INSERT | UPDATE | DELETE ..` (the common table expressions precede the modifying
342    /// statement). The default (PostgreSQL) has all three; each is its own leaf: `with.insert`,
343    /// `with.update`, `with.delete`.
344    fn with_statement(&self, kind: StmtKind, ctx: &mut Ctx) -> R<()> {
345        ctx.note(with_leaf(kind), Tier::Exact, "", None)
346    }
347
348    /// `WITH x AS (INSERT/UPDATE/DELETE .. RETURNING ..) ..`. The default (PostgreSQL) has it; a
349    /// target without it refuses the leaf `cte.data_modifying`.
350    fn data_modifying_cte(&self, ctx: &mut Ctx) -> R<()> {
351        ctx.note("cte.data_modifying", Tier::Exact, "", None)
352    }
353
354    /// A row-locking clause. The default (PostgreSQL) gives every form; each form is its own leaf:
355    /// `row_lock` (FOR UPDATE), `row_lock.share`, `row_lock.of`, `row_lock.nowait`,
356    /// `row_lock.skip_locked`.
357    fn row_lock(&self, lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
358        note_row_lock_leaves(lock, ctx)
359    }
360
361    fn returning(&self, _kind: StmtKind, ctx: &mut Ctx) -> R<()> {
362        ctx.note("returning", Tier::Exact, "", None)
363    }
364
365    /// `LIMIT`/`OFFSET` tail; operands already printed. Returns `""` when neither is present.
366    fn limit_offset(&self, limit: Option<&str>, offset: Option<&str>, ctx: &mut Ctx) -> R<String> {
367        let mut s = String::new();
368        if let Some(l) = limit {
369            s.push_str(&format!(" LIMIT {l}"));
370            ctx.note("limit", Tier::Exact, "", None)?;
371        }
372        if let Some(o) = offset {
373            s.push_str(&format!(" OFFSET {o}"));
374            ctx.note("offset", Tier::Exact, "", None)?;
375        }
376        Ok(s)
377    }
378
379    /// Tier of a join kind on this target (SQLite lacks RIGHT/FULL before 3.39).
380    fn join_tier(&self, _kind: JoinKind) -> Tier {
381        Tier::Exact
382    }
383
384    /// How the extra tables of a multi-table `UPDATE` or `DELETE` are written.
385    fn dml_sources(&self) -> DmlSources {
386        DmlSources::FromClause
387    }
388
389    /// How `UPDATE|DELETE .. ORDER BY .. LIMIT n` is written. The default (PostgreSQL) has no
390    /// direct form: the row is picked by its physical identifier in a subquery.
391    fn dml_limit(&self) -> DmlLimit {
392        DmlLimit::RowIdSubquery("ctid")
393    }
394
395    /// Whole-query rewrite before printing (for example `DISTINCT ON` via a window function).
396    /// Return `Some(q2)` to print `q2` instead; `q2` must not trigger the same rewrite again.
397    fn rewrite_query(&self, _q: &Query, _ctx: &mut Ctx) -> R<Option<Query>> {
398        Ok(None)
399    }
400
401    /// A feature the printer is about to emit: `window_function`, `filter_clause`,
402    /// `recursive_cte`, `named_arg`. Default: exact (PostgreSQL).
403    fn feature(&self, name: &'static str, ctx: &mut Ctx) -> R<()> {
404        ctx.note(name, Tier::Exact, "", None)
405    }
406
407    /// `TRIM(..)` with operands already printed.
408    fn trim(&self, side: TrimSide, expr: &str, chars: Option<&str>, ctx: &mut Ctx) -> R<String> {
409        ctx.note("trim", Tier::Exact, "", None)?;
410        Ok(match (side, chars) {
411            (TrimSide::Both, None) => format!("TRIM({expr})"),
412            (s, c) => {
413                let kw = match s {
414                    TrimSide::Both => "BOTH",
415                    TrimSide::Leading => "LEADING",
416                    TrimSide::Trailing => "TRAILING",
417                };
418                match c {
419                    Some(c) => format!("TRIM({kw} {c} FROM {expr})"),
420                    None => format!("TRIM({kw} FROM {expr})"),
421                }
422            }
423        })
424    }
425
426    /// `left (+|-) make_interval(parts..)`; `parts` are (unit, printed value). Return `Some(text)`
427    /// to replace the whole expression, `None` to print it the generic way.
428    fn interval_arith(
429        &self,
430        _minus: bool,
431        _left: &str,
432        _parts: &[(String, String)],
433        _ctx: &mut Ctx,
434    ) -> R<Option<String>> {
435        Ok(None)
436    }
437
438    /// JSON `->` / `->>` with operands printed. Default: PostgreSQL.
439    fn json_access(&self, text: bool, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
440        ctx.note(
441            if text { "json_get_text" } else { "json_get" },
442            Tier::Exact,
443            "",
444            None,
445        )?;
446        Ok(format!("{lhs} {} {rhs}", if text { "->>" } else { "->" }))
447    }
448
449    /// JSON `#>` / `#>>` with operands printed. Default: PostgreSQL.
450    fn json_path_access(&self, text: bool, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
451        ctx.note(
452            if text { "json_path_text" } else { "json_path" },
453            Tier::Exact,
454            "",
455            None,
456        )?;
457        Ok(format!("{lhs} {} {rhs}", if text { "#>>" } else { "#>" }))
458    }
459
460    /// Replace the default `l OP r` text for a binary operator (for example `||` -> `CONCAT`,
461    /// `/` -> `DIV`). Operands are already printed. Return `None` for the default.
462    fn binary_override(
463        &self,
464        _op: BinaryOp,
465        _l: &str,
466        _r: &str,
467        _numeric: bool,
468        _ctx: &mut Ctx,
469    ) -> R<Option<String>> {
470        Ok(None)
471    }
472
473    /// One ORDER BY item with its direction and NULL placement. `nulls_first` is explicit.
474    fn order_item(&self, expr: &str, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
475        let mut s = expr.to_string();
476        if desc {
477            s.push_str(" DESC");
478        }
479        s.push_str(&self.nulls_order(desc, nulls_first, ctx)?);
480        Ok(s)
481    }
482
483    /// The native spelling of an insert that replaces conflicting rows (`REPLACE INTO` on MySQL and
484    /// MariaDB, `INSERT OR REPLACE INTO` on SQLite). `None` (the default, PostgreSQL) means there is
485    /// none: the printer then writes an upsert when the schema states the table's columns and its
486    /// one unique key, and refuses (leaf `replace_into`) otherwise.
487    fn replace_keyword(&self) -> Option<&'static str> {
488        None
489    }
490
491    /// Whether an upsert must name its conflict key columns (PostgreSQL and SQLite do; MySQL and
492    /// MariaDB fire on any unique key). When it does and the source stated none, the printer takes
493    /// the key from the schema if the table has exactly one stated unique key.
494    fn needs_conflict_key(&self) -> bool {
495        true
496    }
497
498    /// How the SET list of an upsert refers to the value that was proposed for insertion.
499    fn excluded_ref(&self, column_quoted: &str) -> String {
500        format!("EXCLUDED.{column_quoted}")
501    }
502
503    /// Whether an upsert's `WHERE` has no native spelling and is written into the `SET` expressions as
504    /// `col = IF(cond, new, col)` (MySQL and MariaDB). The printer does the rewrite.
505    fn upsert_where_as_if(&self) -> bool {
506        false
507    }
508
509    /// The whole `ON CONFLICT ..` clause. `set` and `where_` are printed; `columns` are quoted.
510    #[allow(
511        clippy::too_many_arguments,
512        reason = "each argument is a distinct clause of the ON CONFLICT form; a parameter struct would only rename them"
513    )]
514    fn upsert_clause(
515        &self,
516        conflict_cols: &[String],
517        do_nothing: bool,
518        set: &str,
519        where_: Option<&str>,
520        _first_insert_col: &str,
521        ctx: &mut Ctx,
522    ) -> R<String> {
523        if !do_nothing && conflict_cols.is_empty() {
524            return Err(ctx.refuse(
525                "upsert.no_conflict_key",
526                "the source upsert names no conflict key (MySQL ON DUPLICATE KEY UPDATE fires on any unique key); this target needs the key columns, and the schema does not state exactly one unique key for the table",
527                &["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)"],
528            ));
529        }
530        ctx.note(
531            if where_.is_some() {
532                "upsert_where"
533            } else {
534                "upsert"
535            },
536            Tier::Exact,
537            "",
538            None,
539        )?;
540        let mut s = String::from(" ON CONFLICT");
541        if !conflict_cols.is_empty() {
542            s.push_str(&format!(" ({})", conflict_cols.join(", ")));
543        }
544        if do_nothing {
545            s.push_str(" DO NOTHING");
546        } else {
547            s.push_str(&format!(" DO UPDATE SET {set}"));
548            if let Some(w) = where_ {
549                s.push_str(&format!(" WHERE {w}"));
550            }
551        }
552        Ok(s)
553    }
554
555    /// Membership in an array parameter: `lhs = ANY(ph)` (or `<> ALL` when `negated`). The target
556    /// must record how the caller binds parameter `n` via [`Ctx::bind_array_param`]. **The default
557    /// refuses**: a target with no array codec has no honest translation.
558    fn array_membership(
559        &self,
560        _lhs: &str,
561        _ph: &str,
562        _negated: bool,
563        n: u32,
564        ctx: &mut Ctx,
565    ) -> R<String> {
566        Err(ctx.refuse(
567            "array_param",
568            &format!(
569                "target `{}` has no codec for an array parameter (${n})",
570                ctx.target
571            ),
572            &["expand the array into an IN (..) list in the application"],
573        ))
574    }
575
576    /// Hook for `[NOT] BETWEEN`. `numeric` is true when an operand is syntactically numeric (so no
577    /// text collation is involved). Default: exact.
578    fn between(&self, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
579        Ok(())
580    }
581
582    /// Hook for operators whose meaning differs. `numeric` is true when an operand is syntactically
583    /// numeric (a number literal, arithmetic, or a numeric aggregate). Default: exact.
584    fn binary_op(&self, _op: BinaryOp, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
585        Ok(())
586    }
587
588    /// Text for one ORDER BY item's null-ordering suffix, `""` for none. `nulls_first` is always
589    /// explicit after reading (the reader fills in the source dialect's default).
590    fn nulls_order(&self, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
591        // PostgreSQL default: NULLs are the largest value (last ascending, first descending).
592        let default_first = desc;
593        ctx.note("null_ordering", Tier::Exact, "", None)?;
594        if nulls_first == default_first {
595            Ok(String::new())
596        } else {
597            Ok(if nulls_first {
598                " NULLS FIRST"
599            } else {
600                " NULLS LAST"
601            }
602            .to_string())
603        }
604    }
605}
606
607/// Functions with the same name and meaning on every dialect UniSQL targets so far.
608pub const PORTABLE_FUNCTIONS: &[&str] = &[
609    "count",
610    "sum",
611    "min",
612    "max",
613    "avg",
614    "coalesce",
615    "nullif",
616    "abs",
617    "lower",
618    "upper",
619    "length",
620    "replace",
621    "substr",
622    "row_number",
623    "rank",
624    "dense_rank",
625    "percent_rank",
626    "cume_dist",
627    "ntile",
628    "lag",
629    "lead",
630    "first_value",
631    "last_value",
632    "nth_value",
633    // `strpos(haystack, needle)`: the IR name for MySQL `LOCATE`/`INSTR`, `POSITION(.. IN ..)` and
634    // SQLite `instr`; each writer spells it natively or refuses.
635    "strpos",
636    // `ceil` / `floor` of a number (the reader normalises CEILING).
637    "ceil",
638    "floor",
639];
640
641pub fn generic_call(name: &str, args: &[String], distinct: bool, star: bool) -> String {
642    generic_call_ordered(name, args, distinct, star, None)
643}
644
645/// `NAME([DISTINCT] args [ORDER BY ..])`.
646pub fn generic_call_ordered(
647    name: &str,
648    args: &[String],
649    distinct: bool,
650    star: bool,
651    order: Option<&str>,
652) -> String {
653    let ord = order.map(|o| format!(" ORDER BY {o}")).unwrap_or_default();
654    if star {
655        return format!("{}(*)", name.to_uppercase());
656    }
657    format!(
658        "{}({}{}{})",
659        name.to_uppercase(),
660        if distinct { "DISTINCT " } else { "" },
661        args.join(", "),
662        ord
663    )
664}
665
666/// PostgreSQL's spelling of a type.
667pub fn pg_type_name(ty: &SqlType) -> String {
668    match ty {
669        SqlType::SmallInt => "SMALLINT".into(),
670        SqlType::Integer => "INTEGER".into(),
671        SqlType::BigInt => "BIGINT".into(),
672        SqlType::Real => "REAL".into(),
673        SqlType::Double => "DOUBLE PRECISION".into(),
674        SqlType::Numeric {
675            precision: None, ..
676        } => "NUMERIC".into(),
677        SqlType::Numeric {
678            precision: Some(p),
679            scale: None,
680        } => format!("NUMERIC({p})"),
681        SqlType::Numeric {
682            precision: Some(p),
683            scale: Some(s),
684        } => format!("NUMERIC({p}, {s})"),
685        SqlType::Text => "TEXT".into(),
686        SqlType::Varchar(None) => "VARCHAR".into(),
687        SqlType::Varchar(Some(n)) => format!("VARCHAR({n})"),
688        SqlType::Boolean => "BOOLEAN".into(),
689        SqlType::Date => "DATE".into(),
690        SqlType::Timestamp { with_tz: false } => "TIMESTAMP".into(),
691        SqlType::Timestamp { with_tz: true } => "TIMESTAMPTZ".into(),
692        SqlType::Uuid => "UUID".into(),
693        SqlType::Regclass => "REGCLASS".into(),
694        SqlType::Bytes => "BYTEA".into(),
695        SqlType::Json => "JSON".into(),
696        SqlType::Jsonb => "JSONB".into(),
697    }
698}
699
700/// The argument at `i` when it is a non-negative integer literal.
701pub fn literal_count(f: &Function, i: usize) -> Option<u64> {
702    match f.args.get(i) {
703        Some(FunctionArg::Expr(Expr::Literal(Literal::Number(n)))) => n.parse().ok(),
704        _ => None,
705    }
706}
707
708/// The argument at `i` when it is a non-empty string literal.
709pub fn literal_nonempty_string(f: &Function, i: usize) -> bool {
710    matches!(
711        f.args.get(i),
712        Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) if !s.is_empty()
713    )
714}
715
716/// The argument at `i` when it is a string literal of exactly one character.
717pub fn literal_single_char_string(f: &Function, i: usize) -> bool {
718    matches!(
719        f.args.get(i),
720        Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) if s.chars().count() == 1
721    )
722}
723
724/// The fractional-second precision written in `UTC_TIMESTAMP(p)`: `Some(0)` when absent, `None`
725/// when it is not an integer literal.
726pub fn utc_timestamp_precision(f: &Function) -> Option<u32> {
727    match f.args.as_slice() {
728        [] => Some(0),
729        [FunctionArg::Expr(Expr::Literal(Literal::Number(n)))] => n.parse().ok(),
730        _ => None,
731    }
732}
733
734/// `date_trunc('<field>', x)` with a literal field: that field, lower-cased.
735pub fn date_trunc_field(f: &Function) -> Option<String> {
736    if f.name != "date_trunc" {
737        return None;
738    }
739    match f.args.first() {
740        Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) => Some(s.to_ascii_lowercase()),
741        _ => None,
742    }
743}
744
745/// `to_char(ts, '<format>')` with a literal format made only of `YYYY`, `MM`, `DD`, `HH24`, `MI`,
746/// `SS` and the separators `- / : . ,` and space: the format in the target's own specifiers
747/// (`[year, month, day, hour, minute, second]`). `None` for any other format, which has no verified
748/// mapping.
749pub fn to_char_format(f: &Function, spec: [&str; 6]) -> Option<String> {
750    if f.name != "to_char" || f.args.len() != 2 {
751        return None;
752    }
753    let Some(FunctionArg::Expr(Expr::Literal(Literal::String(fmt)))) = f.args.get(1) else {
754        return None;
755    };
756    let mut out = String::new();
757    let mut rest = fmt.as_str();
758    while !rest.is_empty() {
759        let tokens = [
760            ("YYYY", spec[0]),
761            ("MM", spec[1]),
762            ("DD", spec[2]),
763            ("HH24", spec[3]),
764            ("MI", spec[4]),
765            ("SS", spec[5]),
766        ];
767        if let Some((tok, s)) = tokens.iter().find(|(t, _)| rest.starts_with(t)) {
768            out.push_str(s);
769            rest = &rest[tok.len()..];
770        } else {
771            let c = rest.chars().next()?;
772            if !matches!(c, '-' | '/' | ':' | '.' | ',' | ' ') {
773                return None;
774            }
775            out.push(c);
776            rest = &rest[1..];
777        }
778    }
779    Some(out)
780}
781
782/// The leaf of `EXTRACT(field FROM x)`: `extract.<field>`, and `extract.epoch.interval` when the operand
783/// is a difference of timestamps (an interval), which is not the epoch of a timestamp.
784pub fn extract_leaf(field: &str, interval: bool) -> String {
785    if interval && field == "epoch" {
786        "extract.epoch.interval".to_string()
787    } else {
788        format!("extract.{field}")
789    }
790}
791
792/// The base leaf of a locking clause: `row_lock` for FOR UPDATE, `row_lock.share` for FOR SHARE.
793pub fn row_lock_leaf(lock: &RowLockClause) -> &'static str {
794    match lock.strength {
795        RowLock::Update => "row_lock",
796        RowLock::Share => "row_lock.share",
797    }
798}
799
800/// Records every leaf a locking clause uses (the same set `needs::constructs` names), all Exact.
801pub fn note_row_lock_leaves(lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
802    ctx.note(row_lock_leaf(lock), Tier::Exact, "", None)?;
803    if lock.of.is_some() {
804        ctx.note("row_lock.of", Tier::Exact, "", None)?;
805    }
806    match lock.wait {
807        LockWait::Block => {}
808        LockWait::NoWait => ctx.note("row_lock.nowait", Tier::Exact, "", None)?,
809        LockWait::SkipLocked => ctx.note("row_lock.skip_locked", Tier::Exact, "", None)?,
810    }
811    Ok(())
812}
813
814/// The leaf of `WITH .. <statement>`.
815pub fn with_leaf(kind: StmtKind) -> &'static str {
816    match kind {
817        StmtKind::Insert => "with.insert",
818        StmtKind::Update => "with.update",
819        StmtKind::Delete => "with.delete",
820    }
821}