Skip to main content

Module sql_macro

Module sql_macro 

Source
Expand description

SQL macro registration for DuckDB extensions.

SQL macros let you package reusable SQL expressions and queries as named DuckDB functions — no FFI callbacks required. This module provides a safe Rust builder for creating both scalar and table macros via CREATE OR REPLACE MACRO statements executed during extension initialization.

§Macro types

TypeSQLReturns
ScalarAS (expression)one value per row
TableAS TABLE querya table

§Example

use quack_rs::sql_macro::SqlMacro;
use quack_rs::error::ExtensionError;

fn register(con: libduckdb_sys::duckdb_connection) -> Result<(), ExtensionError> {
    unsafe {
        // Scalar macro: clamp(x, lo, hi) — no C++ needed!
        SqlMacro::scalar("clamp", &["x", "lo", "hi"], "greatest(lo, least(hi, x))")?
            .register(con)?;

        // Table macro: active_rows(tbl) — returns filtered rows
        SqlMacro::table("active_rows", &["tbl"], "SELECT * FROM tbl WHERE active = true")?
            .register(con)?;
    }
    Ok(())
}

§SQL injection safety

Macro names and parameter names are validated against validate_function_name: only [a-z][a-z0-9_]* identifiers are accepted. These names are interpolated literally into the generated SQL (no quoting required because they are already restricted to safe characters).

The SQL body (expression / query) is your own extension code, not user-supplied input. Never build macro bodies from untrusted runtime data. There is no escaping applied to the body.

Structs§

SqlMacro
A SQL macro definition ready to be registered with DuckDB.

Enums§

MacroBody
The body of a SQL macro: a scalar expression or a table query.