Macro diesel::sql_function[][src]

macro_rules! sql_function {
    ($(# $meta : tt) * fn $fn_name : ident $args : tt $(;) *) => { ... };
    ($(# $meta : tt) * fn $fn_name : ident $args : tt -> $return_type : ty $(;) *) => { ... };
    ($(# $meta : tt) * fn $fn_name : ident < $($tokens : tt) *) => { ... };
    ($fn_name : ident, $struct_name : ident, $args : tt -> $return_type : ty) => { ... };
    ($fn_name : ident, $struct_name : ident, $args : tt -> $return_type : ty,
 $docs : expr) => { ... };
    ($fn_name : ident, $struct_name : ident,
 ($($arg_name : ident : $arg_type : ty), *)) => { ... };
    ($fn_name : ident, $struct_name : ident, $args : tt -> $return_type : ty,
 $docs : expr, $helper_ty_docs : expr) => { ... };
}
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:

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

will generate this code:

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

pub(crate) mod lower {
    pub type HelperType<X> = ...;
}

If you are using this macro for part of a library, where the function is part of your public API, it is highly recommended that you re-export this helper type with the same name as your function. This is the standard structure:

pub mod functions {
    use super::types::*;
    use diesel::sql_types::*;

    sql_function! {
        /// Represents the Pg `LENGTH` function used with `tsvector`s.
        fn length(x: TsVector) -> Integer;
    }
}

pub mod helper_types {
    /// The return type of `length(expr)`
    pub type Length<Expr> = functions::length::HelperType<Expr>;
}

pub mod dsl {
    pub use functions::*;
    pub use helper_types::*;
}

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

Adding Doc Comments

use diesel::sql_types::Text;

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 should not be implemented.
  • #[sql_name="name"]
    • The SQL to be generated is different than 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 an example of all of this:

use diesel::sql_types::Foldable;

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

crates.select(sum(id));

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 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. Generic functions and variadic functions are not supported on SQLite.

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

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

add_mul::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);