open_pql/pql_parser/ast/
stmt.rs

1use super::*;
2
3#[derive(PartialEq, Eq, Debug)]
4pub struct Stmt<'i> {
5    pub selectors: Vec<Selector<'i>>,
6    pub from: FromClause<'i>,
7}
8
9fn ensure_uniq_names<'i>(selectors: &[Selector]) -> ResultE<'i, ()> {
10    let mut used = FxHashSet::default();
11
12    for selector in selectors {
13        if let Some(id) = &selector.alias
14            && !used.insert(id.inner.to_ascii_lowercase())
15        {
16            return Err(user_err(Error::DuplicatedSelectorName(id.loc)));
17        }
18    }
19
20    Ok(())
21}
22
23impl<'i> Stmt<'i> {
24    pub fn new(
25        selectors: Vec<Selector<'i>>,
26        from: FromClause<'i>,
27    ) -> ResultE<'i, Self> {
28        ensure_uniq_names(&selectors)?;
29
30        Ok(Self { selectors, from })
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use super::{super::super::parser::*, *};
37
38    fn s(s: &str) -> Stmt<'_> {
39        StmtParser::new().parse(s).unwrap()
40    }
41
42    fn e(s: &str) -> Error {
43        StmtParser::new().parse(s).unwrap_err().into()
44    }
45
46    #[test]
47    fn test_stmt() {
48        assert_eq!(s("select avg(_)  from _=''").selectors.len(), 1);
49        assert_eq!(s("select avg(_), from _=''").selectors.len(), 1);
50
51        assert_eq!(
52            s("select avg(_) as s1 from _=''").selectors[0].alias,
53            Some(("s1", (17, 19)).into())
54        );
55
56        assert_eq!(
57            e("select avg(_) as s1, avg(_) as s1 from _=''"),
58            Error::DuplicatedSelectorName((31, 33))
59        );
60    }
61}