1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use super::Function;
use crate::ast::{Column, Expression};

/// Defines a grouping for the `GROUP BY` statement.
pub type GroupByDefinition<'a> = Expression<'a>;

/// A list of definitions for the `GROUP BY` statement
#[derive(Debug, Default, PartialEq, Clone)]
pub struct Grouping<'a>(pub Vec<GroupByDefinition<'a>>);

impl<'a> Grouping<'a> {
    #[doc(hidden)]
    pub fn append(mut self, value: GroupByDefinition<'a>) -> Self {
        self.0.push(value);
        self
    }

    pub fn new(values: Vec<GroupByDefinition<'a>>) -> Self {
        Self(values)
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// An item that can be used in the `GROUP BY` statement
pub trait Groupable<'a>
where
    Self: Sized,
{
    /// Group by `self`
    fn group(self) -> GroupByDefinition<'a>;
}

/// Convert the value into a group by definition.
pub trait IntoGroupByDefinition<'a> {
    fn into_group_by_definition(self) -> GroupByDefinition<'a>;
}

impl<'a> IntoGroupByDefinition<'a> for &'a str {
    fn into_group_by_definition(self) -> GroupByDefinition<'a> {
        let column: Column = self.into();
        column.into()
    }
}

impl<'a> IntoGroupByDefinition<'a> for (&'a str, &'a str) {
    fn into_group_by_definition(self) -> GroupByDefinition<'a> {
        let column: Column = self.into();
        column.into()
    }
}

impl<'a> IntoGroupByDefinition<'a> for Column<'a> {
    fn into_group_by_definition(self) -> GroupByDefinition<'a> {
        self.into()
    }
}

impl<'a> IntoGroupByDefinition<'a> for Function<'a> {
    fn into_group_by_definition(self) -> GroupByDefinition<'a> {
        self.into()
    }
}

impl<'a> IntoGroupByDefinition<'a> for GroupByDefinition<'a> {
    fn into_group_by_definition(self) -> GroupByDefinition<'a> {
        self
    }
}

impl<'a> Groupable<'a> for Column<'a> {
    fn group(self) -> GroupByDefinition<'a> {
        self.into()
    }
}

impl<'a> Groupable<'a> for &'a str {
    fn group(self) -> GroupByDefinition<'a> {
        Column::from(self).group()
    }
}