rustdb 0.2.3

SQL database (in development)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
use crate::*;
use Instruction::*;

/// Evaluation environment - stack of Values, references to DB and Query.
pub struct EvalEnv<'r> {
    pub stack: Vec<Value>,
    pub bp: usize, // "Base Pointer" - used to access local variables.
    pub db: DB,
    pub tr: &'r mut dyn Transaction,
    pub call_depth: usize,
}
impl<'r> EvalEnv<'r> {
    /// Construct a new EvalEnv.
    pub fn new(db: DB, tr: &'r mut dyn Transaction) -> Self {
        EvalEnv {
            stack: Vec::new(),
            bp: 0,
            db,
            tr,
            call_depth: 0,
        }
    }

    /// Allocate and initialise local variables.
    pub fn alloc_locals(&mut self, dt: &[DataType], param_count: usize) {
        for d in dt.iter().skip(param_count) {
            let v = Value::default(*d);
            self.stack.push(v);
        }
    }

    /// Execute list of instructions.
    pub fn go(&mut self, ilist: &[Instruction]) {
        let n = ilist.len();
        let mut ip = 0;
        while ip < n {
            let i = &ilist[ip];
            ip += 1;
            match i {
                PushConst(x) => self.stack.push((*x).clone()),
                PushValue(e) => {
                    let v = e.eval(self, &[]);
                    self.stack.push(v);
                }
                PushLocal(x) => self.push_local(*x),
                PopToLocal(x) => self.pop_to_local(*x),
                Jump(x) => ip = *x,
                JumpIfFalse(x, e) => {
                    if !e.eval(self, &[]) {
                        ip = *x;
                    }
                }
                Call(x) => self.call(x),
                Return => break,
                Throw => {
                    let s = self.pop_string();
                    panic!("{}", s);
                }
                Execute => self.execute(),
                DataOp(x) => self.exec_do(x),
                Select(cse) => self.select(cse),
                Set(cse) => self.set(cse),
                ForInit(for_id, cte) => self.for_init(*for_id, cte),
                ForNext(break_id, info) => {
                    if !self.for_next(info) {
                        ip = *break_id;
                    }
                }
                ForSortInit(for_id, cte) => self.for_sort_init(*for_id, cte),
                ForSortNext(break_id, info) => {
                    if !self.for_sort_next(info) {
                        ip = *break_id;
                    }
                }
                // Special push instructions ( optimisations )
                PushInt(e) => {
                    let v = e.eval(self, &[]);
                    self.stack.push(Value::Int(v));
                }
                PushFloat(e) => {
                    let v = e.eval(self, &[]);
                    self.stack.push(Value::Float(v));
                }
                PushBool(e) => {
                    let v = e.eval(self, &[]);
                    self.stack.push(Value::Bool(v));
                }
            }
        }
    } // end fn go

    /// Call a function.
    pub fn call(&mut self, r: &Function) {
        self.call_depth += 1;
        /*
            if let Some(n) = stacker::remaining_stack()
            {
              if n < 64 * 1024 { panic!("Stack less than 64k call depth={}", self.call_depth) }
            }
            else
        */
        if self.call_depth > 500 {
            panic!("Call depth limit of 500 reached");
        }
        let save_bp = self.bp;
        self.bp = self.stack.len() - r.param_count;
        self.alloc_locals(&r.local_typ, r.param_count);
        self.go(&r.ilist.borrow());
        let pop_count = r.local_typ.len();
        if pop_count > 0 {
            if r.return_type != NONE {
                if r.param_count == 0
                // function result already in correct position.
                {
                    self.discard(pop_count - 1);
                } else {
                    let result = self.stack[self.bp + r.param_count].clone();
                    self.discard(pop_count);
                    self.stack.push(result);
                }
            } else {
                self.discard(pop_count);
            }
        }
        self.bp = save_bp;
        self.call_depth -= 1;
    }

    /// Discard n items from stack.
    fn discard(&mut self, mut n: usize) {
        while n > 0 {
            self.stack.pop();
            n -= 1;
        }
    }

