Macro diesel::prelude::sql_function
source · 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:
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.
- Indicates that this is an aggregate function, and that
#[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));
§SQL Functions without Arguments
A common example is ordering a query using the RANDOM()
sql function,
which can be implemented using sql_function!
like this:
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
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 = &mut 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);
§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 cannot propagate the panics due to the FFI bounary.
This is is the same for custom aggregate functions.
§Custom Aggregate Functions
Custom aggregate functions can be created in SQLite by adding an #[aggregate]
attribute inside of sql_function
. register_impl
needs to be called on
the generated function 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;
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::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;
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::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_semeseter_avg) = result {
println!("The largest semester average is: {}", max_semeseter_avg);
}
Ok(())
}