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    Begin,
36    Commit,
37    Rollback,
38}
39
40// =============================================================================
41// SELECT Statement
42// =============================================================================
43
44/// A SELECT query.
45#[derive(Debug, Clone, PartialEq)]
46#[derive(Default)]
47pub struct SelectStatement {
48    pub distinct: bool,
49    pub columns: Vec<SelectColumn>,
50    pub from: Option<FromClause>,
51    pub where_clause: Option<Expression>,
52    pub group_by: Vec<Expression>,
53    pub having: Option<Expression>,
54    pub order_by: Vec<OrderByItem>,
55    pub limit: Option<u64>,
56    pub offset: Option<u64>,
57}
58
59
60/// A column in SELECT list.
61#[derive(Debug, Clone, PartialEq)]
62pub enum SelectColumn {
63    AllColumns,
64    TableAllColumns(String),
65    Expression { expr: Expression, alias: Option<String> },
66}
67
68/// FROM clause.
69#[derive(Debug, Clone, PartialEq)]
70pub struct FromClause {
71    pub source: TableReference,
72    pub joins: Vec<JoinClause>,
73}
74
75/// Reference to a table or subquery.
76#[derive(Debug, Clone, PartialEq)]
77pub enum TableReference {
78    Table { name: String, alias: Option<String> },
79    Subquery { query: Box<SelectStatement>, alias: String },
80}
81
82/// JOIN clause.
83#[derive(Debug, Clone, PartialEq)]
84pub struct JoinClause {
85    pub join_type: JoinType,
86    pub table: TableReference,
87    pub condition: Option<Expression>,
88}
89
90/// Type of JOIN.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum JoinType {
93    Inner,
94    Left,
95    Right,
96    Full,
97    Cross,
98}
99
100/// ORDER BY item.
101#[derive(Debug, Clone, PartialEq)]
102pub struct OrderByItem {
103    pub expression: Expression,
104    pub ascending: bool,
105    pub nulls_first: Option<bool>,
106}
107
108// =============================================================================
109// INSERT Statement
110// =============================================================================
111
112/// An INSERT statement.
113#[derive(Debug, Clone, PartialEq)]
114pub struct InsertStatement {
115    pub table: String,
116    pub columns: Option<Vec<String>>,
117    pub source: InsertSource,
118}
119
120/// Source for INSERT data.
121#[derive(Debug, Clone, PartialEq)]
122pub enum InsertSource {
123    Values(Vec<Vec<Expression>>),
124    Query(Box<SelectStatement>),
125}
126
127// =============================================================================
128// UPDATE Statement
129// =============================================================================
130
131/// An UPDATE statement.
132#[derive(Debug, Clone, PartialEq)]
133pub struct UpdateStatement {
134    pub table: String,
135    pub assignments: Vec<Assignment>,
136    pub where_clause: Option<Expression>,
137}
138
139/// Column assignment.
140#[derive(Debug, Clone, PartialEq)]
141pub struct Assignment {
142    pub column: String,
143    pub value: Expression,
144}
145
146// =============================================================================
147// DELETE Statement
148// =============================================================================
149
150/// A DELETE statement.
151#[derive(Debug, Clone, PartialEq)]
152pub struct DeleteStatement {
153    pub table: String,
154    pub where_clause: Option<Expression>,
155}
156
157// =============================================================================
158// DDL Statements
159// =============================================================================
160
161/// CREATE TABLE statement.
162#[derive(Debug, Clone, PartialEq)]
163pub struct CreateTableStatement {
164    pub name: String,
165    pub columns: Vec<ColumnDefinition>,
166    pub constraints: Vec<TableConstraint>,
167    pub if_not_exists: bool,
168}
169
170/// Column definition.
171#[derive(Debug, Clone, PartialEq)]
172pub struct ColumnDefinition {
173    pub name: String,
174    pub data_type: DataType,
175    pub nullable: bool,
176    pub default: Option<Expression>,
177    pub constraints: Vec<ColumnConstraint>,
178}
179
180/// Column-level constraint.
181#[derive(Debug, Clone, PartialEq)]
182pub enum ColumnConstraint {
183    PrimaryKey,
184    Unique,
185    NotNull,
186    Check(Expression),
187    References { table: String, column: String },
188}
189
190/// Table-level constraint.
191#[derive(Debug, Clone, PartialEq)]
192pub enum TableConstraint {
193    PrimaryKey { columns: Vec<String> },
194    Unique { columns: Vec<String> },
195    ForeignKey {
196        columns: Vec<String>,
197        ref_table: String,
198        ref_columns: Vec<String>,
199    },
200    Check { expression: Expression },
201}
202
203/// DROP TABLE statement.
204#[derive(Debug, Clone, PartialEq)]
205pub struct DropTableStatement {
206    pub name: String,
207    pub if_exists: bool,
208}
209
210/// ALTER TABLE statement.
211#[derive(Debug, Clone, PartialEq)]
212pub struct AlterTableStatement {
213    pub name: String,
214    pub operations: Vec<AlterTableOperation>,
215}
216
217/// ALTER TABLE operation.
218#[derive(Debug, Clone, PartialEq)]
219pub enum AlterTableOperation {
220    AddColumn(ColumnDefinition),
221    DropColumn { name: String, if_exists: bool },
222    RenameColumn { old_name: String, new_name: String },
223    AlterColumn { name: String, data_type: Option<DataType>, set_not_null: Option<bool>, set_default: Option<Option<Expression>> },
224    RenameTable { new_name: String },
225    AddConstraint(TableConstraint),
226    DropConstraint { name: String },
227}
228
229/// CREATE INDEX statement.
230#[derive(Debug, Clone, PartialEq)]
231pub struct CreateIndexStatement {
232    pub name: String,
233    pub table: String,
234    pub columns: Vec<String>,
235    pub unique: bool,
236    pub if_not_exists: bool,
237}
238
239/// DROP INDEX statement.
240#[derive(Debug, Clone, PartialEq)]
241pub struct DropIndexStatement {
242    pub name: String,
243    pub if_exists: bool,
244}
245
246// =============================================================================
247// Expressions
248// =============================================================================
249
250/// An expression in SQL.
251#[derive(Debug, Clone, PartialEq)]
252pub enum Expression {
253    Literal(Literal),
254    Column(ColumnRef),
255    BinaryOp {
256        left: Box<Expression>,
257        op: BinaryOperator,
258        right: Box<Expression>,
259    },
260    UnaryOp {
261        op: UnaryOperator,
262        expr: Box<Expression>,
263    },
264    Function {
265        name: String,
266        args: Vec<Expression>,
267        distinct: bool,
268    },
269    Case {
270        operand: Option<Box<Expression>>,
271        conditions: Vec<(Expression, Expression)>,
272        else_result: Option<Box<Expression>>,
273    },
274    Cast {
275        expr: Box<Expression>,
276        data_type: DataType,
277    },
278    InList {
279        expr: Box<Expression>,
280        list: Vec<Expression>,
281        negated: bool,
282    },
283    InSubquery {
284        expr: Box<Expression>,
285        subquery: Box<SelectStatement>,
286        negated: bool,
287    },
288    Between {
289        expr: Box<Expression>,
290        low: Box<Expression>,
291        high: Box<Expression>,
292        negated: bool,
293    },
294    Like {
295        expr: Box<Expression>,
296        pattern: Box<Expression>,
297        negated: bool,
298    },
299    IsNull {
300        expr: Box<Expression>,
301        negated: bool,
302    },
303    Exists {
304        subquery: Box<SelectStatement>,
305        negated: bool,
306    },
307    Subquery(Box<SelectStatement>),
308    Placeholder(usize),
309}
310
311/// Literal value.
312#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
313pub enum Literal {
314    Null,
315    Boolean(bool),
316    Integer(i64),
317    Float(f64),
318    String(String),
319}
320
321/// Column reference.
322#[derive(Debug, Clone, PartialEq)]
323pub struct ColumnRef {
324    pub table: Option<String>,
325    pub column: String,
326}
327
328/// Binary operators.
329#[derive(Debug, Clone, Copy, PartialEq, Eq)]
330pub enum BinaryOperator {
331    // Arithmetic
332    Add,
333    Subtract,
334    Multiply,
335    Divide,
336    Modulo,
337
338    // Comparison
339    Equal,
340    NotEqual,
341    LessThan,
342    LessThanOrEqual,
343    GreaterThan,
344    GreaterThanOrEqual,
345
346    // Logical
347    And,
348    Or,
349
350    // String
351    Concat,
352}
353
354/// Unary operators.
355#[derive(Debug, Clone, Copy, PartialEq, Eq)]
356pub enum UnaryOperator {
357    Not,
358    Negative,
359    Positive,
360}
361
362// =============================================================================
363// Utility Implementations
364// =============================================================================
365
366impl Expression {
367    /// Create a column reference expression.
368    pub fn column(name: &str) -> Self {
369        Expression::Column(ColumnRef {
370            table: None,
371            column: name.to_string(),
372        })
373    }
374
375    /// Create a qualified column reference.
376    pub fn qualified_column(table: &str, column: &str) -> Self {
377        Expression::Column(ColumnRef {
378            table: Some(table.to_string()),
379            column: column.to_string(),
380        })
381    }
382
383    /// Create an integer literal.
384    pub fn int(value: i64) -> Self {
385        Expression::Literal(Literal::Integer(value))
386    }
387
388    /// Create a string literal.
389    pub fn string(value: &str) -> Self {
390        Expression::Literal(Literal::String(value.to_string()))
391    }
392
393    /// Create a boolean literal.
394    pub fn boolean(value: bool) -> Self {
395        Expression::Literal(Literal::Boolean(value))
396    }
397
398    /// Create a NULL literal.
399    pub fn null() -> Self {
400        Expression::Literal(Literal::Null)
401    }
402}