razeri-plugin-contract 0.14.0

The dialect contract Razeri plugins are written against — rendering traits, data types, platform identity
Documentation
// Copyright (C) 2026 Gabriel Shea
// Licensed under either of the Apache License, Version 2.0 or the MIT
// license, at your option.

//! **Which routine grammar this engine speaks** — the dialect's answer, not a
//! core crate's guess about its name.
//!
//! A stored procedure, a scalar function and a table function are the three
//! places where an engine's SQL stops resembling every other engine's. Razeri
//! composes the routine's *content* — its parameters, its body, its comment —
//! and asks the dialect which grammar to spell it in.
//!
//! All three enums are `#[non_exhaustive]`: Razeri adds a form when it has
//! measured one, and a dialect must state a fallback rather than assume the
//! list it compiled against is the list that ships.
//!
//! # If none of these is your engine
//!
//! There are three honest answers, and they say three different things.
//!
//! - **A near neighbour.** Pick the closest measured form and *run the result*
//!   — the near-neighbour trap is real, and a form that almost fits fails at
//!   `CREATE`, not at review;
//! - **`Custom`, on any of the three.** Your engine has this routine kind and
//!   spells it in a grammar Razeri does not carry — Oracle's PL/SQL is the
//!   worked case. `Custom` names your grammar and hands the rendering to your
//!   dialect: Razeri substitutes nothing and refuses nothing, and your
//!   dialect's own render method spells the whole `CREATE`. See
//!   [`RoutineSpec`](crate::routine_spec::RoutineSpec) for what Razeri hands
//!   you and [`SqlRenderer::render_procedure`](crate::SqlRenderer::render_procedure)
//!   for the method you owe;
//! - **`Unsupported`, on any of the three.** Your engine has no routine of this
//!   kind at any spelling. It carries your own words, and those words are what
//!   the author reads instead of another engine's.
//!
//! `Custom` and `Unsupported` are opposite claims and the difference matters to
//! a reader: one says *this engine has it and Razeri cannot spell it*, the
//! other says *this engine does not have it*. Answering `Unsupported` for a
//! grammar Razeri merely lacks tells every reader something false about the
//! engine.

/// Which stored-procedure grammar this engine speaks.
///
/// The default is [`ProcedureForm::Agnostic`], Razeri's own annotated form. It
/// parses nowhere: it is the honest answer for a dialect that has not said, and
/// the conformance kit reports it as an unanswered obligation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum ProcedureForm {
    /// PL/pgSQL — a dollar-quoted body with `DECLARE`, `SELECT … INTO`,
    /// `RAISE`, `IF` and an `EXCEPTION` block. `PostgreSQL`, Citus and
    /// `Redshift`, all three measured deploying and running.
    PlPgSql,
    /// `MySQL`/`MariaDB`'s compound statement — the same block structure with
    /// `DELIMITER`-free `BEGIN … END` and no dollar quoting.
    MySql,
    /// T-SQL — `CREATE PROCEDURE … AS BEGIN … END`, `@`-prefixed parameters.
    TSql,
    /// Snowflake Scripting.
    SnowflakeScripting,
    /// Databricks SQL scripting.
    Databricks,
    /// `ClickHouse`.
    ClickHouse,
    /// `GoogleSQL` scripting — `BigQuery`'s, whose body is not quoted at all.
    GoogleSql,
    /// Razeri's agnostic annotated form: ANSI SQL carrying `@razeri:` headers.
    /// It is a design artifact, not something an engine parses.
    #[default]
    Agnostic,
    /// **This engine has stored procedures and spells them in a grammar Razeri
    /// does not carry.** The string is the grammar's own name — `"PL/SQL"`,
    /// `"Teradata SPL"` — and it is what a reader of a report or a rendered
    /// comment sees.
    ///
    /// Answering this moves the rendering to your dialect and moves nothing
    /// else: Razeri neither substitutes a near neighbour nor refuses, and every
    /// question it would have answered from a named grammar it asks your
    /// dialect instead. The method it asks is
    /// [`SqlRenderer::render_procedure`](crate::SqlRenderer::render_procedure),
    /// and **a dialect that answers `Custom` without overriding it has
    /// promised a rendering it does not provide** — the conformance kit
    /// reports that as blocking, and the rendered SQL says the same thing in a
    /// comment where the procedure would have been.
    Custom(&'static str),
    /// **This engine has no stored procedures.** The string is the orientation
    /// an author reads instead of a syntax error — say what this engine offers
    /// in their place (`DuckDB`'s macros, `SQLite`'s application-level logic),
    /// because the sentence that helps is the one about *this* engine.
    ///
    /// Not the answer for a grammar Razeri cannot spell — that is
    /// [`Custom`](Self::Custom), and the difference is the difference between a
    /// fact about the engine and a fact about Razeri.
    Unsupported(&'static str),
}

impl ProcedureForm {
    /// The dialect's own refusal wording, or `None` where this engine has
    /// stored procedures.
    #[must_use]
    pub const fn refusal(self) -> Option<&'static str> {
        match self {
            ProcedureForm::Unsupported(orientation) => Some(orientation),
            _ => None,
        }
    }

    /// The name of the grammar this dialect renders itself, or `None` where
    /// Razeri renders the procedure.
    ///
    /// The one accessor every surface reads — the renderer that delegates, the
    /// conformance kit that checks the dialect kept its promise, and any report
    /// that names the grammar — so none of them carries a second reading of the
    /// variant.
    #[must_use]
    pub const fn custom_grammar(self) -> Option<&'static str> {
        match self {
            ProcedureForm::Custom(grammar) => Some(grammar),
            _ => None,
        }
    }
}

