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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
use crate::common::{FQName, Identifier, OrderClause, RelationElement};
use itertools::Itertools;
use std::fmt::{Display, Formatter};

/// data for select statements
#[derive(PartialEq, Debug, Clone)]
pub struct Select {
    /// if true DISTINCT results
    pub distinct: bool,
    /// if true JSON reslts
    pub json: bool,
    /// The table name.
    pub table_name: FQName,
    /// the list of elements to select.
    pub columns: Vec<SelectElement>,
    /// the where clause
    pub where_clause: Vec<RelationElement>,
    /// the optional ordering
    pub order: Option<OrderClause>,
    /// the number of items to return
    pub limit: Option<i32>,
    /// if true ALLOW FILTERING is displayed
    pub filtering: bool,
}

impl Select {
    /// return the column names selected
    /// does not return functions.
    pub fn select_names(&self) -> Vec<String> {
        self.columns
            .iter()
            .filter_map(|e| {
                if let SelectElement::Column(named) = e {
                    Some(named.to_string())
                } else {
                    None
                }
            })
            .collect()
    }

    /// return the aliased column names.  If the column is not aliased the
    /// base column name is returned.
    /// does not return functions.
    pub fn select_alias(&self) -> Vec<Identifier> {
        self.columns
            .iter()
            .filter_map(|e| match e {
                SelectElement::Column(named) => {
                    Some(named.alias.clone().unwrap_or_else(|| named.name.clone()))
                }
                _ => None,
            })
            .collect()
    }
}

impl Display for Select {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "SELECT {}{}{} FROM {}{}{}{}{}",
            if self.distinct { "DISTINCT " } else { "" },
            if self.json { "JSON " } else { "" },
            self.columns.iter().join(", "),
            self.table_name,
            if !self.where_clause.is_empty() {
                format!(" WHERE {}", self.where_clause.iter().join(" AND "))
            } else {
                "".to_string()
            },
            self.order
                .as_ref()
                .map_or("".to_string(), |x| format!(" ORDER BY {}", x)),
            self.limit
                .map_or("".to_string(), |x| format!(" LIMIT {}", x)),
            if self.filtering {
                " ALLOW FILTERING"
            } else {
                ""
            }
        )
    }
}

/// the selectable elements for a select statement
#[derive(PartialEq, Debug, Clone)]
pub enum SelectElement {
    /// All of the columns
    Star,
    /// a named column.  May have an alias specified.
    Column(Named),
    /// a named column.  May have an alias specified.
    Function(Named),
}

impl Display for SelectElement {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            SelectElement::Star => write!(f, "*"),
            SelectElement::Column(named) | SelectElement::Function(named) => write!(f, "{}", named),
        }
    }
}

#[derive(PartialEq, Debug, Clone)]
pub struct Named {
    pub name: Identifier,
    pub alias: Option<Identifier>,
}

/// the name an optional alias for a named item.
impl Named {
    pub fn new(name: &str, alias: &str) -> Named {
        Named {
            name: Identifier::parse(name),
            alias: Some(Identifier::parse(alias)),
        }
    }

    pub fn simple(name: &str) -> Named {
        Named {
            name: Identifier::parse(name),
            alias: None,
        }
    }

    pub fn alias_or_name(&self) -> &Identifier {
        match &self.alias {
            None => &self.name,
            Some(alias) => alias,
        }
    }
}

impl Display for Named {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match &self.alias {
            None => write!(f, "{}", self.name),
            Some(a) => write!(f, "{} AS {}", self.name, a),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::select::{Named, SelectElement};

    #[test]
    fn test_select_element_display() {
        assert_eq!("*", SelectElement::Star.to_string());
        assert_eq!(
            "col",
            SelectElement::Column(Named::simple("col")).to_string()
        );
        assert_eq!(
            "func",
            SelectElement::Function(Named::simple("func")).to_string()
        );
        assert_eq!(
            "col AS alias",
            SelectElement::Column(Named::new("col", "alias")).to_string()
        );
        assert_eq!(
            "func AS alias",
            SelectElement::Function(Named::new("func", "alias")).to_string()
        );
    }
}