rustdb/
run.rs

1use crate::{
2    panic, Assigns, Block, Cell, ColInfo, DataType, EvalEnv, Expr, IndexInfo, ObjRef, PagePtr, Rc,
3    RefCell, Table, Value,
4};
5
6/// Instruction.
7#[non_exhaustive]
8pub enum Instruction {
9    /// Push constant.
10    PushConst(Value),
11    /// Push expression.
12    PushValue(CExpPtr<Value>),
13    /// Push local variable.
14    PushLocal(usize),
15    /// Assign local variable.
16    PopToLocal(usize),
17    /// Jump.
18    Jump(usize),
19    /// Jump if false.
20    JumpIfFalse(usize, CExpPtr<bool>),
21    /// Call
22    Call(Rc<Function>),
23    /// Return from function.
24    Return,
25    /// Throw error.
26    Throw,
27    /// Execute string.
28    Execute,
29    /// Initialise FOR statement.
30    ForInit(usize, Box<CTableExpression>),
31    /// Next iteration of FOR statement.
32    ForNext(usize, Box<ForNextInfo>),
33    /// Initialise FOR statement ( sorted case ).
34    ForSortInit(usize, Box<CFromExpression>),
35    /// Next iteration of FOR statement ( sorted case ).
36    ForSortNext(usize, Box<(usize, usize, Assigns)>),
37    /// Data operation.
38    DataOp(Box<DO>),
39    /// SELECT expression.
40    Select(Box<CFromExpression>),
41    /// Set local variables from table.
42    Set(Box<CFromExpression>),
43    // Special push instructions ( optimisations )
44    /// Push Integer expression.
45    PushInt(CExpPtr<i64>),
46    /// Push Float expression.
47    PushFloat(CExpPtr<f64>),
48    /// Push bool expression.
49    PushBool(CExpPtr<bool>),
50    // More optimisations.
51    /// Assign a local variable.
52    AssignLocal(usize, CExpPtr<Value>),
53    /// Append to a local variable.
54    AppendLocal(usize, CExpPtr<Value>),
55    /// Increment (+=) a local variable.
56    IncLocal(usize, CExpPtr<Value>),
57    /// Decrement (-=) a local variable.
58    DecLocal(usize, CExpPtr<Value>),
59}
60
61/// Compiled Function.
62#[non_exhaustive]
63pub struct Function {
64    /// Number of parameters.
65    pub param_count: usize,
66    /// Function return type.
67    pub return_type: DataType,
68    /// Types of local parameters/variables.
69    pub local_typ: Vec<DataType>,
70    /// Source SQL.
71    pub source: Rc<String>,
72    /// List of instructions.
73    pub ilist: RefCell<Vec<Instruction>>, // Valid when compiled is true.
74    /// Has function been compiled.
75    pub compiled: Cell<bool>,
76}
77
78/// Compiled expression which yields type T when evaluated.
79pub trait CExp<T> {
80    /// Evaluate the compiled expression.
81    fn eval(&self, ee: &mut EvalEnv, data: &[u8]) -> T;
82}
83
84/// Pointer to [CExp].
85pub type CExpPtr<T> = Box<dyn CExp<T>>;
86
87/// Function that compiles a builtin function call.
88#[derive(Clone, Copy)]
89#[non_exhaustive]
90pub enum CompileFunc {
91    /// Value result.
92    Value(fn(&Block, &mut [Expr]) -> CExpPtr<Value>),
93    /// Int result.
94    Int(fn(&Block, &mut [Expr]) -> CExpPtr<i64>),
95    /// Float result.
96    Float(fn(&Block, &mut [Expr]) -> CExpPtr<f64>),
97}
98
99/// Iterator that yields references to page data.
100pub type DataSource = Box<dyn Iterator<Item = (PagePtr, usize)>>;
101
102/// State for FOR loop (non-sorted case).
103#[non_exhaustive]
104pub struct ForState {
105    /// Data source.
106    pub data_source: DataSource,
107}
108impl std::fmt::Debug for ForState {
109    fn fmt(&self, _f: &mut std::fmt::Formatter) -> std::fmt::Result {
110        Ok(())
111    }
112}
113
114/// State for FOR loop (sorted case).
115#[non_exhaustive]
116pub struct ForSortState {
117    /// Currrent index into rows.
118    pub ix: usize,
119    /// Rows.
120    pub rows: Vec<Vec<Value>>,
121}
122impl std::fmt::Debug for ForSortState {
123    fn fmt(&self, _f: &mut std::fmt::Formatter) -> std::fmt::Result {
124        Ok(())
125    }
126}
127
128/// Info for ForNext Inst.
129#[non_exhaustive]
130pub struct ForNextInfo {
131    /// FOR id.
132    pub for_id: usize,
133    /// Assigns.
134    pub assigns: Assigns,
135    /// Expressions.
136    pub exps: Vec<CExpPtr<Value>>,
137    /// WHERE expression.
138    pub wher: Option<CExpPtr<bool>>,
139}
140
141/// Compiled Table Expression.
142#[non_exhaustive]
143pub enum CTableExpression {
144    /// Base table.
145    Base(Rc<Table>),
146    /// Row identified by Id.
147    IdGet(Rc<Table>, CExpPtr<i64>),
148    /// Indexed rows.
149    IxGet(Rc<Table>, Vec<CExpPtr<Value>>, usize),
150    /// VALUE expressions.
151    Values(Vec<Vec<CExpPtr<Value>>>),
152}
153
154impl CTableExpression {
155    /// Get underlying table.
156    pub fn table(&self) -> Rc<Table> {
157        match self {
158            CTableExpression::Base(t) => t.clone(),
159            CTableExpression::IdGet(t, _) => t.clone(),
160            CTableExpression::IxGet(t, _, _) => t.clone(),
161            _ => panic!(),
162        }
163    }
164}
165
166/// Compiled From Expression.
167#[non_exhaustive]
168pub struct CFromExpression {
169    /// Column names.
170    pub colnames: Vec<String>,
171    /// Assignments ( left hand side ).
172    pub assigns: Assigns,
173    /// Expressions.
174    pub exps: Vec<CExpPtr<Value>>,
175    /// FROM expression.
176    pub from: Option<CTableExpression>,
177    /// WHERE expression.
178    pub wher: Option<CExpPtr<bool>>,
179    /// ORDER BY expressions.
180    pub orderby: Vec<CExpPtr<Value>>,
181    /// DESC bits.
182    pub desc: Vec<bool>,
183}
184
185/// Database Operation
186#[non_exhaustive]
187pub enum DO {
188    /// Create Schema.
189    CreateSchema(String),
190    /// Create Table.
191    CreateTable(ColInfo),
192    /// Create Index.
193    CreateIndex(IndexInfo),
194    /// Create Function.
195    CreateFunction(ObjRef, Rc<String>, bool),
196    /// Alter Table.
197    AlterTable(ObjRef, Vec<AlterCol>),
198    /// Drop Schema.
199    DropSchema(String),
200    /// Drop Table.
201    DropTable(ObjRef),
202    /// Drop Index.
203    DropIndex(ObjRef, String),
204    /// Drop Function.
205    DropFunction(ObjRef),
206    /// Insert into Table.
207    Insert(Rc<Table>, Vec<usize>, CTableExpression),
208    /// Update Table rows.
209    Update(
210        Vec<(usize, CExpPtr<Value>)>,
211        CTableExpression,
212        Option<CExpPtr<bool>>,
213    ),
214    /// Delete Table rows.
215    Delete(CTableExpression, Option<CExpPtr<bool>>),
216}
217
218/// Actions for altering columns of a table.
219#[non_exhaustive]
220pub enum AlterCol {
221    /// Add column.
222    Add(String, DataType),
223    /// Drop column.
224    Drop(String),
225    /// Modify column.
226    Modify(String, DataType),
227}