    /// Pop a value from the stack and assign it to a local varaiable.
    fn pop_to_local(&mut self, local: usize) {
        self.stack[self.bp + local] = self.stack.pop().unwrap();
    }

    /// Pop string from the stack.
    fn pop_string(&mut self) -> String {
        if let Value::String(s) = self.stack.pop().unwrap() {
            s.to_string()
        } else {
            panic!()
        }
    }

    /// Push clone of local variable onto the stack.
    fn push_local(&mut self, local: usize) {
        self.stack.push(self.stack[self.bp + local].clone());
    }

    /// Execute a ForInit instruction. Constructs For state and assigns it to local variable.
    fn for_init(&mut self, for_id: usize, cte: &CTableExpression) {
        let data_source = self.data_source(cte);
        let fs = util::new(ForState { data_source });
        self.stack[self.bp + for_id] = Value::For(fs);
    }

    /// Evaluate optional where expression.
    fn ok(&mut self, wher: &Option<CExpPtr<bool>>, data: &[u8]) -> bool {
        if let Some(w) = wher {
            w.eval(self, data)
        } else {
            true
        }
    }

    /// Execute a ForNext instruction. Fetches a record from underlying file that satisfies the where condition,
    /// evaluates the expressions and assigns the results to local variables.
    fn for_next(&mut self, info: &ForNextInfo) -> bool {
        loop {
            let next = if let Value::For(fs) = &self.stack[self.bp + info.for_id] {
                fs.borrow_mut().data_source.next()
            } else {
                panic!("Jump into FOR loop");
            };
            if let Some((pp, off)) = next {
                let p = pp.borrow();
                let data = &p.data[off..];
                // Eval and check WHERE condition, eval expressions and assign to locals.
                if self.ok(&info.wher, data) {
                    for (i, a) in info.assigns.iter().enumerate() {
                        let val = info.exps[i].eval(self, data);
                        self.assign_local(a, val);
                    }
                    return true;
                }
            } else {
                return false;
            }
        }
    }

    /// Execute ForSortInit instruction. Constructs sorted vector of rows.
    fn for_sort_init(&mut self, for_id: usize, cse: &CSelectExpression) {
        let rows = self.get_temp(cse);
        self.stack[self.bp + for_id] = Value::ForSort(util::new(ForSortState { ix: 0, rows }));
    }

    /// Execute ForSortNext instruction. Assigns locals from current row, moves to next row.
    fn for_sort_next(&mut self, info: &(usize, usize, Assigns)) -> bool {
        let (for_id, orderbylen, assigns) = info;
        if let Value::ForSort(fs) = &self.stack[self.bp + for_id] {
            let fs = fs.clone();
            let mut fs = fs.borrow_mut();
            if fs.ix == fs.rows.len() {
                false
            } else {
                fs.ix += 1;
                let row = &fs.rows[fs.ix - 1];
                for (cn, a) in assigns.iter().enumerate() {
                    let val = row[orderbylen + cn].clone();
                    self.assign_local(a, val);
                }
                true
            }
        } else {
            panic!("Jump into FOR loop");
        }
    }

    /// Execute SQL string.
    fn execute(&mut self) {
        let s = self.pop_string();
        self.db.run(&s, self.tr);
    }

    /// Execute a data operation (DO).
    fn exec_do(&mut self, dop: &DO) {
        match dop {
            DO::Insert(tp, cols, values) => self.insert(tp.clone(), cols, values),
            DO::Update(assigns, from, wher) => self.update(assigns, from, wher),
            DO::Delete(from, wher) => self.delete(from, wher),
            DO::CreateSchema(name) => sys::create_schema(&self.db, name),
            DO::CreateTable(ti) => sys::create_table(&self.db, ti),
            DO::CreateIndex(x) => sys::create_index(&self.db, x),
            DO::CreateFunction(name, source, alter) => {
                sys::create_function(&self.db, name, source.clone(), *alter)
            }
            DO::DropSchema(name) => self.drop_schema(name),
            DO::DropTable(name) => self.drop_table(name),
            DO::DropFunction(name) => self.drop_function(name),
            _ => panic!(),
        }
    }

