//! SCQL 方言的抽象语法树,逐位对齐 `refs/nax/nax/sql/ast.py`。 //! //! 节点只描述「查询说了什么」,不含执行语义;执行语义在 [`crate::engine`]。 use std::fmt; /// 字面量 / 单元格值:数字或字符串。 #[derive(Clone, Debug, PartialEq)] pub enum Value { Num(f64), Str(String), } impl Value { pub fn as_num(&self) -> Option { match self { Value::Num(v) => Some(*v), Value::Str(_) => None, } } pub fn as_str(&self) -> Option<&str> { match self { Value::Str(s) => Some(s), Value::Num(_) => None, } } } impl fmt::Display for Value { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Value::Num(v) => { // 整数形态不带小数点,贴近 Python 的 repr(int) if v.fract() == 0.0 && v.abs() < 1e15 { write!(f, "{}", *v as i64) } else { write!(f, "{v}") } } Value::Str(s) => write!(f, "'{s}'"), } } } /// 列引用,可带表限定名。 #[derive(Clone, Debug, PartialEq, Eq)] pub struct Column { pub table: Option, pub name: String, } impl Column { pub fn new(table: Option, name: String) -> Self { Self { table, name } } } impl fmt::Display for Column { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match &self.table { Some(t) => write!(f, "{t}.{}", self.name), None => write!(f, "{}", self.name), } } } /// 表达式。 #[derive(Clone, Debug, PartialEq)] pub enum Expr { Column(Column), Literal(Value), BinOp { op: String, left: Box, right: Box, }, UnaryOp { op: String, operand: Box, }, InList { expr: Box, values: Vec, negated: bool, }, Agg { func: String, arg: Option>, }, } impl Expr { /// 与 Python `__str__` 一致的标签串,用于 SELECT 默认列名与 HAVING / ORDER BY 匹配。 pub fn label(&self) -> String { match self { Expr::Column(c) => c.to_string(), Expr::Literal(v) => v.to_string(), Expr::BinOp { op, left, right } => format!("({} {op} {})", left.label(), right.label()), Expr::UnaryOp { op, operand } => format!("{op}({})", operand.label()), Expr::InList { expr, values, negated, } => { let kw = if *negated { "NOT IN" } else { "IN" }; let vals: Vec = values.iter().map(|v| v.to_string()).collect(); format!("({} {kw} ({},))", expr.label(), vals.join(", ")) } Expr::Agg { func, arg } => match arg { None => format!("{func}(*)"), Some(a) => format!("{func}({})", a.label()), }, } } } /// SELECT 项。 #[derive(Clone, Debug, PartialEq)] pub struct SelectItem { pub expr: Expr, pub alias: Option, } impl SelectItem { pub fn label(&self) -> String { self.alias.clone().unwrap_or_else(|| self.expr.label()) } } /// 表引用(含别名)。 #[derive(Clone, Debug, PartialEq, Eq)] pub struct TableRef { pub name: String, pub alias: Option, } impl TableRef { /// 查询里引用这张表时使用的名字。 pub fn key(&self) -> String { self.alias.clone().unwrap_or_else(|| self.name.clone()) } } /// 受限等值内连接(由 PSI 完成)。 #[derive(Clone, Debug, PartialEq)] pub struct Join { pub right: TableRef, pub left_key: Column, pub right_key: Column, } /// ORDER BY 键。 #[derive(Clone, Debug, PartialEq)] pub struct OrderKey { pub expr: Expr, pub descending: bool, } /// 一条查询。 #[derive(Clone, Debug, PartialEq)] pub struct Query { pub select: Vec, pub from: TableRef, pub join: Option, pub where_: Option, pub group_by: Vec, pub having: Option, pub order_by: Vec, pub limit: Option, } impl Query { pub fn tables(&self) -> Vec<&TableRef> { let mut v = vec![&self.from]; if let Some(j) = &self.join { v.push(&j.right); } v } }