1use std::str::FromStr;
2
3use crate::parser;
4use crate::sql::Env;
5use crate::sql::Expr;
6use crate::value::PqlValue;
7
8#[derive(Debug, Default, Clone, PartialEq)]
9pub struct Field {
10 pub expr: Expr,
11 pub alias: Option<String>,
12}
13
14impl FromStr for Field {
15 type Err = anyhow::Error;
16
17 fn from_str(s: &str) -> anyhow::Result<Self> {
18 match parser::expressions::parse_field(s) {
19 Ok((_, field)) => Ok(field),
20 Err(nom::Err::Error(err)) => {
21 eprint!("{}", err);
22 anyhow::bail!("failed")
23 }
24 _ => todo!(),
25 }
26 }
27}
28
29impl Field {
30 pub fn expand_fullpath(&self, env: &Env) -> Self {
31 Self {
32 expr: env.expand_fullpath(&self.expr),
33 alias: self.alias.to_owned(),
34 }
35 }
36
37 pub fn evaluate(self, env: &Env) -> PqlValue {
38 let value = self.expr.eval(&env);
39 value
40 }
41
42 pub fn rename(self) -> (String, Expr) {
43 if let Some(alias) = self.alias {
44 (alias, self.expr)
45 } else {
46 let alias = match &self.expr {
47 Expr::Selector(selector) => selector.to_vec().last().unwrap().to_string(),
48 _ => todo!(),
49 };
50 (alias, self.expr)
51 }
52 }
53}