/// Which scalar-function grammar this engine speaks.
///
/// The default is [`ScalarFunctionForm::PostgreSql`], which is what an
/// unlisted dialect has always been handed. It is a guess and a dangerous one
/// on a near neighbour: `LANGUAGE SQL IMMUTABLE PARALLEL SAFE` is a *"syntax
/// error at or near `PARALLEL`"* on `Redshift`, an engine that descends from
/// `PostgreSQL` and reports itself as one. State your form.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum ScalarFunctionForm {
    /// `CREATE FUNCTION … RETURNS … LANGUAGE SQL IMMUTABLE PARALLEL SAFE AS
    /// $$…$$` — `PostgreSQL`, Citus and Razeri's agnostic renderer.
    #[default]
    PostgreSql,
    /// `DuckDB`'s `CREATE MACRO`.
    DuckDb,
    /// T-SQL's scalar UDF.
    TSql,
    /// `ClickHouse`'s lambda `CREATE FUNCTION … AS (x) -> …`.
    ClickHouse,
    /// Snowflake's UDF.
    Snowflake,
    /// `MySQL`/`MariaDB`'s `CREATE FUNCTION … DETERMINISTIC`.
    MySql,
    /// Databricks SQL's UDF.
    Databricks,
    /// `GoogleSQL`'s `CREATE FUNCTION` — `BigQuery`'s.
    GoogleSql,
    /// `Redshift`'s: the volatility is mandatory rather than optional, there is
    /// no `PARALLEL SAFE`, `LANGUAGE` follows the body rather than preceding
    /// it, and the body addresses its parameters as `$1` and never by name.
    Redshift,
    /// **This engine has scalar functions and spells them in a grammar Razeri
    /// does not carry.** The string is the grammar's own name.
    ///
    /// Your dialect renders the whole `CREATE`, through
    /// [`SqlRenderer::render_scalar_function`](crate::SqlRenderer::render_scalar_function).
    /// Razeri substitutes no near neighbour and refuses nothing; a dialect that
    /// answers `Custom` without overriding that method has promised a rendering
    /// it does not provide, and the conformance kit reports it.
    Custom(&'static str),
    /// **This engine has no scalar function.**
    ///
    /// Rare — rare enough that no engine Razeri has measured is one — and the
    /// default was a silent `PostgreSql` for want of anywhere to say it. The
    /// string is the orientation an author reads: say what this engine offers
    /// instead before saying what it lacks, and name the near form if there is
    /// one.
    ///
    /// It is prose that lands inside a SQL comment, so it must never spell a
    /// complete statement.
    Unsupported(&'static str),
}

impl ScalarFunctionForm {
    /// The dialect's own refusal wording, or `None` where this engine has a
    /// scalar function.
    #[must_use]
    pub const fn refusal(self) -> Option<&'static str> {
        match self {
            ScalarFunctionForm::Unsupported(orientation) => Some(orientation),
            _ => None,
        }
    }

    /// The name of the grammar this dialect renders itself, or `None` where
    /// Razeri renders the function.
    #[must_use]
    pub const fn custom_grammar(self) -> Option<&'static str> {
        match self {
            ScalarFunctionForm::Custom(grammar) => Some(grammar),
            _ => None,
        }
    }
}

