Skip to main content

aegis_query/
ast.rs

1//! Aegis AST - Abstract Syntax Tree
2//!
3//! Internal representation of parsed SQL statements. Provides a clean,
4//! typed representation that is easier to analyze and optimize than
5//! the raw parser output.
6//!
7//! Key Features:
8//! - Typed expression trees
9//! - Statement variants for DML and DDL
10//! - Support for subqueries and CTEs
11//! - Extensible for custom Aegis features
12//!
13//! @version 0.1.0
14//! @author AutomataNexus Development Team
15
16use aegis_common::DataType;
17use serde::{Deserialize, Serialize};
18
19// =============================================================================
20// Statements
21// =============================================================================
22
23/// Top-level SQL statement.
24#[derive(Debug, Clone, PartialEq)]
25pub enum Statement {
26    Select(SelectStatement),
27    Insert(InsertStatement),
28    Update(UpdateStatement),
29    Delete(DeleteStatement),
30    CreateTable(CreateTableStatement),
31    DropTable(DropTableStatement),
32    AlterTable(AlterTableStatement),
33    CreateIndex(CreateIndexStatement),
34    DropIndex(DropIndexStatement),
35    SetOperation(SetOperationStatement),
36    Begin,
37    Commit,
38    Rollback,
39}
40
41// =============================================================================
42// Set Operations
43// =============================================================================
44
45/// Type of set operation.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum SetOperationType {
48    Union,
49    UnionAll,
50    Intersect,
51    Except,
52}
53
54/// A set operation combining two queries.
55#[derive(Debug, Clone, PartialEq)]
56pub struct SetOperationStatement {
57    pub op: SetOperationType,
58    pub left: Box<Statement>,
59    pub right: Box<Statement>,
60}
61
62// =============================================================================
63// SELECT Statement
64// =============================================================================
65
66/// A SELECT query.
67#[derive(Debug, Clone, PartialEq, Default)]
68pub struct SelectStatement {
69    pub distinct: bool,
70    pub columns: Vec<SelectColumn>,
71    pub from: Option<FromClause>,
72    pub where_clause: Option<Expression>,
73    pub group_by: Vec<Expression>,
74    pub having: Option<Expression>,
75    pub order_by: Vec<OrderByItem>,
76    pub limit: Option<u64>,
77    pub offset: Option<u64>,
78}
79
80/// A column in SELECT list.
81#[derive(Debug, Clone, PartialEq)]
82pub enum SelectColumn {
83    AllColumns,
84    TableAllColumns(String),
85    Expression {
86        expr: Expression,
87        alias: Option<String>,
88    },
89}
90
91/// FROM clause.
92#[derive(Debug, Clone, PartialEq)]
93pub struct FromClause {
94    pub source: TableReference,
95    pub joins: Vec<JoinClause>,
96}
97
98/// Reference to a table or subquery.
99#[derive(Debug, Clone, PartialEq)]
100pub enum TableReference {
101    Table {
102        name: String,
103        alias: Option<String>,
104    },
105    Subquery {
106        query: Box<SelectStatement>,
107        alias: String,
108    },
109}
110
111/// JOIN clause.
112#[derive(Debug, Clone, PartialEq)]
113pub struct JoinClause {
114    pub join_type: JoinType,
115    pub table: TableReference,
116    pub condition: Option<Expression>,
117}
118
119/// Type of JOIN.
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum JoinType {
122    Inner,
123    Left,
124    Right,
125    Full,
126    Cross,
127}
128
129/// ORDER BY item.
130#[derive(Debug, Clone, PartialEq)]
131pub struct OrderByItem {
132    pub expression: Expression,
133    pub ascending: bool,
134    pub nulls_first: Option<bool>,
135}
136
137// =============================================================================
138// INSERT Statement
139// =============================================================================
140
141/// An INSERT statement.
142#[derive(Debug, Clone, PartialEq)]
143pub struct InsertStatement {
144    pub table: String,
145    pub columns: Option<Vec<String>>,
146    pub source: InsertSource,
147}
148
149/// Source for INSERT data.
150#[derive(Debug, Clone, PartialEq)]
151pub enum InsertSource {
152    Values(Vec<Vec<Expression>>),
153    Query(Box<SelectStatement>),
154}
155
156// =============================================================================
157// UPDATE Statement
158// =============================================================================
159
160/// An UPDATE statement.
161#[derive(Debug, Clone, PartialEq)]
162pub struct UpdateStatement {
163    pub table: String,
164    pub assignments: Vec<Assignment>,
165    pub where_clause: Option<Expression>,
166}
167
168/// Column assignment.
169#[derive(Debug, Clone, PartialEq)]
170pub struct Assignment {
171    pub column: String,
172    pub value: Expression,
173}
174
175// =============================================================================
176// DELETE Statement
177// =============================================================================
178
179/// A DELETE statement.
180#[derive(Debug, Clone, PartialEq)]
181pub struct DeleteStatement {
182    pub table: String,
183    pub where_clause: Option<Expression>,
184}
185
186// =============================================================================
187// DDL Statements
188// =============================================================================
189
190/// CREATE TABLE statement.
191#[derive(Debug, Clone, PartialEq)]
192pub struct CreateTableStatement {
193    pub name: String,
194    pub columns: Vec<ColumnDefinition>,
195    pub constraints: Vec<TableConstraint>,
196    pub if_not_exists: bool,
197}
198
199/// Column definition.
200#[derive(Debug, Clone, PartialEq)]
201pub struct ColumnDefinition {
202    pub name: String,
203    pub data_type: DataType,
204    pub nullable: bool,
205    pub default: Option<Expression>,
206    pub constraints: Vec<ColumnConstraint>,
207}
208
209/// Column-level constraint.
210#[derive(Debug, Clone, PartialEq)]
211pub enum ColumnConstraint {
212    PrimaryKey,
213    Unique,
214    NotNull,
215    Check(Expression),
216    References { table: String, column: String },
217}
218
219/// Table-level constraint.
220#[derive(Debug, Clone, PartialEq)]
221pub enum TableConstraint {
222    PrimaryKey {
223        columns: Vec<String>,
224    },
225    Unique {
226        columns: Vec<String>,
227    },
228    ForeignKey {
229        columns: Vec<String>,
230        ref_table: String,
231        ref_columns: Vec<String>,
232    },
233    Check {
234        expression: Expression,
235    },
236}
237
238/// DROP TABLE statement.
239#[derive(Debug, Clone, PartialEq)]
240pub struct DropTableStatement {
241    pub name: String,
242    pub if_exists: bool,
243}
244
245/// ALTER TABLE statement.
246#[derive(Debug, Clone, PartialEq)]
247pub struct AlterTableStatement {
248    pub name: String,
249    pub operations: Vec<AlterTableOperation>,
250}
251
252/// ALTER TABLE operation.
253#[derive(Debug, Clone, PartialEq)]
254pub enum AlterTableOperation {
255    AddColumn(ColumnDefinition),
256    DropColumn {
257        name: String,
258        if_exists: bool,
259    },
260    RenameColumn {
261        old_name: String,
262        new_name: String,
263    },
264    AlterColumn {
265        name: String,
266        data_type: Option<DataType>,
267        set_not_null: Option<bool>,
268        set_default: Option<Option<Expression>>,
269    },
270    RenameTable {
271        new_name: String,
272    },
273    AddConstraint(TableConstraint),
274    DropConstraint {
275        name: String,
276    },
277}
278
279/// CREATE INDEX statement.
280#[derive(Debug, Clone, PartialEq)]
281pub struct CreateIndexStatement {
282    pub name: String,
283    pub table: String,
284    pub columns: Vec<String>,
285    pub unique: bool,
286    pub if_not_exists: bool,
287}
288
289/// DROP INDEX statement.
290#[derive(Debug, Clone, PartialEq)]
291pub struct DropIndexStatement {
292    pub name: String,
293    pub if_exists: bool,
294}
295
296// =============================================================================
297// Expressions
298// =============================================================================
299
300/// An expression in SQL.
301#[derive(Debug, Clone, PartialEq)]
302pub enum Expression {
303    Literal(Literal),
304    Column(ColumnRef),
305    BinaryOp {
306        left: Box<Expression>,
307        op: BinaryOperator,
308        right: Box<Expression>,
309    },
310    UnaryOp {
311        op: UnaryOperator,
312        expr: Box<Expression>,
313    },
314    Function {
315        name: String,
316        args: Vec<Expression>,
317        distinct: bool,
318    },
319    Case {
320        operand: Option<Box<Expression>>,
321        conditions: Vec<(Expression, Expression)>,
322        else_result: Option<Box<Expression>>,
323    },
324    Cast {
325        expr: Box<Expression>,
326        data_type: DataType,
327    },
328    InList {
329        expr: Box<Expression>,
330        list: Vec<Expression>,
331        negated: bool,
332    },
333    InSubquery {
334        expr: Box<Expression>,
335        subquery: Box<SelectStatement>,
336        negated: bool,
337    },
338    Between {
339        expr: Box<Expression>,
340        low: Box<Expression>,
341        high: Box<Expression>,
342        negated: bool,
343    },
344    Like {
345        expr: Box<Expression>,
346        pattern: Box<Expression>,
347        negated: bool,
348    },
349    IsNull {
350        expr: Box<Expression>,
351        negated: bool,
352    },
353    Exists {
354        subquery: Box<SelectStatement>,
355        negated: bool,
356    },
357    Subquery(Box<SelectStatement>),
358    Placeholder(usize),
359}
360
361/// Literal value.
362#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
363pub enum Literal {
364    Null,
365    Boolean(bool),
366    Integer(i64),
367    Float(f64),
368    String(String),
369}
370
371/// Column reference.
372#[derive(Debug, Clone, PartialEq)]
373pub struct ColumnRef {
374    pub table: Option<String>,
375    pub column: String,
376}
377
378/// Binary operators.
379#[derive(Debug, Clone, Copy, PartialEq, Eq)]
380pub enum BinaryOperator {
381    // Arithmetic
382    Add,
383    Subtract,
384    Multiply,
385    Divide,
386    Modulo,
387
388    // Comparison
389    Equal,
390    NotEqual,
391    LessThan,
392    LessThanOrEqual,
393    GreaterThan,
394    GreaterThanOrEqual,
395
396    // Logical
397    And,
398    Or,
399
400    // String
401    Concat,
402}
403
404/// Unary operators.
405#[derive(Debug, Clone, Copy, PartialEq, Eq)]
406pub enum UnaryOperator {
407    Not,
408    Negative,
409    Positive,
410}
411
412// =============================================================================
413// Utility Implementations
414// =============================================================================
415
416impl Expression {
417    /// Create a column reference expression.
418    pub fn column(name: &str) -> Self {
419        Expression::Column(ColumnRef {
420            table: None,
421            column: name.to_string(),
422        })
423    }
424
425    /// Create a qualified column reference.
426    pub fn qualified_column(table: &str, column: &str) -> Self {
427        Expression::Column(ColumnRef {
428            table: Some(table.to_string()),
429            column: column.to_string(),
430        })
431    }
432
433    /// Create an integer literal.
434    pub fn int(value: i64) -> Self {
435        Expression::Literal(Literal::Integer(value))
436    }
437
438    /// Create a string literal.
439    pub fn string(value: &str) -> Self {
440        Expression::Literal(Literal::String(value.to_string()))
441    }
442
443    /// Create a boolean literal.
444    pub fn boolean(value: bool) -> Self {
445        Expression::Literal(Literal::Boolean(value))
446    }
447
448    /// Create a NULL literal.
449    pub fn null() -> Self {
450        Expression::Literal(Literal::Null)
451    }
452}