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    /// Placeholder text for the 1-based parameter `n`.
155    fn placeholder(&self, n: u32) -> String {
156        format!("${n}")
157    }
158
159    fn bool_literal(&self, b: bool, _ctx: &mut Ctx) -> R<String> {
160        Ok(if b { "TRUE" } else { "FALSE" }.to_string())
161    }
162
163    /// `lhs [NOT] LIKE rhs` / `ILIKE`, operands already printed.
164    fn like(
165        &self,
166        lhs: &str,
167        rhs: &str,
168        negated: bool,
169        ci: bool,
170        esc: Escape<'_>,
171        ctx: &mut Ctx,
172    ) -> R<String> {
173        let kw = if ci { "ILIKE" } else { "LIKE" };
174        ctx.note(if ci { "ilike" } else { "like" }, Tier::Exact, "", None)?;
175        let tail = match esc {
176            Escape::Default => String::new(), // PostgreSQL's default escape is a backslash
177            Escape::None => " ESCAPE ''".to_string(),
178            Escape::Custom(c) => format!(" ESCAPE {c}"),
179        };
180        Ok(format!(
181            "{lhs} {}{kw} {rhs}{tail}",
182            if negated { "NOT " } else { "" }
183        ))
184    }
185
186    /// A function call with arguments already printed. Return the full call text.
187    fn function(&self, f: &Function, args: &[String], ctx: &mut Ctx) -> R<String> {
188        // Same dialect in and out is the identity: the reader accepted the name. Otherwise the name
189        // must be on this target's verified list; a foreign function name is never passed through.
190        if ctx.source != self.name() && !PORTABLE_FUNCTIONS.contains(&f.name.as_str()) {
191            return Err(ctx.refuse(
192                &format!("fn:{}", f.name),
193                "no verified mapping for this function on this target yet",
194                &[],
195            ));
196        }
197        ctx.note(format!("fn:{}", f.name), Tier::Exact, "", None)?;
198        let order = ctx.agg_order.take();
199        Ok(generic_call_ordered(
200            &f.name,
201            args,
202            f.distinct,
203            f.star,
204            order.as_deref(),
205        ))
206    }
207
208    fn cast(&self, expr: &str, ty: &SqlType, ctx: &mut Ctx) -> R<String> {
209        if ctx.lenient_source() {
210            ctx.note(
211                format!("cast.to_{}", ty.leaf()),
212                Tier::Conditional,
213                "the source casts leniently (a malformed value becomes 0); the target raises an error",
214                Some(Allowance::LenientCast),
215            )?;
216        } else {
217            ctx.note(format!("cast.to_{}", ty.leaf()), Tier::Exact, "", None)?;
218        }
219        Ok(format!("CAST({expr} AS {})", pg_type_name(ty)))
220    }
221
222    fn distinct_on(&self, ctx: &mut Ctx) -> R<()> {
223        ctx.note("distinct_on", Tier::Exact, "", None)
224    }
225
226    /// `a <=> b` (null-safe equality), operands printed. Default (PostgreSQL): `IS NOT DISTINCT FROM`.
227    fn null_safe_eq(&self, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
228        ctx.note("null_safe_eq", Tier::Exact, "", None)?;
229        Ok(format!("{lhs} IS NOT DISTINCT FROM {rhs}"))
230    }
231
232    /// `EXTRACT(field FROM expr)`, operand printed. Default (PostgreSQL): exact, one leaf per field
233    /// (`extract.year`, `extract.epoch`, ...): a target maps a field only once it is verified.
234    fn extract(&self, field: &str, expr: &str, interval: bool, ctx: &mut Ctx) -> R<String> {
235        ctx.note(extract_leaf(field, interval), Tier::Exact, "", None)?;
236        Ok(format!("EXTRACT({} FROM {expr})", field.to_uppercase()))
237    }
238
239    /// `EXTRACT(EPOCH FROM a - b)`, operands printed: the seconds between two timestamps.
240    /// `None` (the default) means "no verified mapping": the printer then goes the generic way and
241    /// the `extract` hook decides (PostgreSQL writes it back, the others refuse).
242    fn epoch_of_difference(&self, _a: &str, _b: &str, _ctx: &mut Ctx) -> R<Option<String>> {
243        Ok(None)
244    }
245
246    /// `ARRAY[..]`, elements printed. Default (PostgreSQL): exact; a target without an array type
247    /// refuses the leaf `array_literal`.
248    fn array_literal(&self, items: &[String], ctx: &mut Ctx) -> R<String> {
249        ctx.note("array_literal", Tier::Exact, "", None)?;
250        Ok(format!("ARRAY[{}]", items.join(", ")))
251    }
252
253    /// A table-valued function in FROM (`generate_series`, `jsonb_object_keys`, `unnest`, ...). Default
254    /// (PostgreSQL): exact, one leaf per function (`table_function.<name>`). A target that has not
255    /// verified the function refuses that leaf.
256    fn table_function(&self, name: &str, ctx: &mut Ctx) -> R<()> {
257        ctx.note(format!("table_function.{name}"), Tier::Exact, "", None)
258    }
259
260    /// `expr AT TIME ZONE zone`. Default (PostgreSQL): exact. A target without it refuses the leaf
261    /// `at_time_zone`.
262    fn at_time_zone(&self, ctx: &mut Ctx) -> R<()> {
263        ctx.note("at_time_zone", Tier::Exact, "", None)
264    }
265
266    /// `ARRAY(SELECT ..)`. Default (PostgreSQL): exact. A target without an array type refuses the
267    /// leaf `array_subquery`.
268    fn array_subquery(&self, ctx: &mut Ctx) -> R<()> {
269        ctx.note("array_subquery", Tier::Exact, "", None)
270    }
271
272    /// `WITH .. INSERT | UPDATE | DELETE ..` (the common table expressions precede the modifying
273    /// statement). The default (PostgreSQL) has all three; each is its own leaf: `with.insert`,
274    /// `with.update`, `with.delete`.
275    fn with_statement(&self, kind: StmtKind, ctx: &mut Ctx) -> R<()> {
276        ctx.note(with_leaf(kind), Tier::Exact, "", None)
277    }
278
279    /// `WITH x AS (INSERT/UPDATE/DELETE .. RETURNING ..) ..`. The default (PostgreSQL) has it; a
280    /// target without it refuses the leaf `cte.data_modifying`.
281    fn data_modifying_cte(&self, ctx: &mut Ctx) -> R<()> {
282        ctx.note("cte.data_modifying", Tier::Exact, "", None)
283    }
284
285    /// A row-locking clause. The default (PostgreSQL) gives every form; each form is its own leaf:
286    /// `row_lock` (FOR UPDATE), `row_lock.share`, `row_lock.of`, `row_lock.nowait`,
287    /// `row_lock.skip_locked`.
288    fn row_lock(&self, lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
289        note_row_lock_leaves(lock, ctx)
290    }
291
292    fn returning(&self, _kind: StmtKind, ctx: &mut Ctx) -> R<()> {
293        ctx.note("returning", Tier::Exact, "", None)
294    }
295
296    /// `LIMIT`/`OFFSET` tail; operands already printed. Returns `""` when neither is present.
297    fn limit_offset(&self, limit: Option<&str>, offset: Option<&str>, ctx: &mut Ctx) -> R<String> {
298        let mut s = String::new();
299        if let Some(l) = limit {
300            s.push_str(&format!(" LIMIT {l}"));
301            ctx.note("limit", Tier::Exact, "", None)?;
302        }
303        if let Some(o) = offset {
304            s.push_str(&format!(" OFFSET {o}"));
305            ctx.note("offset", Tier::Exact, "", None)?;
306        }
307        Ok(s)
308    }
309
310    /// Tier of a join kind on this target (SQLite lacks RIGHT/FULL before 3.39).
311    fn join_tier(&self, _kind: JoinKind) -> Tier {
312        Tier::Exact
313    }
314
315    /// Tier of `UPDATE .. FROM`.
316    fn update_from_tier(&self) -> Tier {
317        Tier::Exact
318    }
319
320    /// Whole-query rewrite before printing (for example `DISTINCT ON` via a window function).
321    /// Return `Some(q2)` to print `q2` instead; `q2` must not trigger the same rewrite again.
322    fn rewrite_query(&self, _q: &Query, _ctx: &mut Ctx) -> R<Option<Query>> {
323        Ok(None)
324    }
325
326    /// A feature the printer is about to emit: `window_function`, `filter_clause`,
327    /// `recursive_cte`, `named_arg`. Default: exact (PostgreSQL).
328    fn feature(&self, name: &'static str, ctx: &mut Ctx) -> R<()> {
329        ctx.note(name, Tier::Exact, "", None)
330    }
331
332    /// `TRIM(..)` with operands already printed.
333    fn trim(&self, side: TrimSide, expr: &str, chars: Option<&str>, ctx: &mut Ctx) -> R<String> {
334        ctx.note("trim", Tier::Exact, "", None)?;
335        Ok(match (side, chars) {
336            (TrimSide::Both, None) => format!("TRIM({expr})"),
337            (s, c) => {
338                let kw = match s {
339                    TrimSide::Both => "BOTH",
340                    TrimSide::Leading => "LEADING",
341                    TrimSide::Trailing => "TRAILING",
342                };
343                match c {
344                    Some(c) => format!("TRIM({kw} {c} FROM {expr})"),
345                    None => format!("TRIM({kw} FROM {expr})"),
346                }
347            }
348        })
349    }
350
351    /// `left (+|-) make_interval(parts..)`; `parts` are (unit, printed value). Return `Some(text)`
352    /// to replace the whole expression, `None` to print it the generic way.
353    fn interval_arith(
354        &self,
355        _minus: bool,
356        _left: &str,
357        _parts: &[(String, String)],
358        _ctx: &mut Ctx,
359    ) -> R<Option<String>> {
360        Ok(None)
361    }
362
363    /// JSON `->` / `->>` with operands printed. Default: PostgreSQL.
364    fn json_access(&self, text: bool, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
365        ctx.note(
366            if text { "json_get_text" } else { "json_get" },
367            Tier::Exact,
368            "",
369            None,
370        )?;
371        Ok(format!("{lhs} {} {rhs}", if text { "->>" } else { "->" }))
372    }
373
374    /// Replace the default `l OP r` text for a binary operator (for example `||` -> `CONCAT`,
375    /// `/` -> `DIV`). Operands are already printed. Return `None` for the default.
376    fn binary_override(
377        &self,
378        _op: BinaryOp,
379        _l: &str,
380        _r: &str,
381        _numeric: bool,
382        _ctx: &mut Ctx,
383    ) -> R<Option<String>> {
384        Ok(None)
385    }
386
387    /// One ORDER BY item with its direction and NULL placement. `nulls_first` is explicit.
388    fn order_item(&self, expr: &str, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
389        let mut s = expr.to_string();
390        if desc {
391            s.push_str(" DESC");
392        }
393        s.push_str(&self.nulls_order(desc, nulls_first, ctx)?);
394        Ok(s)
395    }
396
397    /// The native spelling of an insert that replaces conflicting rows (`REPLACE INTO` on MySQL and
398    /// MariaDB, `INSERT OR REPLACE INTO` on SQLite). `None` (the default, PostgreSQL) means there is
399    /// none: the printer then writes an upsert when the schema states the table's columns and its
400    /// one unique key, and refuses (leaf `replace_into`) otherwise.
401    fn replace_keyword(&self) -> Option<&'static str> {
402        None
403    }
404
405    /// Whether an upsert must name its conflict key columns (PostgreSQL and SQLite do; MySQL and
406    /// MariaDB fire on any unique key). When it does and the source stated none, the printer takes
407    /// the key from the schema if the table has exactly one stated unique key.
408    fn needs_conflict_key(&self) -> bool {
409        true
410    }
411
412    /// How the SET list of an upsert refers to the value that was proposed for insertion.
413    fn excluded_ref(&self, column_quoted: &str) -> String {
414        format!("EXCLUDED.{column_quoted}")
415    }
416
417    /// The whole `ON CONFLICT ..` clause. `set` and `where_` are printed; `columns` are quoted.
418    #[allow(clippy::too_many_arguments)]
419    fn upsert_clause(
420        &self,
421        conflict_cols: &[String],
422        do_nothing: bool,
423        set: &str,
424        where_: Option<&str>,
425        _first_insert_col: &str,
426        ctx: &mut Ctx,
427    ) -> R<String> {
428        if !do_nothing && conflict_cols.is_empty() {
429            return Err(ctx.refuse(
430                "upsert.no_conflict_key",
431                "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",
432                &["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)"],
433            ));
434        }
435        ctx.note(
436            if where_.is_some() {
437                "upsert_where"
438            } else {
439                "upsert"
440            },
441            Tier::Exact,
442            "",
443            None,
444        )?;
445        let mut s = String::from(" ON CONFLICT");
446        if !conflict_cols.is_empty() {
447            s.push_str(&format!(" ({})", conflict_cols.join(", ")));
448        }
449        if do_nothing {
450            s.push_str(" DO NOTHING");
451        } else {
452            s.push_str(&format!(" DO UPDATE SET {set}"));
453            if let Some(w) = where_ {
454                s.push_str(&format!(" WHERE {w}"));
455            }
456        }
457        Ok(s)
458    }
459
460    /// Membership in an array parameter: `lhs = ANY(ph)` (or `<> ALL` when `negated`). The target
461    /// must record how the caller binds parameter `n` via [`Ctx::bind_array_param`]. **The default
462    /// refuses**: a target with no array codec has no honest translation.
463    fn array_membership(
464        &self,
465        _lhs: &str,
466        _ph: &str,
467        _negated: bool,
468        n: u32,
469        ctx: &mut Ctx,
470    ) -> R<String> {
471        Err(ctx.refuse(
472            "array_param",
473            &format!(
474                "target `{}` has no codec for an array parameter (${n})",
475                ctx.target
476            ),
477            &["expand the array into an IN (..) list in the application"],
478        ))
479    }
480
481    /// Hook for `[NOT] BETWEEN`. `numeric` is true when an operand is syntactically numeric (so no
482    /// text collation is involved). Default: exact.
483    fn between(&self, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
484        Ok(())
485    }
486
487    /// Hook for operators whose meaning differs. `numeric` is true when an operand is syntactically
488    /// numeric (a number literal, arithmetic, or a numeric aggregate). Default: exact.
489    fn binary_op(&self, _op: BinaryOp, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
490        Ok(())
491    }
492
493    /// Text for one ORDER BY item's null-ordering suffix, `""` for none. `nulls_first` is always
494    /// explicit after reading (the reader fills in the source dialect's default).
495    fn nulls_order(&self, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
496        // PostgreSQL default: NULLs are the largest value (last ascending, first descending).
497        let default_first = desc;
498        ctx.note("null_ordering", Tier::Exact, "", None)?;
499        if nulls_first == default_first {
500            Ok(String::new())
501        } else {
502            Ok(if nulls_first {
503                " NULLS FIRST"
504            } else {
505                " NULLS LAST"
506            }
507            .to_string())
508        }
509    }
510}
511
512/// Functions with the same name and meaning on every dialect UniSQL targets so far.
513pub const PORTABLE_FUNCTIONS: &[&str] = &[
514    "count",
515    "sum",
516    "min",
517    "max",
518    "avg",
519    "coalesce",
520    "nullif",
521    "abs",
522    "lower",
523    "upper",
524    "length",
525    "replace",
526    "substr",
527    "row_number",
528    "rank",
529    "dense_rank",
530    "percent_rank",
531    "cume_dist",
532    "ntile",
533    "lag",
534    "lead",
535    "first_value",
536    "last_value",
537    "nth_value",
538];
539
540pub fn generic_call(name: &str, args: &[String], distinct: bool, star: bool) -> String {
541    generic_call_ordered(name, args, distinct, star, None)
542}
543
544/// `NAME([DISTINCT] args [ORDER BY ..])`.
545pub fn generic_call_ordered(
546    name: &str,
547    args: &[String],
548    distinct: bool,
549    star: bool,
550    order: Option<&str>,
551) -> String {
552    let ord = order.map(|o| format!(" ORDER BY {o}")).unwrap_or_default();
553    if star {
554        return format!("{}(*)", name.to_uppercase());
555    }
556    format!(
557        "{}({}{}{})",
558        name.to_uppercase(),
559        if distinct { "DISTINCT " } else { "" },
560        args.join(", "),
561        ord
562    )
563}
564
565/// PostgreSQL's spelling of a type.
566pub fn pg_type_name(ty: &SqlType) -> String {
567    match ty {
568        SqlType::SmallInt => "SMALLINT".into(),
569        SqlType::Integer => "INTEGER".into(),
570        SqlType::BigInt => "BIGINT".into(),
571        SqlType::Real => "REAL".into(),
572        SqlType::Double => "DOUBLE PRECISION".into(),
573        SqlType::Numeric {
574            precision: None, ..
575        } => "NUMERIC".into(),
576        SqlType::Numeric {
577            precision: Some(p),
578            scale: None,
579        } => format!("NUMERIC({p})"),
580        SqlType::Numeric {
581            precision: Some(p),
582            scale: Some(s),
583        } => format!("NUMERIC({p}, {s})"),
584        SqlType::Text => "TEXT".into(),
585        SqlType::Varchar(None) => "VARCHAR".into(),
586        SqlType::Varchar(Some(n)) => format!("VARCHAR({n})"),
587        SqlType::Boolean => "BOOLEAN".into(),
588        SqlType::Date => "DATE".into(),
589        SqlType::Timestamp { with_tz: false } => "TIMESTAMP".into(),
590        SqlType::Timestamp { with_tz: true } => "TIMESTAMPTZ".into(),
591        SqlType::Uuid => "UUID".into(),
592        SqlType::Bytes => "BYTEA".into(),
593        SqlType::Json => "JSON".into(),
594        SqlType::Jsonb => "JSONB".into(),
595    }
596}
597
598/// The argument at `i` when it is a non-negative integer literal.
599pub fn literal_count(f: &Function, i: usize) -> Option<u64> {
600    match f.args.get(i) {
601        Some(FunctionArg::Expr(Expr::Literal(Literal::Number(n)))) => n.parse().ok(),
602        _ => None,
603    }
604}
605
606/// The argument at `i` when it is a non-empty string literal.
607pub fn literal_nonempty_string(f: &Function, i: usize) -> bool {
608    matches!(
609        f.args.get(i),
610        Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) if !s.is_empty()
611    )
612}
613
614/// The fractional-second precision written in `UTC_TIMESTAMP(p)`: `Some(0)` when absent, `None`
615/// when it is not an integer literal.
616pub fn utc_timestamp_precision(f: &Function) -> Option<u32> {
617    match f.args.as_slice() {
618        [] => Some(0),
619        [FunctionArg::Expr(Expr::Literal(Literal::Number(n)))] => n.parse().ok(),
620        _ => None,
621    }
622}
623
624/// `date_trunc('<field>', x)` with a literal field: that field, lower-cased.
625pub fn date_trunc_field(f: &Function) -> Option<String> {
626    if f.name != "date_trunc" {
627        return None;
628    }
629    match f.args.first() {
630        Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) => Some(s.to_ascii_lowercase()),
631        _ => None,
632    }
633}
634
635/// The leaf of `EXTRACT(field FROM x)`: `extract.<field>`, and `extract.epoch.interval` when the operand
636/// is a difference of timestamps (an interval), which is not the epoch of a timestamp.
637pub fn extract_leaf(field: &str, interval: bool) -> String {
638    if interval && field == "epoch" {
639        "extract.epoch.interval".to_string()
640    } else {
641        format!("extract.{field}")
642    }
643}
644
645/// The base leaf of a locking clause: `row_lock` for FOR UPDATE, `row_lock.share` for FOR SHARE.
646pub fn row_lock_leaf(lock: &RowLockClause) -> &'static str {
647    match lock.strength {
648        RowLock::Update => "row_lock",
649        RowLock::Share => "row_lock.share",
650    }
651}
652
653/// Records every leaf a locking clause uses (the same set `needs::constructs` names), all Exact.
654pub fn note_row_lock_leaves(lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
655    ctx.note(row_lock_leaf(lock), Tier::Exact, "", None)?;
656    if lock.of.is_some() {
657        ctx.note("row_lock.of", Tier::Exact, "", None)?;
658    }
659    match lock.wait {
660        LockWait::Block => {}
661        LockWait::NoWait => ctx.note("row_lock.nowait", Tier::Exact, "", None)?,
662        LockWait::SkipLocked => ctx.note("row_lock.skip_locked", Tier::Exact, "", None)?,
663    }
664    Ok(())
665}
666
667/// The leaf of `WITH .. <statement>`.
668pub fn with_leaf(kind: StmtKind) -> &'static str {
669    match kind {
670        StmtKind::Insert => "with.insert",
671        StmtKind::Update => "with.update",
672        StmtKind::Delete => "with.delete",
673    }
674}