/// Which **table-valued function** grammar this engine speaks — the routine a
/// query selects `FROM`, returning columns rather than one value.
///
/// The default is [`TableFunctionForm::PostgreSql`], which is what an unlisted
/// dialect has always been handed. Four engines in Razeri's own set have no
/// table-valued function they can render, and each says so in **its own words**
/// through [`TableFunctionForm::Unsupported`] — because a refusal written once
/// per *kind* tells a `Redshift` author about `MySQL`, and the sentence that
/// helps is the one about their engine.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum TableFunctionForm {
    /// `CREATE FUNCTION … RETURNS TABLE(…)` / `RETURNS SETOF …` over a
    /// dollar-quoted body — `PostgreSQL`, Citus, and Razeri's agnostic
    /// renderer.
    #[default]
    PostgreSql,
    /// `DuckDB`'s table `MACRO`: `CREATE MACRO f(x) AS TABLE SELECT …`. There
    /// is no `RETURNS` clause at all, which is why riding the `PostgreSQL` arm
    /// was `Parser Error: syntax error at or near "RETURNS"`.
    DuckDb,
    /// `GoogleSQL`'s `CREATE TABLE FUNCTION` — `BigQuery`'s.
    GoogleSql,
    /// T-SQL's two shapes: the inline TVF (`RETURNS TABLE AS RETURN (…)`) and
    /// the multi-statement one (`RETURNS @t TABLE(…) BEGIN … RETURN END`).
    TSql,
    /// `ClickHouse`'s parameterized view, addressed with `{param:Type}`.
    ClickHouse,
    /// Snowflake's UDTF, including the staged-handler registration.
    Snowflake,
    /// Databricks SQL's `CREATE FUNCTION … RETURNS TABLE … RETURN <query>`.
    Databricks,
    /// **This engine has no table-valued function.**
    ///
    /// The string is the orientation an author reads — at build time, when
    /// Razeri refuses to write the routine, and again in the rendered refusal
    /// if anything asks the renderer directly. Write it fix-first: say what
    /// this engine offers *instead* before saying what it lacks, name the
    /// `artifact:` values a designer would reach for, and name the near form if
    /// there is one, because a near form the author will find on their own is
    /// the thing that costs them a day.
    ///
    /// It is prose that lands inside a SQL comment, so it must never spell a
    /// complete statement.
    Unsupported(&'static str),
    /// **This engine has a table-valued function and spells it in a grammar
    /// Razeri does not carry.** The string is the grammar's own name.
    ///
    /// Your dialect renders the whole `CREATE`, through
    /// [`SqlRenderer::render_table_function`](crate::SqlRenderer::render_table_function).
    /// It is the opposite claim to [`Unsupported`](Self::Unsupported): the
    /// build door writes the routine rather than declining it, because this
    /// engine has one.
    Custom(&'static str),
}

impl TableFunctionForm {
    /// The dialect's own refusal wording, or `None` where this engine has the
    /// form.
    ///
    /// The one accessor both surfaces read — the build door that declines to
    /// write the routine, and the renderer that would otherwise emit DDL — so
    /// neither one carries a second copy of the words.
    ///
    /// [`Custom`](Self::Custom) answers `None` here, and that is the whole
    /// point of it: an engine whose grammar Razeri cannot spell still **has** a
    /// table-valued function, so the door that asks *may I write this at all*
    /// gets a yes.
    #[must_use]
    pub const fn refusal(self) -> Option<&'static str> {
        match self {
            TableFunctionForm::Unsupported(orientation) => Some(orientation),
            _ => None,
        }
    }

    /// The name of the grammar this dialect renders itself, or `None` where
    /// Razeri renders the function.
    #[must_use]
    pub const fn custom_grammar(self) -> Option<&'static str> {
        match self {
            TableFunctionForm::Custom(grammar) => Some(grammar),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The defaults are what an undecided dialect gets, and they are the
    /// behaviour Razeri has always had for an unlisted platform.
    #[test]
    fn the_defaults_are_the_agnostic_procedure_and_the_postgres_functions() {
        assert_eq!(ProcedureForm::default(), ProcedureForm::Agnostic);
        assert_eq!(ScalarFunctionForm::default(), ScalarFunctionForm::PostgreSql);
        assert_eq!(TableFunctionForm::default(), TableFunctionForm::PostgreSql);
    }

    /// A form that renders carries no refusal; an `Unsupported` one carries the
    /// dialect's own sentence and nothing else does.
    #[test]
    fn only_the_unsupported_form_carries_refusal_wording() {
        assert_eq!(TableFunctionForm::PostgreSql.refusal(), None);
        assert_eq!(TableFunctionForm::GoogleSql.refusal(), None);
        assert_eq!(
            TableFunctionForm::Unsupported("my engine has none").refusal(),
            Some("my engine has none")
        );
    }

    /// **`Custom` is a claim that the engine HAS the routine kind**, so it
    /// carries no refusal on any of the three enums. Every door that asks
    /// *"may I write this at all"* reads `refusal()`, and a `Custom` that
    /// answered a sentence there would have Razeri decline to write a routine
    /// the engine is perfectly able to run.
    #[test]
    fn a_custom_grammar_is_not_a_refusal_on_any_of_the_three() {
        assert_eq!(ProcedureForm::Custom("PL/SQL").refusal(), None);
        assert_eq!(ScalarFunctionForm::Custom("PL/SQL").refusal(), None);
        assert_eq!(TableFunctionForm::Custom("PL/SQL").refusal(), None);
    }

    /// The grammar's name reaches every reader from one accessor, and only
    /// `Custom` has one to give.
    #[test]
    fn only_the_custom_form_names_a_grammar() {
        assert_eq!(ProcedureForm::Custom("PL/SQL").custom_grammar(), Some("PL/SQL"));
        assert_eq!(ScalarFunctionForm::Custom("PL/SQL").custom_grammar(), Some("PL/SQL"));
        assert_eq!(TableFunctionForm::Custom("PL/SQL").custom_grammar(), Some("PL/SQL"));
        assert_eq!(ProcedureForm::TSql.custom_grammar(), None);
        assert_eq!(ScalarFunctionForm::Redshift.custom_grammar(), None);
        assert_eq!(TableFunctionForm::DuckDb.custom_grammar(), None);
        assert_eq!(ProcedureForm::Unsupported("none here").custom_grammar(), None);
    }

    /// **The scalar-function enum can now say what the other two always
    /// could.** An engine with no scalar function had one reachable answer, and
    /// it was `PostgreSql` — a grammar, silently, for an engine that has none.
    #[test]
    fn the_scalar_function_form_can_refuse_in_its_own_words() {
        assert_eq!(
            ScalarFunctionForm::Unsupported("no scalar function here").refusal(),
            Some("no scalar function here")
        );
        assert_eq!(ScalarFunctionForm::PostgreSql.refusal(), None);
    }
}