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