Skip to main content

sql_builder/func/
call.rs

1use super::*;
2
3/// Function call.
4#[derive(Debug, Clone, PartialEq)]
5pub struct FunctionCall {
6    pub(crate) func: Func,
7    pub(crate) args: Vec<Expr>,
8    pub(crate) mods: Vec<FuncArgMod>,
9    pub(crate) filter: Option<Condition>,
10}
11
12#[derive(Debug, Default, Copy, Clone, PartialEq)]
13pub struct FuncArgMod {
14    pub distinct: bool,
15}
16
17impl FunctionCall {
18    pub(crate) fn new(func: impl Into<Func>) -> Self {
19        Self {
20            func: func.into(),
21            args: Vec::new(),
22            mods: Vec::new(),
23            filter: None,
24        }
25    }
26
27    /// Append an argument to the function call
28    pub fn arg<T>(self, arg: T) -> Self
29    where
30        T: Into<Expr>,
31    {
32        self.arg_with(arg, Default::default())
33    }
34
35    pub(crate) fn arg_with<T>(mut self, arg: T, mod_: FuncArgMod) -> Self
36    where
37        T: Into<Expr>,
38    {
39        self.args.push(arg.into());
40        self.mods.push(mod_);
41        self
42    }
43
44    /// Replace the arguments of the function call
45    pub fn args<I>(mut self, args: I) -> Self
46    where
47        I: IntoIterator<Item = Expr>,
48    {
49        self.args = args.into_iter().collect();
50        self.mods = vec![Default::default(); self.args.len()];
51        self
52    }
53
54    pub fn get_func(&self) -> &Func {
55        &self.func
56    }
57
58    pub fn get_args(&self) -> &[Expr] {
59        &self.args
60    }
61
62    pub fn get_mods(&self) -> &[FuncArgMod] {
63        &self.mods
64    }
65
66    /// Append a `FILTER (WHERE ...)` clause to the function call.
67    ///
68    /// # Examples
69    ///
70    /// ```
71    /// use sql_builder::*;
72    ///
73    /// let query = Query::select()
74    ///     .expr_as(
75    ///         Func::count(Expr::val(1))
76    ///             .filter(
77    ///                 Cond::all()
78    ///                     .add(Expr::col("character").eq("foo"))
79    ///                     .add(Expr::col("size_w").eq(1))
80    ///             ),
81    ///         Alias::new("filtered_total")
82    ///     )
83    ///     .expr_as(Func::count(Expr::val(1)), Alias::new("total"))
84    ///     .from("character")
85    ///     .to_owned();
86    ///
87    /// assert_eq!(
88    ///     query.to_string(PostgresQueryBuilder).unwrap(),
89    ///     r#"SELECT COUNT(1) FILTER (WHERE "character" = 'foo' AND "size_w" = 1) AS "filtered_total", COUNT(1) AS "total" FROM "character""#
90    /// );
91    /// assert_eq!(
92    ///     query.to_string(SqliteQueryBuilder).unwrap(),
93    ///     r#"SELECT COUNT(1) FILTER (WHERE "character" = 'foo' AND "size_w" = 1) AS "filtered_total", COUNT(1) AS "total" FROM "character""#
94    /// );
95    /// ```
96    pub fn filter(mut self, condition: impl Into<Condition>) -> Self {
97        self.filter = Some(condition.into());
98        self
99    }
100
101    pub fn get_filter(&self) -> Option<&Condition> {
102        self.filter.as_ref()
103    }
104}