define_sql_function!() { /* proc-macro */ }
Expand description

Declare a sql function for use in your code.

Diesel only provides support for a very small number of SQL functions. This macro enables you to add additional functions from the SQL standard, as well as any custom functions your application might have.

The syntax for this macro is very similar to that of a normal Rust function, except the argument and return types will be the SQL types being used. Typically, these types will come from diesel::sql_types

This macro will generate two items. A function with the name that you’ve given, and a module with a helper type representing the return type of your function. For example, this invocation:

define_sql_function!(fn lower(x: Text) -> Text);

will generate this code:

pub fn lower<X>(x: X) -> lower<X> {
    ...
}

pub type lower<X> = ...;

Most attributes given to this macro will be put on the generated function (including doc comments).

§Adding Doc Comments

use diesel::sql_types::Text;

define_sql_function! {
    /// Represents the `canon_crate_name` SQL function, created in
    /// migration ....
    fn canon_crate_name(a: Text) -> Text;
}

let target_name = "diesel";
crates.filter(canon_crate_name(name).eq(canon_crate_name(target_name)));
// This will generate the following SQL
// SELECT * FROM crates WHERE canon_crate_name(crates.name) = canon_crate_name($1)

§Special Attributes

There are a handful of special attributes that Diesel will recognize. They are:

  • #[aggregate]
    • Indicates that this is an aggregate function, and that NonAggregate shouldn’t be implemented.
  • #[sql_name = "name"]
    • The SQL to be generated is different from the Rust name of the function. This can be used to represent functions which can take many argument types, or to capitalize function names.

Functions can also be generic. Take the definition of sum, for example:

use diesel::sql_types::Foldable;

define_sql_function! {
    #[aggregate]
    #[sql_name = "SUM"]
    fn sum<ST: Foldable>(expr: ST) -> ST::Sum;
}

crates.select(sum(id));

§SQL Functions without Arguments

A common example is ordering a query using the RANDOM() sql function, which can be implemented using define_sql_function! like this:

define_sql_function!(fn random() -> Text);

crates.order(random());

§Use with SQLite

On most backends, the implementation of the function is defined in a migration using CREATE FUNCTION. On SQLite, the function is implemented in Rust instead. You must call register_impl or register_nondeterministic_impl (in the generated function’s _internals module) with every connection before you can use the function.

These functions will only be generated if the sqlite feature is enabled, and the function is not generic. SQLite doesn’t support generic functions and variadic functions.

use diesel::sql_types::{Integer, Double};
define_sql_function!(fn add_mul(x: Integer, y: Integer, z: Double) -> Double);

let connection = &mut SqliteConnection::establish(":memory:")?;

add_mul_utils::register_impl(connection, |x: i32, y: i32, z: f64| {
    (x + y) as f64 * z
})?;

let result = select(add_mul(1, 2, 1.5))
    .get_result::<f64>(connection)?;
assert_eq!(4.5, result);

§Panics

If an implementation of the custom function panics and unwinding is enabled, the panic is caught and the function returns to libsqlite with an error. It can’t propagate the panics due to the FFI boundary.

This is the same for custom aggregate functions.

§Custom Aggregate Functions

Custom aggregate functions can be created in SQLite by adding an #[aggregate] attribute inside define_sql_function. register_impl (in the generated function’s _utils module) needs to be called with a type implementing the SqliteAggregateFunction trait as a type parameter as shown in the examples below.

use diesel::sql_types::Integer;
use diesel::sqlite::SqliteAggregateFunction;

define_sql_function! {
    #[aggregate]
    fn my_sum(x: Integer) -> Integer;
}

#[derive(Default)]
struct MySum { sum: i32 }

impl SqliteAggregateFunction<i32> for MySum {
    type Output = i32;

    fn step(&mut self, expr: i32) {
        self.sum += expr;
    }

    fn finalize(aggregator: Option<Self>) -> Self::Output {
        aggregator.map(|a| a.sum).unwrap_or_default()
    }
}

fn run() -> Result<(), Box<dyn (::std::error::Error)>> {
    let connection = &mut SqliteConnection::establish(":memory:")?;

    my_sum_utils::register_impl::<MySum, _>(connection)?;

    let total_score = players.select(my_sum(score))
        .get_result::<i32>(connection)?;

    println!("The total score of all the players is: {}", total_score);

    Ok(())
}

With multiple function arguments, the arguments are passed as a tuple to SqliteAggregateFunction

use diesel::sql_types::{Float, Nullable};
use diesel::sqlite::SqliteAggregateFunction;

define_sql_function! {
    #[aggregate]
    fn range_max(x0: Float, x1: Float) -> Nullable<Float>;
}

#[derive(Default)]
struct RangeMax<T> { max_value: Option<T> }

impl<T: Default + PartialOrd + Copy + Clone> SqliteAggregateFunction<(T, T)> for RangeMax<T> {
    type Output = Option<T>;

    fn step(&mut self, (x0, x1): (T, T)) {
        // Compare self.max_value to x0 and x1
    }

    fn finalize(aggregator: Option<Self>) -> Self::Output {
        aggregator?.max_value
    }
}

fn run() -> Result<(), Box<dyn (::std::error::Error)>> {
    let connection = &mut SqliteConnection::establish(":memory:")?;

    range_max_utils::register_impl::<RangeMax<f32>, _, _>(connection)?;

    let result = student_avgs.select(range_max(s1_avg, s2_avg))
        .get_result::<Option<f32>>(connection)?;

    if let Some(max_semester_avg) = result {
        println!("The largest semester average is: {}", max_semester_avg);
    }

    Ok(())
}