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.
This is a legacy variant of the [#[declare_sql_function]
] attribute macro, which
should be preferred instead. It will generate the same code as the attribute macro
and also it will accept the same syntax as the other macro.
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.
- Indicates that this is an aggregate function, and that
#[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.