open_pql/pql_parser/ast/
selector.rs

1use super::*;
2
3#[derive(PartialEq, Eq, Debug, Display)]
4pub enum SelectorKind {
5    Avg,
6    Count,
7    Max,
8    Min,
9}
10
11#[derive(PartialEq, Eq, Debug)]
12pub struct Selector<'i> {
13    pub kind: SelectorKind,
14    pub expr: Expr<'i>,
15    pub alias: Option<Ident<'i>>,
16}
17
18impl<'i> Selector<'i> {
19    pub fn new(
20        kind: &Ident<'i>,
21        expr: Expr<'i>,
22        alias: Option<Ident<'i>>,
23    ) -> ResultE<'i, Self> {
24        let kind = match kind.inner.to_ascii_lowercase().as_str() {
25            "avg" => SelectorKind::Avg,
26            "count" => SelectorKind::Count,
27            "max" => SelectorKind::Max,
28            "min" => SelectorKind::Min,
29            _ => return Err(Error::UnrecognizedSelector(kind.loc).into()),
30        };
31
32        Ok(Self { kind, expr, alias })
33    }
34}
35
36#[cfg(test)]
37mod tests {
38    use super::{super::super::parser::*, *};
39
40    fn s(s: &str) -> Selector<'_> {
41        SelectorParser::new().parse(s).unwrap()
42    }
43
44    fn e(s: &str) -> Error {
45        SelectorParser::new().parse(s).unwrap_err().into()
46    }
47
48    #[test]
49    fn test_selector() {
50        let obj1 = s("avg(equity(hero, river))");
51        let obj2 = s("avg(equity(hero, river)) as s1");
52
53        assert_eq!(obj1.kind, obj2.kind);
54        assert_eq!(obj1.expr, obj2.expr);
55
56        assert_eq!(obj1.kind, SelectorKind::Avg);
57        assert![matches!(obj1.expr, Expr::FnCall(_))];
58        assert_eq!(obj1.alias, None);
59
60        assert_eq!(obj2.alias, Some(("s1", (28, 30)).into()));
61    }
62
63    #[test]
64    fn test_selector_err() {
65        assert_eq!(e("invalid(_)"), Error::UnrecognizedSelector((0, 7)));
66    }
67}