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