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    /// `expr AT TIME ZONE zone`. Default (PostgreSQL): exact. A target without it refuses the leaf
249    /// `at_time_zone`.
250    fn at_time_zone(&self, ctx: &mut Ctx) -> R<()> {
251        ctx.note("at_time_zone", Tier::Exact, "", None)
252    }
253
254    /// `ARRAY(SELECT ..)`. Default (PostgreSQL): exact. A target without an array type refuses the
255    /// leaf `array_subquery`.
256    fn array_subquery(&self, ctx: &mut Ctx) -> R<()> {
257        ctx.note("array_subquery", Tier::Exact, "", None)
258    }
259
260    /// `WITH .. INSERT | UPDATE | DELETE ..` (the common table expressions precede the modifying
261    /// statement). The default (PostgreSQL) has all three; each is its own leaf: `with.insert`,
262    /// `with.update`, `with.delete`.
263    fn with_statement(&self, kind: StmtKind, ctx: &mut Ctx) -> R<()> {
264        ctx.note(with_leaf(kind), Tier::Exact, "", None)
265    }
266
267    /// `WITH x AS (INSERT/UPDATE/DELETE .. RETURNING ..) ..`. The default (PostgreSQL) has it; a
268    /// target without it refuses the leaf `cte.data_modifying`.
269    fn data_modifying_cte(&self, ctx: &mut Ctx) -> R<()> {
270        ctx.note("cte.data_modifying", Tier::Exact, "", None)
271    }
272
273    /// A row-locking clause. The default (PostgreSQL) gives every form; each form is its own leaf:
274    /// `row_lock` (FOR UPDATE), `row_lock.share`, `row_lock.of`, `row_lock.nowait`,
275    /// `row_lock.skip_locked`.
276    fn row_lock(&self, lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
277        note_row_lock_leaves(lock, ctx)
278    }
279
280    fn returning(&self, _kind: StmtKind, ctx: &mut Ctx) -> R<()> {
281        ctx.note("returning", Tier::Exact, "", None)
282    }
283
284    /// `LIMIT`/`OFFSET` tail; operands already printed. Returns `""` when neither is present.
285    fn limit_offset(&self, limit: Option<&str>, offset: Option<&str>, ctx: &mut Ctx) -> R<String> {
286        let mut s = String::new();
287        if let Some(l) = limit {
288            s.push_str(&format!(" LIMIT {l}"));
289            ctx.note("limit", Tier::Exact, "", None)?;
290        }
291        if let Some(o) = offset {
292            s.push_str(&format!(" OFFSET {o}"));
293            ctx.note("offset", Tier::Exact, "", None)?;
294        }
295        Ok(s)
296    }
297
298    /// Tier of a join kind on this target (SQLite lacks RIGHT/FULL before 3.39).
299    fn join_tier(&self, _kind: JoinKind) -> Tier {
300        Tier::Exact
301    }
302
303    /// Tier of `UPDATE .. FROM`.
304    fn update_from_tier(&self) -> Tier {
305        Tier::Exact
306    }
307
308    /// Whole-query rewrite before printing (for example `DISTINCT ON` via a window function).
309    /// Return `Some(q2)` to print `q2` instead; `q2` must not trigger the same rewrite again.
310    fn rewrite_query(&self, _q: &Query, _ctx: &mut Ctx) -> R<Option<Query>> {
311        Ok(None)
312    }
313
314    /// A feature the printer is about to emit: `window_function`, `filter_clause`,
315    /// `recursive_cte`, `named_arg`. Default: exact (PostgreSQL).
316    fn feature(&self, name: &'static str, ctx: &mut Ctx) -> R<()> {
317        ctx.note(name, Tier::Exact, "", None)
318    }
319
320    /// `TRIM(..)` with operands already printed.
321    fn trim(&self, side: TrimSide, expr: &str, chars: Option<&str>, ctx: &mut Ctx) -> R<String> {
322        ctx.note("trim", Tier::Exact, "", None)?;
323        Ok(match (side, chars) {
324            (TrimSide::Both, None) => format!("TRIM({expr})"),
325            (s, c) => {
326                let kw = match s {
327                    TrimSide::Both => "BOTH",
328                    TrimSide::Leading => "LEADING",
329                    TrimSide::Trailing => "TRAILING",
330                };
331                match c {
332                    Some(c) => format!("TRIM({kw} {c} FROM {expr})"),
333                    None => format!("TRIM({kw} FROM {expr})"),
334                }
335            }
336        })
337    }
338
339    /// `left (+|-) make_interval(parts..)`; `parts` are (unit, printed value). Return `Some(text)`
340    /// to replace the whole expression, `None` to print it the generic way.
341    fn interval_arith(
342        &self,
343        _minus: bool,
344        _left: &str,
345        _parts: &[(String, String)],
346        _ctx: &mut Ctx,
347    ) -> R<Option<String>> {
348        Ok(None)
349    }
350
351    /// JSON `->` / `->>` with operands printed. Default: PostgreSQL.
352    fn json_access(&self, text: bool, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
353        ctx.note(
354            if text { "json_get_text" } else { "json_get" },
355            Tier::Exact,
356            "",
357            None,
358        )?;
359        Ok(format!("{lhs} {} {rhs}", if text { "->>" } else { "->" }))
360    }
361
362    /// Replace the default `l OP r` text for a binary operator (for example `||` -> `CONCAT`,
363    /// `/` -> `DIV`). Operands are already printed. Return `None` for the default.
364    fn binary_override(
365        &self,
366        _op: BinaryOp,
367        _l: &str,
368        _r: &str,
369        _numeric: bool,
370        _ctx: &mut Ctx,
371    ) -> R<Option<String>> {
372        Ok(None)
373    }
374
375    /// One ORDER BY item with its direction and NULL placement. `nulls_first` is explicit.
376    fn order_item(&self, expr: &str, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
377        let mut s = expr.to_string();
378        if desc {
379            s.push_str(" DESC");
380        }
381        s.push_str(&self.nulls_order(desc, nulls_first, ctx)?);
382        Ok(s)
383    }
384
385    /// How the SET list of an upsert refers to the value that was proposed for insertion.
386    fn excluded_ref(&self, column_quoted: &str) -> String {
387        format!("EXCLUDED.{column_quoted}")
388    }
389
390    /// The whole `ON CONFLICT ..` clause. `set` and `where_` are printed; `columns` are quoted.
391    #[allow(clippy::too_many_arguments)]
392    fn upsert_clause(
393        &self,
394        conflict_cols: &[String],
395        do_nothing: bool,
396        set: &str,
397        where_: Option<&str>,
398        _first_insert_col: &str,
399        ctx: &mut Ctx,
400    ) -> R<String> {
401        if !do_nothing && conflict_cols.is_empty() {
402            return Err(ctx.refuse(
403                "upsert.no_conflict_key",
404                "the source upsert names no conflict key (MySQL ON DUPLICATE KEY UPDATE fires on any unique key); this target needs the key columns",
405                &["state the conflict key columns in the statement"],
406            ));
407        }
408        ctx.note(
409            if where_.is_some() {
410                "upsert_where"
411            } else {
412                "upsert"
413            },
414            Tier::Exact,
415            "",
416            None,
417        )?;
418        let mut s = String::from(" ON CONFLICT");
419        if !conflict_cols.is_empty() {
420            s.push_str(&format!(" ({})", conflict_cols.join(", ")));
421        }
422        if do_nothing {
423            s.push_str(" DO NOTHING");
424        } else {
425            s.push_str(&format!(" DO UPDATE SET {set}"));
426            if let Some(w) = where_ {
427                s.push_str(&format!(" WHERE {w}"));
428            }
429        }
430        Ok(s)
431    }
432
433    /// Membership in an array parameter: `lhs = ANY(ph)` (or `<> ALL` when `negated`). The target
434    /// must record how the caller binds parameter `n` via [`Ctx::bind_array_param`]. **The default
435    /// refuses**: a target with no array codec has no honest translation.
436    fn array_membership(
437        &self,
438        _lhs: &str,
439        _ph: &str,
440        _negated: bool,
441        n: u32,
442        ctx: &mut Ctx,
443    ) -> R<String> {
444        Err(ctx.refuse(
445            "array_param",
446            &format!(
447                "target `{}` has no codec for an array parameter (${n})",
448                ctx.target
449            ),
450            &["expand the array into an IN (..) list in the application"],
451        ))
452    }
453
454    /// Hook for `[NOT] BETWEEN`. `numeric` is true when an operand is syntactically numeric (so no
455    /// text collation is involved). Default: exact.
456    fn between(&self, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
457        Ok(())
458    }
459
460    /// Hook for operators whose meaning differs. `numeric` is true when an operand is syntactically
461    /// numeric (a number literal, arithmetic, or a numeric aggregate). Default: exact.
462    fn binary_op(&self, _op: BinaryOp, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
463        Ok(())
464    }
465
466    /// Text for one ORDER BY item's null-ordering suffix, `""` for none. `nulls_first` is always
467    /// explicit after reading (the reader fills in the source dialect's default).
468    fn nulls_order(&self, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
469        // PostgreSQL default: NULLs are the largest value (last ascending, first descending).
470        let default_first = desc;
471        ctx.note("null_ordering", Tier::Exact, "", None)?;
472        if nulls_first == default_first {
473            Ok(String::new())
474        } else {
475            Ok(if nulls_first {
476                " NULLS FIRST"
477            } else {
478                " NULLS LAST"
479            }
480            .to_string())
481        }
482    }
483}
484
485/// Functions with the same name and meaning on every dialect UniSQL targets so far.
486pub const PORTABLE_FUNCTIONS: &[&str] = &[
487    "count",
488    "sum",
489    "min",
490    "max",
491    "avg",
492    "coalesce",
493    "nullif",
494    "abs",
495    "lower",
496    "upper",
497    "length",
498    "replace",
499    "substr",
500    "row_number",
501    "rank",
502    "dense_rank",
503    "percent_rank",
504    "cume_dist",
505    "ntile",
506    "lag",
507    "lead",
508    "first_value",
509    "last_value",
510    "nth_value",
511];
512
513pub fn generic_call(name: &str, args: &[String], distinct: bool, star: bool) -> String {
514    generic_call_ordered(name, args, distinct, star, None)
515}
516
517/// `NAME([DISTINCT] args [ORDER BY ..])`.
518pub fn generic_call_ordered(
519    name: &str,
520    args: &[String],
521    distinct: bool,
522    star: bool,
523    order: Option<&str>,
524) -> String {
525    let ord = order.map(|o| format!(" ORDER BY {o}")).unwrap_or_default();
526    if star {
527        return format!("{}(*)", name.to_uppercase());
528    }
529    format!(
530        "{}({}{}{})",
531        name.to_uppercase(),
532        if distinct { "DISTINCT " } else { "" },
533        args.join(", "),
534        ord
535    )
536}
537
538/// PostgreSQL's spelling of a type.
539pub fn pg_type_name(ty: &SqlType) -> String {
540    match ty {
541        SqlType::SmallInt => "SMALLINT".into(),
542        SqlType::Integer => "INTEGER".into(),
543        SqlType::BigInt => "BIGINT".into(),
544        SqlType::Real => "REAL".into(),
545        SqlType::Double => "DOUBLE PRECISION".into(),
546        SqlType::Numeric {
547            precision: None, ..
548        } => "NUMERIC".into(),
549        SqlType::Numeric {
550            precision: Some(p),
551            scale: None,
552        } => format!("NUMERIC({p})"),
553        SqlType::Numeric {
554            precision: Some(p),
555            scale: Some(s),
556        } => format!("NUMERIC({p}, {s})"),
557        SqlType::Text => "TEXT".into(),
558        SqlType::Varchar(None) => "VARCHAR".into(),
559        SqlType::Varchar(Some(n)) => format!("VARCHAR({n})"),
560        SqlType::Boolean => "BOOLEAN".into(),
561        SqlType::Date => "DATE".into(),
562        SqlType::Timestamp { with_tz: false } => "TIMESTAMP".into(),
563        SqlType::Timestamp { with_tz: true } => "TIMESTAMPTZ".into(),
564        SqlType::Uuid => "UUID".into(),
565        SqlType::Bytes => "BYTEA".into(),
566        SqlType::Json => "JSON".into(),
567        SqlType::Jsonb => "JSONB".into(),
568    }
569}
570
571/// `date_trunc('<field>', x)` with a literal field: that field, lower-cased.
572pub fn date_trunc_field(f: &Function) -> Option<String> {
573    if f.name != "date_trunc" {
574        return None;
575    }
576    match f.args.first() {
577        Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) => Some(s.to_ascii_lowercase()),
578        _ => None,
579    }
580}
581
582/// The leaf of `EXTRACT(field FROM x)`: `extract.<field>`, and `extract.epoch.interval` when the operand
583/// is a difference of timestamps (an interval), which is not the epoch of a timestamp.
584pub fn extract_leaf(field: &str, interval: bool) -> String {
585    if interval && field == "epoch" {
586        "extract.epoch.interval".to_string()
587    } else {
588        format!("extract.{field}")
589    }
590}
591
592/// The base leaf of a locking clause: `row_lock` for FOR UPDATE, `row_lock.share` for FOR SHARE.
593pub fn row_lock_leaf(lock: &RowLockClause) -> &'static str {
594    match lock.strength {
595        RowLock::Update => "row_lock",
596        RowLock::Share => "row_lock.share",
597    }
598}
599
600/// Records every leaf a locking clause uses (the same set `needs::constructs` names), all Exact.
601pub fn note_row_lock_leaves(lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
602    ctx.note(row_lock_leaf(lock), Tier::Exact, "", None)?;
603    if lock.of.is_some() {
604        ctx.note("row_lock.of", Tier::Exact, "", None)?;
605    }
606    match lock.wait {
607        LockWait::Block => {}
608        LockWait::NoWait => ctx.note("row_lock.nowait", Tier::Exact, "", None)?,
609        LockWait::SkipLocked => ctx.note("row_lock.skip_locked", Tier::Exact, "", None)?,
610    }
611    Ok(())
612}
613
614/// The leaf of `WITH .. <statement>`.
615pub fn with_leaf(kind: StmtKind) -> &'static str {
616    match kind {
617        StmtKind::Insert => "with.insert",
618        StmtKind::Update => "with.update",
619        StmtKind::Delete => "with.delete",
620    }
621}