Menu
Public repository / e176e1fd6e59c85c44fb813065b5f50a3c332126
AkurAI-Framework / crates/sql/src/ast.rs
Latest change 5a1781679346dc042a413c85c2ddfc034f219ae0 - feat(sql): lexer + parser for a SQL subset (AST) by Ólafur Búi Ólafsson
//! The SQL abstract syntax tree — the output of [`crate::parse`].
//!
//! This is a deliberately small subset (single-table `SELECT`, `INSERT`,
//! `CREATE TABLE`) sufficient to drive the storage engine later. It carries no
//! execution semantics; it is pure shape.
/// A single parsed SQL statement.
#[derive(Debug, Clone, PartialEq)]
pub enum Statement {
Select(SelectStmt),
Insert(InsertStmt),
CreateTable(CreateTableStmt),
}
/// `SELECT <cols|*> FROM <table> [WHERE <expr>] [ORDER BY <col> [ASC|DESC]] [LIMIT <n>]`.
#[derive(Debug, Clone, PartialEq)]
pub struct SelectStmt {
pub columns: Vec<SelectColumn>,
pub table: String,
pub where_clause: Option<Expr>,
pub order_by: Option<OrderBy>,
pub limit: Option<i64>,
}
/// A projected column in a `SELECT` list.
#[derive(Debug, Clone, PartialEq)]
pub enum SelectColumn {
/// `*` — all columns.
All,
/// A named column.
Named(String),
}
/// An `ORDER BY <column> [ASC|DESC]` clause.
#[derive(Debug, Clone, PartialEq)]
pub struct OrderBy {
pub column: String,
pub direction: Direction,
}
/// Sort direction. `ASC` is the default when none is written.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Direction {
Asc,
Desc,
}
/// `INSERT INTO <table> (<cols>) VALUES (<values>)`.
#[derive(Debug, Clone, PartialEq)]
pub struct InsertStmt {
pub table: String,
pub columns: Vec<String>,
pub values: Vec<Literal>,
}
/// `CREATE TABLE <table> (<col> <type> [NOT NULL], …)`.
#[derive(Debug, Clone, PartialEq)]
pub struct CreateTableStmt {
pub table: String,
pub columns: Vec<ColumnDef>,
}
/// One column definition in a `CREATE TABLE`.
#[derive(Debug, Clone, PartialEq)]
pub struct ColumnDef {
pub name: String,
pub ty: DataType,
pub not_null: bool,
}
/// A column's declared storage type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DataType {
Integer,
Text,
Real,
}
/// A `WHERE` expression tree. `AND` binds tighter than `OR`.
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
/// A literal value.
Literal(Literal),
/// A column reference.
Column(String),
/// `left <op> right`.
Comparison {
left: Box<Expr>,
op: CompareOp,
right: Box<Expr>,
},
/// `left AND right`.
And(Box<Expr>, Box<Expr>),
/// `left OR right`.
Or(Box<Expr>, Box<Expr>),
/// `NOT operand`.
Not(Box<Expr>),
}
/// A comparison operator inside a `WHERE` expression.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompareOp {
Eq,
NotEq,
Lt,
LtEq,
Gt,
GtEq,
}
/// A literal value: the leaves of expressions and `INSERT` value lists.
#[derive(Debug, Clone, PartialEq)]
pub enum Literal {
Null,
Int(i64),
Float(f64),
Str(String),
}