1#[derive(Debug, Clone, PartialEq)]
6pub enum ArithOp {
7 Add,
8 Sub,
9 Mul,
10 Div,
11 Mod,
12}
13
14#[derive(Debug, Clone, PartialEq)]
15pub enum Expr {
16 Literal(SqlValue),
17 Column(String),
18 BinaryOp { left: Box<Expr>, op: ArithOp, right: Box<Expr> },
19 UnaryMinus(Box<Expr>),
20 Case { whens: Vec<(WhereClause, Box<Expr>)>, else_expr: Option<Box<Expr>> },
21 DateAdd { date: Box<Expr>, days: Box<Expr> },
22 DateDiff { left: Box<Expr>, right: Box<Expr> },
23 CurrentDate,
24 CurrentTimestamp,
25 Aggregate { func: AggFunc, arg: String, arg_expr: Option<Box<Expr>> },
26}
27
28impl Expr {
29 pub fn as_column(&self) -> Option<&str> {
30 if let Expr::Column(name) = self { Some(name) } else { None }
31 }
32
33 pub fn display_name(&self) -> String {
34 match self {
35 Expr::Literal(SqlValue::Int(n)) => n.to_string(),
36 Expr::Literal(SqlValue::Float(f)) => f.to_string(),
37 Expr::Literal(SqlValue::String(s)) => format!("'{}'", s),
38 Expr::Literal(SqlValue::Null) => "NULL".to_string(),
39 Expr::Literal(SqlValue::List(_)) => "list".to_string(),
40 Expr::Column(name) => name.clone(),
41 Expr::BinaryOp { left, op, right } => {
42 let op_str = match op {
43 ArithOp::Add => "+",
44 ArithOp::Sub => "-",
45 ArithOp::Mul => "*",
46 ArithOp::Div => "/",
47 ArithOp::Mod => "%",
48 };
49 format!("{} {} {}", left.display_name(), op_str, right.display_name())
50 }
51 Expr::UnaryMinus(inner) => format!("-{}", inner.display_name()),
52 Expr::Case { .. } => "CASE".to_string(),
53 Expr::DateAdd { date, days } => format!("DATE_ADD({}, {})", date.display_name(), days.display_name()),
54 Expr::DateDiff { left, right } => format!("DATEDIFF({}, {})", left.display_name(), right.display_name()),
55 Expr::CurrentDate => "CURRENT_DATE".to_string(),
56 Expr::CurrentTimestamp => "CURRENT_TIMESTAMP".to_string(),
57 Expr::Aggregate { func, arg, .. } => {
58 let func_name = match func {
59 AggFunc::Count => "COUNT",
60 AggFunc::Sum => "SUM",
61 AggFunc::Avg => "AVG",
62 AggFunc::Min => "MIN",
63 AggFunc::Max => "MAX",
64 };
65 format!("{}({})", func_name, arg)
66 }
67 }
68 }
69
70 pub fn contains_aggregate(&self) -> bool {
71 match self {
72 Expr::Aggregate { .. } => true,
73 Expr::BinaryOp { left, right, .. } => {
74 left.contains_aggregate() || right.contains_aggregate()
75 }
76 Expr::UnaryMinus(inner) => inner.contains_aggregate(),
77 Expr::Case { whens, else_expr } => {
78 whens.iter().any(|(_, e)| e.contains_aggregate())
79 || else_expr.as_ref().map_or(false, |e| e.contains_aggregate())
80 }
81 _ => false,
82 }
83 }
84}
85
86#[derive(Debug, Clone, PartialEq)]
87pub struct OrderSpec {
88 pub column: String,
89 pub expr: Option<Expr>,
90 pub descending: bool,
91}
92
93#[derive(Debug, Clone, PartialEq)]
94pub enum CmpOp {
95 Eq,
96 Ne,
97 Lt,
98 Gt,
99 Le,
100 Ge,
101 Like,
102 NotLike,
103 In,
104 IsNull,
105 IsNotNull,
106}
107
108#[derive(Debug, Clone, PartialEq)]
109pub enum BoolOpKind {
110 And,
111 Or,
112}
113
114#[derive(Debug, Clone, PartialEq)]
115pub struct Comparison {
116 pub column: String,
117 pub op: CmpOp,
118 pub value: Option<SqlValue>,
119 pub left_expr: Option<Expr>,
120 pub right_expr: Option<Expr>,
121}
122
123#[derive(Debug, Clone, PartialEq)]
124pub struct BoolOp {
125 pub op: BoolOpKind,
126 pub left: Box<WhereClause>,
127 pub right: Box<WhereClause>,
128}
129
130#[derive(Debug, Clone, PartialEq)]
131pub enum WhereClause {
132 Comparison(Comparison),
133 BoolOp(BoolOp),
134}
135
136#[derive(Debug, Clone, PartialEq)]
137pub enum SqlValue {
138 String(String),
139 Int(i64),
140 Float(f64),
141 Null,
142 List(Vec<SqlValue>),
143}
144
145#[derive(Debug, Clone, PartialEq)]
146pub enum JoinType {
147 Inner,
148 Left,
149}
150
151#[derive(Debug, Clone, PartialEq)]
152pub struct JoinClause {
153 pub join_type: JoinType,
154 pub table: String,
155 pub alias: Option<String>,
156 pub condition: WhereClause,
157}
158
159#[derive(Debug, Clone, PartialEq)]
160pub enum AggFunc {
161 Count,
162 Sum,
163 Avg,
164 Min,
165 Max,
166}
167
168#[derive(Debug, Clone, PartialEq)]
169pub enum SelectExpr {
170 Column(String),
171 Aggregate { func: AggFunc, arg: String, arg_expr: Option<Expr>, alias: Option<String> },
172 Expr { expr: Expr, alias: Option<String> },
173}
174
175impl SelectExpr {
176 pub fn output_name(&self) -> String {
177 match self {
178 SelectExpr::Column(name) => name.clone(),
179 SelectExpr::Aggregate { func, arg, alias, .. } => {
180 if let Some(a) = alias {
181 a.clone()
182 } else {
183 let func_name = match func {
184 AggFunc::Count => "COUNT",
185 AggFunc::Sum => "SUM",
186 AggFunc::Avg => "AVG",
187 AggFunc::Min => "MIN",
188 AggFunc::Max => "MAX",
189 };
190 format!("{}({})", func_name, arg)
191 }
192 }
193 SelectExpr::Expr { expr, alias } => {
194 alias.clone().unwrap_or_else(|| expr.display_name())
195 }
196 }
197 }
198
199 pub fn is_aggregate(&self) -> bool {
200 match self {
201 SelectExpr::Aggregate { .. } => true,
202 SelectExpr::Expr { expr, .. } => expr.contains_aggregate(),
203 _ => false,
204 }
205 }
206}
207
208#[derive(Debug, Clone, PartialEq)]
209pub struct SelectQuery {
210 pub columns: ColumnList,
211 pub table: String,
212 pub table_alias: Option<String>,
213 pub subquery: Option<Box<SelectQuery>>,
214 pub joins: Vec<JoinClause>,
215 pub where_clause: Option<WhereClause>,
216 pub group_by: Option<Vec<String>>,
217 pub having: Option<WhereClause>,
218 pub order_by: Option<Vec<OrderSpec>>,
219 pub limit: Option<i64>,
220}
221
222#[derive(Debug, Clone, PartialEq)]
223pub enum ColumnList {
224 All,
225 Named(Vec<SelectExpr>),
226}
227
228#[derive(Debug, Clone, PartialEq)]
229pub struct InsertQuery {
230 pub table: String,
231 pub columns: Vec<String>,
232 pub values: Vec<SqlValue>,
233}
234
235#[derive(Debug, Clone, PartialEq)]
236pub struct UpdateQuery {
237 pub table: String,
238 pub assignments: Vec<(String, SqlValue)>,
239 pub where_clause: Option<WhereClause>,
240}
241
242#[derive(Debug, Clone, PartialEq)]
243pub struct DeleteQuery {
244 pub table: String,
245 pub where_clause: Option<WhereClause>,
246}
247
248#[derive(Debug, Clone, PartialEq)]
249pub struct AlterRenameFieldQuery {
250 pub table: String,
251 pub old_name: String,
252 pub new_name: String,
253}
254
255#[derive(Debug, Clone, PartialEq)]
256pub struct AlterDropFieldQuery {
257 pub table: String,
258 pub field_name: String,
259}
260
261#[derive(Debug, Clone, PartialEq)]
262pub struct AlterMergeFieldsQuery {
263 pub table: String,
264 pub sources: Vec<String>,
265 pub into: String,
266}
267
268#[derive(Debug, Clone, PartialEq)]
269pub struct CreateViewQuery {
270 pub view_name: String,
271 pub columns: Option<Vec<String>>,
272 pub query: Box<SelectQuery>,
273}
274
275#[derive(Debug, Clone, PartialEq)]
276pub struct DropViewQuery {
277 pub view_name: String,
278}
279
280#[derive(Debug, Clone, PartialEq)]
281pub enum Statement {
282 Select(SelectQuery),
283 Insert(InsertQuery),
284 Update(UpdateQuery),
285 Delete(DeleteQuery),
286 AlterRename(AlterRenameFieldQuery),
287 AlterDrop(AlterDropFieldQuery),
288 AlterMerge(AlterMergeFieldsQuery),
289 CreateView(CreateViewQuery),
290 DropView(DropViewQuery),
291}
292
293impl Statement {
294 pub fn table_name(&self) -> &str {
295 match self {
296 Statement::Select(q) => &q.table,
297 Statement::Insert(q) => &q.table,
298 Statement::Update(q) => &q.table,
299 Statement::Delete(q) => &q.table,
300 Statement::AlterRename(q) => &q.table,
301 Statement::AlterDrop(q) => &q.table,
302 Statement::AlterMerge(q) => &q.table,
303 Statement::CreateView(q) => &q.view_name,
304 Statement::DropView(q) => &q.view_name,
305 }
306 }
307}
308
309pub fn where_clause_to_sql(clause: &WhereClause) -> String {
310 match clause {
311 WhereClause::BoolOp(bop) => {
312 let left = where_clause_to_sql(&bop.left);
313 let right = where_clause_to_sql(&bop.right);
314 let op = match bop.op {
315 BoolOpKind::And => "AND",
316 BoolOpKind::Or => "OR",
317 };
318 format!("{} {} {}", left, op, right)
319 }
320 WhereClause::Comparison(cmp) => {
321 let op_str = match cmp.op {
322 CmpOp::Eq => "=",
323 CmpOp::Ne => "!=",
324 CmpOp::Lt => "<",
325 CmpOp::Gt => ">",
326 CmpOp::Le => "<=",
327 CmpOp::Ge => ">=",
328 CmpOp::Like => "LIKE",
329 CmpOp::NotLike => "NOT LIKE",
330 CmpOp::In => "IN",
331 CmpOp::IsNull => "IS NULL",
332 CmpOp::IsNotNull => "IS NOT NULL",
333 };
334 if matches!(cmp.op, CmpOp::IsNull | CmpOp::IsNotNull) {
335 if let Some(ref expr) = cmp.left_expr {
336 return format!("{} {}", expr.display_name(), op_str);
337 }
338 return format!("{} {}", cmp.column, op_str);
339 }
340 if let (Some(ref left), Some(ref right)) = (&cmp.left_expr, &cmp.right_expr) {
341 return format!("{} {} {}", left.display_name(), op_str, right.display_name());
342 }
343 match &cmp.value {
344 Some(SqlValue::String(s)) => format!("{} {} '{}'", cmp.column, op_str, s),
345 Some(SqlValue::Int(n)) => format!("{} {} {}", cmp.column, op_str, n),
346 Some(SqlValue::Float(f)) => format!("{} {} {}", cmp.column, op_str, f),
347 Some(SqlValue::Null) => format!("{} {} NULL", cmp.column, op_str),
348 Some(SqlValue::List(items)) => {
349 let vals: Vec<String> = items.iter().map(|v| match v {
350 SqlValue::String(s) => format!("'{}'", s),
351 SqlValue::Int(n) => n.to_string(),
352 SqlValue::Float(f) => f.to_string(),
353 _ => "NULL".to_string(),
354 }).collect();
355 format!("{} {} ({})", cmp.column, op_str, vals.join(", "))
356 }
357 None => format!("{} {}", cmp.column, op_str),
358 }
359 }
360 }
361}