    /// Get list of record ids for DELETE/UPDATE.
    fn get_id_list(&mut self, te: &CTableExpression, w: &Option<CExpPtr<bool>>) -> Vec<u64> {
        let mut idlist = Vec::new();

        for (pp, off) in self.data_source(te) {
            let p = pp.borrow();
            let data = &p.data[off..];
            if self.ok(w, data) {
                idlist.push(util::getu64(data, 0));
            }
        }
        idlist
    }

    /// Execute INSERT operation.
    fn insert(&mut self, t: TablePtr, cols: &[usize], src: &CTableExpression) {
        if let CTableExpression::Values(x) = src {
            self.insert_values(t, cols, x);
        } else {
            panic!();
        }
    }

    /// Execute a DELETE operation.
    fn delete(&mut self, from: &CTableExpression, w: &Option<CExpPtr<bool>>) {
        let idlist = self.get_id_list(from, w);
        let t = from.table();
        let mut oldrow = t.row();
        for id in idlist {
            // Load oldrow so that any codes are deleted.
            if let Some((pp, off)) = t.id_get(&self.db, id) {
                let p = pp.borrow();
                let data = &p.data[off..];
                oldrow.load(&self.db, data);
            } else {
                panic!()
            }
            t.remove(&self.db, &oldrow);
        }
    }

    /// Execute an UPDATE operation.
    fn update(
        &mut self,
        assigns: &[(usize, CExpPtr<Value>)],
        from: &CTableExpression,
        w: &Option<CExpPtr<bool>>,
    ) {
        let idlist = self.get_id_list(from, w);
        let t = from.table();
        let mut oldrow = t.row();
        for id in idlist {
            if let Some((pp, off)) = t.id_get(&self.db, id) {
                let mut newrow = {
                    let p = pp.borrow();
                    let data = &p.data[off..];
                    oldrow.load(&self.db, data);
                    let mut newrow = oldrow.clone();
                    for (col, exp) in assigns {
                        newrow.values[*col] = exp.eval(self, data);
                    }
                    newrow
                };
                // Would be nice to optimise this to minimise re-indexing.
                t.remove(&self.db, &oldrow);
                t.insert(&self.db, &mut newrow);
            }
        }
    }

    /// Get DataSource from CTableExpression.
    fn data_source(&mut self, te: &CTableExpression) -> DataSource {
        match te {
            CTableExpression::Base(t) => Box::new(t.scan(&self.db)),
            CTableExpression::IdGet(t, idexp) => {
                let id = idexp.eval(self, &[]);
                Box::new(t.scan_id(&self.db, id))
            }
            CTableExpression::IxGet(t, val, index) => {
                let mut keys = Vec::new();
                for v in val {
                    keys.push(v.eval(self, &[]));
                }
                Box::new(t.scan_keys(&self.db, keys, *index))
            }
            _ => panic!(),
        }
    }

    /// Execute a SELECT operation.
    fn select(&mut self, cse: &CSelectExpression) {
        if let Some(te) = &cse.from {
            let obl = cse.orderby.len();
            let mut temp = Vec::new(); // For sorting.
            for (pp, off) in self.data_source(te) {
                let p = pp.borrow();
                let data = &p.data[off..];
                if self.ok(&cse.wher, data) {
                    let mut values = Vec::new();
                    if obl > 0 {
                        // Push the sort keys.
                        for ce in &cse.orderby {
                            let val = ce.eval(self, data);
                            values.push(val);
                        }
                    }
                    for ce in &cse.exps {
                        let val = ce.eval(self, data);
                        values.push(val);
                    }
                    if obl > 0 {
                        // Save row for later sorting.
                        temp.push(values);
                    } else {
                        // Output directly.
                        self.tr.selected(&values);
                    }
                }
            }
            if obl > 0 {
                // Sort then output the rows.
                temp.sort_by(|a, b| table::row_compare(a, b, &cse.desc));
                for r in &temp {
                    self.tr.selected(&r[obl..]);
                }
            }
        } else {
            let mut values = Vec::new();
            for ce in &cse.exps {
                let val = ce.eval(self, &[]);
                values.push(val);
            }
            self.tr.selected(&values);
        }
    }

