backend/db/
function.rs

1//! Database functions for diesel query-builder.
2
3use diesel::{
4    define_sql_function,
5    expression::AsExpression,
6    pg::Pg,
7    sql_types::{Array, Float, Nullable, SqlType, Text},
8    Expression,
9};
10
11define_sql_function! {
12    /// The SQL function `array_to_string`.
13    ///
14    /// Used to convert arrays to strings using a delimiter.
15    fn array_to_string(
16        array: Nullable<Array<Nullable<Text>>>,
17        delimiter: Text
18    ) -> Text
19}
20
21define_sql_function! {
22    /// The `pg_trgm` SQL function `similarity`.
23    ///
24    /// Used to find how similar two strings are.
25    ///
26    /// If your column is nullable use [`similarity_nullable()`] instead.
27    fn similarity(
28        t1: Text,
29        t2: Text
30    ) -> Float
31}
32
33define_sql_function! {
34    /// The `pg_trgm` SQL function `similarity`.
35    ///
36    /// Used to find how similar two strings are.
37    ///
38    /// If your column is not nullable use [`similarity()`] instead.
39    #[sql_name = "similarity"]
40    fn similarity_nullable(
41        t1: Nullable<Text>,
42        t2: Text
43    ) -> Float
44}
45
46define_sql_function! {
47    /// The SQL function `greatest`.
48    ///
49    /// Used to find the greatest value of the inputs.
50    #[sql_name = "GREATEST"]
51    fn greatest3(
52        t1: Float,
53        t2: Float,
54        t3: Float,
55    ) -> Float
56}
57define_sql_function! {
58    /// The SQL function `greatest`.
59    ///
60    /// Used to find the greatest value of the inputs.
61    #[sql_name = "GREATEST"]
62    fn greatest4(
63        t1: Float,
64        t2: Float,
65        t3: Float,
66        t4: Float
67    ) -> Float
68}
69
70diesel::infix_operator!(PgTrgmFuzzy, " % ", backend: Pg);
71
72/// Implements `pg_trgm` methods for diesel
73pub trait PgTrgmExpressionMethods
74where
75    Self: Expression + Sized,
76{
77    /// Fuzzy search. Uses the `pg_trgm` `%` operator.
78    ///
79    /// The `%` operator uses the `pg_trgm` function `similarity` in the background with a default value of `0.3`.
80    /// <br>
81    /// If you want a different value use `similarity` with `gt/lt` instead.
82    fn fuzzy<U>(self, right: U) -> PgTrgmFuzzy<Self, U::Expression>
83    where
84        Self::SqlType: SqlType,
85        U: AsExpression<Self::SqlType>,
86    {
87        PgTrgmFuzzy::new(self, right.as_expression())
88    }
89}
90
91impl<T: Expression> PgTrgmExpressionMethods for T {}