Skip to main content

quack_rs/
sql_macro.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2026 Tom F. <https://github.com/tomtom215/>
3// My way of giving something small back to the open source community
4// and encouraging more Rust development!
5
6//! SQL macro registration for `DuckDB` extensions.
7//!
8//! SQL macros let you package reusable SQL expressions and queries as
9//! named `DuckDB` functions — no FFI callbacks required. This module
10//! provides a safe Rust builder for creating both scalar and table macros
11//! via `CREATE OR REPLACE MACRO` statements executed during extension
12//! initialization.
13//!
14//! # Macro types
15//!
16//! | Type | SQL | Returns |
17//! |------|-----|---------|
18//! | **Scalar** | `AS (expression)` | one value per row |
19//! | **Table** | `AS TABLE query`  | a table |
20//!
21//! # Example
22//!
23//! ```rust,no_run
24//! use quack_rs::sql_macro::SqlMacro;
25//! use quack_rs::error::ExtensionError;
26//!
27//! fn register(con: libduckdb_sys::duckdb_connection) -> Result<(), ExtensionError> {
28//!     unsafe {
29//!         // Scalar macro: clamp(x, lo, hi) — no C++ needed!
30//!         SqlMacro::scalar("clamp", &["x", "lo", "hi"], "greatest(lo, least(hi, x))")?
31//!             .register(con)?;
32//!
33//!         // Table macro: active_rows(tbl) — returns filtered rows. A table
34//!         // parameter is read through `query_table`: a bare `FROM tbl` makes
35//!         // DuckDB look for a table named `tbl` at registration, and fail.
36//!         SqlMacro::table("active_rows", &["tbl"], "SELECT * FROM query_table(tbl) WHERE active = true")?
37//!             .register(con)?;
38//!     }
39//!     Ok(())
40//! }
41//! ```
42//!
43//! # SQL injection safety
44//!
45//! Macro names are validated against [`validate_function_name`], and
46//! parameter names against [`validate_parameter_name`]: an ASCII letter or
47//! underscore followed by ASCII letters, digits or underscores
48//! (`[A-Za-z_][A-Za-z0-9_]*`, at most 256 characters), and not a `DuckDB`
49//! keyword that cannot be used in that position unquoted — measured, not
50//! guessed: `coalesce` or `values` cannot be called as a macro, and a
51//! parameter called `order` or `left` could only be referred to in the body
52//! as `"order"` / `"left"`, so each is refused rather than left to fail at
53//! registration or inside the body. Mixed case is accepted.
54//!
55//! The generated SQL always emits the names as **double-quoted identifiers**
56//! (`"name"`). The validated character set cannot contain `"`, so quoting
57//! needs no escaping. Quoting does not make the name case-sensitive: `DuckDB`
58//! resolves identifiers case-insensitively whether or not they were quoted, so
59//! a macro registered as `MyMacro` is callable as `mymacro(...)` or
60//! `MYMACRO(...)`.
61//!
62//! The SQL body (`expression` / `query`) is your own extension code, not
63//! user-supplied input. **Never build macro bodies from untrusted runtime
64//! data.** There is no escaping applied to the body. [`SqlMacro::register`]
65//! does refuse a body that turns the statement into several (`1); DROP TABLE
66//! t; SELECT (1`), using `DuckDB`'s own parser to count them, and a statement
67//! that does not parse at all, but a body can still change the meaning of the one
68//! statement it is part of. Nothing is executed in either refusal.
69//!
70//! # Where a macro lives, and what that means
71//!
72//! A macro is not a function registration: [`SqlMacro::register`] runs
73//! `CREATE OR REPLACE MACRO` on the connection, so the macro is an ordinary
74//! catalog object in the connection's **default database and schema** — the
75//! user's database. That has consequences a registered function does not:
76//!
77//! - **It persists.** In a database file the macro is written to disk and is
78//!   still there in the next session, even if the extension is never loaded
79//!   again. Loading the extension again is fine: `CREATE OR REPLACE` simply
80//!   replaces it.
81//! - **It needs a writable database.** On a database opened read-only the
82//!   `CREATE` fails, so an entry point that propagates the error with `?`
83//!   makes `LOAD` fail. Decide whether a macro is essential or can be skipped
84//!   there.
85//! - **It replaces a user's macro of the same name**, silently — that is what
86//!   `OR REPLACE` means. Prefix macro names with the extension's name.
87//! - **It can shadow a built-in function.** A macro named `abs` in the
88//!   default schema is found before the built-in `abs` in the system catalog,
89//!   so `abs(-1)` calls the macro.
90
91use std::ffi::{CStr, CString};
92
93use libduckdb_sys::{
94    duckdb_connection, duckdb_destroy_result, duckdb_query, duckdb_result, duckdb_result_error,
95    DuckDBSuccess,
96};
97
98use crate::error::ExtensionError;
99use crate::validate::{validate_function_name, validate_parameter_name};
100
101/// The body of a SQL macro: a scalar expression or a table query.
102///
103/// Constructed implicitly by [`SqlMacro::scalar`] and [`SqlMacro::table`].
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub enum MacroBody {
106    /// A SQL expression — generates `AS (expression)`.
107    ///
108    /// Example: `"greatest(lo, least(hi, x))"`
109    Scalar(String),
110
111    /// A SQL query — generates `AS TABLE query`.
112    ///
113    /// Example: `"SELECT * FROM query_table(tbl) WHERE active = true"`
114    Table(String),
115}
116
117/// A SQL macro definition ready to be registered with `DuckDB`.
118///
119/// Use [`SqlMacro::scalar`] or [`SqlMacro::table`] to construct, then call
120/// [`SqlMacro::register`] to install. Use [`SqlMacro::to_sql`] to inspect
121/// the generated `CREATE MACRO` statement without a live connection.
122///
123/// # Example
124///
125/// ```rust
126/// use quack_rs::sql_macro::SqlMacro;
127///
128/// let m = SqlMacro::scalar("add", &["a", "b"], "a + b").unwrap();
129/// assert_eq!(m.to_sql(), r#"CREATE OR REPLACE MACRO "add"("a", "b") AS (a + b)"#);
130/// ```
131#[derive(Debug, Clone)]
132pub struct SqlMacro {
133    name: String,
134    params: Vec<String>,
135    body: MacroBody,
136}
137
138impl SqlMacro {
139    /// Creates a scalar SQL macro definition.
140    ///
141    /// Registers as:
142    /// ```sql
143    /// CREATE OR REPLACE MACRO name(params) AS (expression)
144    /// ```
145    ///
146    /// # Errors
147    ///
148    /// Returns [`ExtensionError`] if `name` or any parameter name is invalid.
149    /// See [`validate_function_name`]
150    /// for naming rules.
151    ///
152    /// # Example
153    ///
154    /// ```rust
155    /// use quack_rs::sql_macro::SqlMacro;
156    ///
157    /// let m = SqlMacro::scalar("clamp", &["x", "lo", "hi"], "greatest(lo, least(hi, x))")?;
158    /// # Ok::<_, quack_rs::error::ExtensionError>(())
159    /// ```
160    pub fn scalar(
161        name: &str,
162        params: &[&str],
163        expression: impl Into<String>,
164    ) -> Result<Self, ExtensionError> {
165        let (name, params) = validate_name_and_params(name, params)?;
166        Ok(Self {
167            name,
168            params,
169            body: MacroBody::Scalar(expression.into()),
170        })
171    }
172
173    /// Creates a table SQL macro definition.
174    ///
175    /// Registers as:
176    /// ```sql
177    /// CREATE OR REPLACE MACRO name(params) AS TABLE query
178    /// ```
179    ///
180    /// # Errors
181    ///
182    /// Returns [`ExtensionError`] if `name` or any parameter name is invalid.
183    ///
184    /// # Example
185    ///
186    /// ```rust
187    /// use quack_rs::sql_macro::SqlMacro;
188    ///
189    /// let m = SqlMacro::table(
190    ///     "active_rows",
191    ///     &["tbl"],
192    ///     // Read a table parameter through `query_table`; a bare `FROM tbl`
193    ///     // is resolved when the macro is created, and fails.
194    ///     "SELECT * FROM query_table(tbl) WHERE active = true",
195    /// )?;
196    /// # Ok::<_, quack_rs::error::ExtensionError>(())
197    /// ```
198    pub fn table(
199        name: &str,
200        params: &[&str],
201        query: impl Into<String>,
202    ) -> Result<Self, ExtensionError> {
203        let (name, params) = validate_name_and_params(name, params)?;
204        Ok(Self {
205            name,
206            params,
207            body: MacroBody::Table(query.into()),
208        })
209    }
210
211    /// Returns the `CREATE OR REPLACE MACRO` SQL statement for this definition.
212    ///
213    /// The macro name and parameter names are emitted as double-quoted
214    /// identifiers; see the [module docs][crate::sql_macro#sql-injection-safety].
215    /// The body is emitted verbatim — except that a scalar body containing
216    /// `--` is followed by a newline before the closing parenthesis, so a
217    /// trailing line comment cannot swallow it.
218    ///
219    /// Useful for logging, testing, and inspection without a live connection.
220    ///
221    /// # Example
222    ///
223    /// ```rust
224    /// use quack_rs::sql_macro::SqlMacro;
225    ///
226    /// let m = SqlMacro::scalar("add", &["a", "b"], "a + b").unwrap();
227    /// assert_eq!(m.to_sql(), r#"CREATE OR REPLACE MACRO "add"("a", "b") AS (a + b)"#);
228    ///
229    /// // A table parameter is read through `query_table`: a bare `FROM tbl` would
230    /// // look for a table named `tbl` when the macro is created, and fail.
231    /// let t = SqlMacro::table("active_rows", &["tbl"], "SELECT * FROM query_table(tbl) WHERE active = true")
232    ///     .unwrap();
233    /// assert_eq!(
234    ///     t.to_sql(),
235    ///     r#"CREATE OR REPLACE MACRO "active_rows"("tbl") AS TABLE SELECT * FROM query_table(tbl) WHERE active = true"#
236    /// );
237    /// ```
238    #[must_use]
239    pub fn to_sql(&self) -> String {
240        // Validation (`validate_function_name`) guarantees no `"` in any
241        // identifier, so wrapping in quotes needs no escaping.
242        let quote = |ident: &str| format!("\"{ident}\"");
243        let name = quote(&self.name);
244        let params = self
245            .params
246            .iter()
247            .map(|p| quote(p))
248            .collect::<Vec<_>>()
249            .join(", ");
250        match &self.body {
251            // A `--` comment runs to the end of the line, and would comment
252            // out the `)` appended here. Only bodies that could hold one get
253            // the newline, so ordinary definitions keep their one-line SQL.
254            MacroBody::Scalar(expr) if expr.contains("--") => {
255                format!("CREATE OR REPLACE MACRO {name}({params}) AS ({expr}\n)")
256            }
257            MacroBody::Scalar(expr) => {
258                format!("CREATE OR REPLACE MACRO {name}({params}) AS ({expr})")
259            }
260            MacroBody::Table(query) => {
261                format!("CREATE OR REPLACE MACRO {name}({params}) AS TABLE {query}")
262            }
263        }
264    }
265
266    /// Registers this macro on the given connection.
267    ///
268    /// Executes the `CREATE OR REPLACE MACRO` statement via `duckdb_query` —
269    /// after checking with `duckdb_extract_statements`, `DuckDB`'s own parser,
270    /// that it is exactly one statement. Read
271    /// [where a macro lives](crate::sql_macro#where-a-macro-lives-and-what-that-means)
272    /// first: the macro is created in the user's database, persists there,
273    /// and fails on a read-only database.
274    ///
275    /// # Errors
276    ///
277    /// Returns [`ExtensionError`] if the SQL does not parse, or the body makes it
278    /// more than one statement (nothing is executed in either case; the parse
279    /// error is `DuckDB`'s own), or if `DuckDB` rejects the SQL
280    /// statement — for example on a read-only database. The error message is
281    /// extracted from `duckdb_result_error`.
282    ///
283    /// # Safety
284    ///
285    /// `con` must be a valid, open [`duckdb_connection`].
286    pub unsafe fn register(self, con: duckdb_connection) -> Result<(), ExtensionError> {
287        let sql = self.to_sql();
288        // SAFETY: caller guarantees con is valid and open.
289        let statements = unsafe { count_statements(con, &sql) }.map_err(|e| {
290            ExtensionError::new(format!("macro '{}': {e} Nothing was executed.", self.name))
291        })?;
292        if statements != 1 {
293            return Err(ExtensionError::new(format!(
294                "macro '{}': the body turns CREATE MACRO into {statements} SQL statements; a \
295                 macro body must be a single expression or query, with no top-level `;`. \
296                 Nothing was executed.",
297                self.name
298            )));
299        }
300        // SAFETY: caller guarantees con is valid and open.
301        unsafe { execute_sql(con, &sql) }
302            .map_err(|e| ExtensionError::new(format!("macro '{}': {e}", self.name)))
303    }
304
305    /// Returns the macro name.
306    #[must_use]
307    pub fn name(&self) -> &str {
308        &self.name
309    }
310
311    /// Returns the macro parameter names.
312    #[must_use]
313    pub fn params(&self) -> &[String] {
314        &self.params
315    }
316
317    /// Returns the macro body.
318    #[must_use]
319    pub const fn body(&self) -> &MacroBody {
320        &self.body
321    }
322}
323
324/// Validates a macro name ([`validate_function_name`]) and all parameter
325/// names ([`validate_parameter_name`]).
326fn validate_name_and_params(
327    name: &str,
328    params: &[&str],
329) -> Result<(String, Vec<String>), ExtensionError> {
330    validate_function_name(name)?;
331    for &param in params {
332        validate_parameter_name(param).map_err(|e| param_error(param, e.as_str()))?;
333    }
334    Ok((
335        name.to_owned(),
336        params.iter().map(|&p| p.to_owned()).collect(),
337    ))
338}
339
340/// Rewords a [`validate_function_name`] error for a parameter.
341///
342/// The validator speaks of a "function name"; for a parameter that is
343/// misleading, and its keyword advice (`SELECT order(...)` is a parser error)
344/// is about calling a function, not about referring to a parameter.
345fn param_error(param: &str, detail: &str) -> ExtensionError {
346    if detail.contains("reserved keyword") {
347        return ExtensionError::new(format!(
348            "invalid parameter name '{param}': it is a reserved keyword in DuckDB's SQL, so the \
349             macro body could only refer to it as \"{param}\"; choose another name"
350        ));
351    }
352    let detail = detail
353        .strip_prefix("function name")
354        .map_or_else(|| detail.to_owned(), |rest| format!("parameter name{rest}"));
355    ExtensionError::new(format!("invalid parameter name '{param}': {detail}"))
356}
357
358/// Counts the statements `DuckDB`'s parser finds in `sql`.
359///
360/// Fails when `sql` does not parse at all (the parser reports 0 statements). That
361/// must not fall through to executing the string: `DuckDB` 2.0 runs the statements of
362/// a multi-statement string that come before a parse error, so a body such as
363/// `1); DROP TABLE t; SELECT (1` (the third statement is not valid SQL) dropped the
364/// table on 2.0.0 while 1.4.4 and 1.5.6, which parse everything first, executed
365/// nothing. The error is `DuckDB`'s own parse error.
366///
367/// # Safety
368///
369/// `con` must be a valid, open [`duckdb_connection`].
370unsafe fn count_statements(con: duckdb_connection, sql: &str) -> Result<u64, ExtensionError> {
371    let c_sql = CString::new(sql)
372        .map_err(|_| ExtensionError::new("SQL statement contains interior null bytes"))?;
373    let mut extracted: libduckdb_sys::duckdb_extracted_statements = std::ptr::null_mut();
374    // SAFETY: con is valid; c_sql is NUL-terminated; `extracted` is a valid
375    // out-pointer, always allocated by DuckDB when `con` and `sql` are non-null.
376    let count = unsafe {
377        libduckdb_sys::duckdb_extract_statements(con, c_sql.as_ptr(), &raw mut extracted)
378    };
379    let parse_error = if count == 0 {
380        // SAFETY: `extracted` came from `duckdb_extract_statements` and is not yet
381        // destroyed. The returned string is owned by it (`wrapper->error.c_str()`
382        // at v1.4.4 and v1.5.6) or null; it is copied here, before the destroy below.
383        let message = unsafe { libduckdb_sys::duckdb_extract_statements_error(extracted) };
384        if message.is_null() {
385            None
386        } else {
387            // SAFETY: non-null, NUL-terminated, valid until the destroy below.
388            Some(
389                unsafe { std::ffi::CStr::from_ptr(message) }
390                    .to_string_lossy()
391                    .into_owned(),
392            )
393        }
394    } else {
395        None
396    };
397    // SAFETY: `extracted` came from `duckdb_extract_statements` (or is null,
398    // which the destructor accepts) and is destroyed once.
399    unsafe { libduckdb_sys::duckdb_destroy_extracted(&raw mut extracted) };
400    if count == 0 {
401        return Err(ExtensionError::new(parse_error.map_or_else(
402            || "DuckDB could not parse the statement.".to_owned(),
403            |message| {
404                format!(
405                    "DuckDB could not parse the statement: {}",
406                    message.trim_end()
407                )
408            },
409        )));
410    }
411    Ok(count)
412}
413
414/// Executes a SQL statement on `con`, surfacing any `DuckDB` error.
415///
416/// Always calls `duckdb_destroy_result`, even on failure.
417///
418/// # Safety
419///
420/// `con` must be a valid, open [`duckdb_connection`].
421unsafe fn execute_sql(con: duckdb_connection, sql: &str) -> Result<(), ExtensionError> {
422    let c_sql = CString::new(sql)
423        .map_err(|_| ExtensionError::new("SQL statement contains interior null bytes"))?;
424
425    // Zero-initialize: duckdb_result contains only integer and pointer fields,
426    // all of which are valid when zero / null.
427    //
428    // SAFETY: duckdb_result is a C struct; zero is a valid bit pattern for every field.
429    let mut result: duckdb_result = unsafe { std::mem::zeroed() };
430
431    // SAFETY: con is valid; c_sql is a valid nul-terminated C string.
432    let rc = unsafe { duckdb_query(con, c_sql.as_ptr(), &raw mut result) };
433
434    // Extract the error message before freeing, because duckdb_result_error
435    // returns a pointer into the result's internal buffer.
436    let outcome = if rc == DuckDBSuccess {
437        Ok(())
438    } else {
439        // SAFETY: result was populated by duckdb_query; duckdb_result_error
440        // returns a pointer valid until duckdb_destroy_result.
441        let ptr = unsafe { duckdb_result_error(&raw mut result) };
442        let msg = if ptr.is_null() {
443            "DuckDB macro registration failed (no error message available)".to_string()
444        } else {
445            // SAFETY: ptr is a valid nul-terminated C string owned by the result.
446            unsafe { CStr::from_ptr(ptr) }
447                .to_string_lossy()
448                .into_owned()
449        };
450        Err(ExtensionError::new(msg))
451    };
452
453    // SAFETY: result was populated by duckdb_query and must always be freed.
454    unsafe { duckdb_destroy_result(&raw mut result) };
455
456    outcome
457}
458
459#[cfg(test)]
460mod tests {
461    use super::*;
462
463    // -----------------------------------------------------------------------
464    // to_sql() — pure-Rust, no DuckDB connection needed
465    // -----------------------------------------------------------------------
466
467    #[test]
468    fn scalar_no_params_to_sql() {
469        let m = SqlMacro::scalar("pi", &[], "3.14159265358979").unwrap();
470        assert_eq!(
471            m.to_sql(),
472            r#"CREATE OR REPLACE MACRO "pi"() AS (3.14159265358979)"#
473        );
474    }
475
476    #[test]
477    fn scalar_one_param_to_sql() {
478        let m = SqlMacro::scalar("double_it", &["x"], "x * 2").unwrap();
479        assert_eq!(
480            m.to_sql(),
481            r#"CREATE OR REPLACE MACRO "double_it"("x") AS (x * 2)"#
482        );
483    }
484
485    #[test]
486    fn scalar_multiple_params_to_sql() {
487        let m = SqlMacro::scalar("add", &["a", "b"], "a + b").unwrap();
488        assert_eq!(
489            m.to_sql(),
490            r#"CREATE OR REPLACE MACRO "add"("a", "b") AS (a + b)"#
491        );
492    }
493
494    #[test]
495    fn scalar_complex_expression_to_sql() {
496        let m =
497            SqlMacro::scalar("clamp", &["x", "lo", "hi"], "greatest(lo, least(hi, x))").unwrap();
498        assert_eq!(
499            m.to_sql(),
500            r#"CREATE OR REPLACE MACRO "clamp"("x", "lo", "hi") AS (greatest(lo, least(hi, x)))"#
501        );
502    }
503
504    #[test]
505    fn table_no_params_to_sql() {
506        let m = SqlMacro::table("all_data", &[], "SELECT 1 AS n").unwrap();
507        assert_eq!(
508            m.to_sql(),
509            r#"CREATE OR REPLACE MACRO "all_data"() AS TABLE SELECT 1 AS n"#
510        );
511    }
512
513    #[test]
514    fn table_with_param_to_sql() {
515        let m = SqlMacro::table(
516            "active_rows",
517            &["tbl"],
518            "SELECT * FROM query_table(tbl) WHERE active = true",
519        )
520        .unwrap();
521        assert_eq!(
522            m.to_sql(),
523            r#"CREATE OR REPLACE MACRO "active_rows"("tbl") AS TABLE SELECT * FROM query_table(tbl) WHERE active = true"#
524        );
525    }
526
527    /// Identifiers are always quoted, so a keyword or mixed-case name reaches
528    /// `DuckDB` intact instead of as a parser error.
529    #[test]
530    fn identifiers_are_double_quoted() {
531        let m = SqlMacro::scalar("MyMacro", &["X", "_y"], "X + _y").unwrap();
532        assert_eq!(
533            m.to_sql(),
534            r#"CREATE OR REPLACE MACRO "MyMacro"("X", "_y") AS (X + _y)"#
535        );
536    }
537
538    // -----------------------------------------------------------------------
539    // Name and parameter validation
540    // -----------------------------------------------------------------------
541
542    #[test]
543    fn mixed_case_macro_name_accepted() {
544        // DuckDB identifiers are case-insensitive and DuckDB ships mixed-case
545        // functions, so rejecting these made a legal name unusable.
546        assert!(SqlMacro::scalar("MyMacro", &[], "1").is_ok());
547        assert!(SqlMacro::scalar("my-macro", &[], "1").is_err());
548    }
549
550    #[test]
551    fn invalid_macro_name_hyphen_rejected() {
552        assert!(SqlMacro::scalar("my-macro", &[], "1").is_err());
553    }
554
555    #[test]
556    fn invalid_macro_name_empty_rejected() {
557        assert!(SqlMacro::scalar("", &[], "1").is_err());
558    }
559
560    #[test]
561    fn mixed_case_param_accepted_but_quoting_chars_are_not() {
562        assert!(SqlMacro::scalar("f", &["GoodParam"], "1").is_ok());
563        let err = SqlMacro::scalar("f", &["bad param"], "1").unwrap_err();
564        assert!(err.as_str().contains("bad param"));
565        assert!(
566            err.as_str()
567                .contains("parameter name contains invalid character"),
568            "{err}"
569        );
570        assert!(!err.as_str().contains("function name"), "{err}");
571    }
572
573    #[test]
574    fn a_keyword_parameter_is_refused_with_a_parameter_specific_message() {
575        let err = SqlMacro::scalar("f", &["order"], "1").unwrap_err();
576        assert!(
577            err.as_str().contains("invalid parameter name 'order'"),
578            "{err}"
579        );
580        assert!(err.as_str().contains("reserved keyword"), "{err}");
581        assert!(!err.as_str().contains("function name"), "{err}");
582    }
583
584    #[test]
585    fn a_scalar_body_with_a_line_comment_ends_with_a_newline() {
586        let m = SqlMacro::scalar("f", &["x"], "x + 1 -- plus one").unwrap();
587        assert_eq!(
588            m.to_sql(),
589            "CREATE OR REPLACE MACRO \"f\"(\"x\") AS (x + 1 -- plus one\n)"
590        );
591    }
592
593    #[test]
594    fn invalid_param_hyphen_rejected() {
595        assert!(SqlMacro::scalar("f", &["a-b"], "1").is_err());
596    }
597
598    #[test]
599    fn valid_underscore_prefix_param() {
600        assert!(SqlMacro::scalar("f", &["_x"], "1").is_ok());
601    }
602
603    #[test]
604    fn valid_single_letter_params() {
605        let m = SqlMacro::scalar("clamp", &["x", "lo", "hi"], "1").unwrap();
606        assert_eq!(m.params(), ["x", "lo", "hi"]);
607    }
608
609    #[test]
610    fn name_and_params_stored_correctly() {
611        let m = SqlMacro::scalar("f", &["a", "b", "c"], "a+b+c").unwrap();
612        assert_eq!(m.name(), "f");
613        assert_eq!(m.params(), ["a", "b", "c"]);
614    }
615
616    // -----------------------------------------------------------------------
617    // Body variant accessors
618    // -----------------------------------------------------------------------
619
620    #[test]
621    fn scalar_body_variant() {
622        let m = SqlMacro::scalar("f", &["x"], "x + 1").unwrap();
623        assert_eq!(m.body(), &MacroBody::Scalar("x + 1".to_string()));
624    }
625
626    #[test]
627    fn table_body_variant() {
628        let m = SqlMacro::table("t", &[], "SELECT 1").unwrap();
629        assert_eq!(m.body(), &MacroBody::Table("SELECT 1".to_string()));
630    }
631
632    // -----------------------------------------------------------------------
633    // Clone and Debug
634    // -----------------------------------------------------------------------
635
636    #[test]
637    fn sql_macro_is_cloneable() {
638        let m = SqlMacro::scalar("f", &["x"], "x").unwrap();
639        let m2 = m.clone();
640        assert_eq!(m.to_sql(), m2.to_sql());
641    }
642
643    #[test]
644    fn macro_body_is_eq() {
645        assert_eq!(MacroBody::Scalar("x".into()), MacroBody::Scalar("x".into()));
646        assert_ne!(MacroBody::Scalar("x".into()), MacroBody::Table("x".into()));
647    }
648}