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