Files
ssw-mpc/crates/mpc-sql/src/ast.rs
T
admin 54781b3f83
ci / gate (push) Waiting to run
refactor: 项目改名 ssw-mpc,crate 统一到 mpc-* 前缀
- 项目与文档标题:nax-rs → ssw-mpc(尚数网-多方安全计算),二进制 nax → mpc
- 18 个 crate 及目录 nax-* → mpc-*,Rust 引用 nax_* → mpc_*
- 环境变量、C 符号、构建/部署脚本:NAX_* → MPC_*、libnax_ray.so → libmpc_ray.so
- 保留协议域分隔常量与 refs/nax 参考实现路径,维持 golden 向量与历史数据兼容
- 新增 [profile.dev] incremental=false
2026-11-05 15:06:12 +08:00

182 lines
4.4 KiB
Rust

//! 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<f64> {
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<String>,
pub name: String,
}
impl Column {
pub fn new(table: Option<String>, 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<Expr>,
right: Box<Expr>,
},
UnaryOp {
op: String,
operand: Box<Expr>,
},
InList {
expr: Box<Expr>,
values: Vec<Value>,
negated: bool,
},
Agg {
func: String,
arg: Option<Box<Expr>>,
},
}
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<String> = 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<String>,
}
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<String>,
}
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<SelectItem>,
pub from: TableRef,
pub join: Option<Join>,
pub where_: Option<Expr>,
pub group_by: Vec<Column>,
pub having: Option<Expr>,
pub order_by: Vec<OrderKey>,
pub limit: Option<usize>,
}
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
}
}