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