    /// Execute a SET operation.
    fn set(&mut self, cse: &CSelectExpression) {
        if let Some(te) = &cse.from {
            for (pp, off) in self.data_source(te) {
                let p = pp.borrow();
                let data = &p.data[off..];
                if self.ok(&cse.wher, data) {
                    for (i, ce) in cse.exps.iter().enumerate() {
                        let val = ce.eval(self, data);
                        self.assign_local(&cse.assigns[i], val);
                    }
                    break; // Only one row is used for SET.
                }
            }
        } else {
            for (i, ce) in cse.exps.iter().enumerate() {
                let val = ce.eval(self, &[]);
                self.assign_local(&cse.assigns[i], val);
            }
        }
    }

    /// Assign or append to a local variable.
    fn assign_local(&mut self, a: &(usize, AssignOp), val: Value) {
        let var = &mut self.stack[self.bp + a.0];
        match a.1 {
            AssignOp::Assign => {
                *var = val;
            }
            AssignOp::Append => {
                var.append(&val);
            }
        }
    }

    /// Insert evaluated values into a table.
    fn insert_values(&mut self, table: TablePtr, ci: &[usize], vals: &[Vec<CExpPtr<Value>>]) {
        let mut row = Row::new(table.info.clone());
        for r in vals {
            row.id = 0;
            for (i, ce) in r.iter().enumerate() {
                let val = ce.eval(self, &[]);
                let cn = ci[i];
                if cn == usize::MAX {
                    if let Value::Int(v) = val {
                        row.id = v;
                    }
                } else {
                    row.values[cn] = val;
                }
            }
            if row.id == 0 {
                row.id = table.alloc_id();
            } else {
                table.id_allocated(row.id);
            }
            self.db.lastid.set(row.id);
            table.insert(&self.db, &mut row);
        }
    }

    /// Get sorted temporary table.
    fn get_temp(&mut self, cse: &CSelectExpression) -> Vec<Vec<Value>> {
        if let Some(te) = &cse.from {
            let mut temp = Vec::new(); // For sorting.
            for (pp, off) in self.data_source(te) {
                let p = pp.borrow();
                let data = &p.data[off..];
                if self.ok(&cse.wher, data) {
                    let mut values = Vec::new();
                    for ce in &cse.orderby {
                        let val = ce.eval(self, data);
                        values.push(val);
                    }
                    for ce in &cse.exps {
                        let val = ce.eval(self, data);
                        values.push(val);
                    }
                    temp.push(values); // Save row for later sorting.
                }
            }
            // Sort the rows.
            temp.sort_by(|a, b| table::row_compare(a, b, &cse.desc));
            temp
        } else {
            panic!()
        }
    }

    fn drop_schema(&mut self, name: &str) {
        if let Some(sid) = sys::get_schema(&self.db, name) {
            let sql = "EXEC sys.DropSchema(".to_string() + &sid.to_string() + ")";
            self.db.run(&sql, self.tr);
            self.db.schemas.borrow_mut().remove(name);
            self.db.function_reset.set(true);
        } else {
            panic!("Drop Schema not found {}", name);
        }
    }

    fn drop_table(&mut self, name: &ObjRef) {
        if let Some(t) = sys::get_table(&self.db, name) {
            let sql = "EXEC sys.DropTable(".to_string() + &t.id.to_string() + ")";
            self.db.run(&sql, self.tr);
            self.db.tables.borrow_mut().remove(name);
            self.db.function_reset.set(true);
            t.free_pages(&self.db);
        } else {
            panic!("Drop Table not found {}", name.str());
        }
    }

    fn drop_function(&mut self, name: &ObjRef) {
        if let Some(fid) = sys::get_function_id(&self.db, name) {
            let sql = "DELETE FROM sys.Function WHERE Id = ".to_string() + &fid.to_string();
            self.db.run(&sql, self.tr);
            self.db.function_reset.set(true);
        } else {
            panic!("Drop Function not found {}", name.str());
        }
    }
} // impl EvalEnv