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 /// PostgreSQL and SQLite take it on an aggregate; MySQL and MariaDB have
69 /// none, so their builders refuse it with a [`RenderError`].
70 ///
71 /// # Examples
72 ///
73 /// ```
74 /// use sql_builder::*;
75 ///
76 /// let query = Query::select()
77 /// .expr_as(
78 /// Func::count(Expr::val(1))
79 /// .filter(
80 /// Cond::all()
81 /// .add(Expr::col("character").eq("foo"))
82 /// .add(Expr::col("size_w").eq(1))
83 /// ),
84 /// Alias::new("filtered_total")
85 /// )
86 /// .expr_as(Func::count(Expr::val(1)), Alias::new("total"))
87 /// .from("character")
88 /// .to_owned();
89 ///
90 /// assert_eq!(
91 /// query.to_string(PostgresQueryBuilder).unwrap(),
92 /// r#"SELECT COUNT(1) FILTER (WHERE "character" = 'foo' AND "size_w" = 1) AS "filtered_total", COUNT(1) AS "total" FROM "character""#
93 /// );
94 /// assert_eq!(
95 /// query.to_string(SqliteQueryBuilder).unwrap(),
96 /// r#"SELECT COUNT(1) FILTER (WHERE "character" = 'foo' AND "size_w" = 1) AS "filtered_total", COUNT(1) AS "total" FROM "character""#
97 /// );
98 /// ```
99 pub fn filter(mut self, condition: impl Into<Condition>) -> Self {
100 self.filter = Some(condition.into());
101 self
102 }
103
104 pub fn get_filter(&self) -> Option<&Condition> {
105 self.filter.as_ref()
106 }
107}