Skip to main content

rustdb/
run.rs

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