matdb 0.1.0

An experimental embedded SQL-like DBMS
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
use std::collections::BTreeMap;

use anyhow::{anyhow, bail, Result};

use crate::{
    ast::{BinOp, Column, Expr, InsertStatement, Statement},
    catalog::Index,
    eval::Context,
    executor::execute_plan_next,
    kv::RangeIterKV,
    plan::{optimize_delete, optimize_select, optimize_update},
    value::Type,
    Db, Value,
};

pub fn run_program(
    db: &mut Db,
    program: &[Statement],
    bindings: Vec<Value>,
) -> Result<Option<(Vec<String>, Vec<Vec<Value>>)>> {
    let mut last_expr = None;

    for stmnt in program {
        match stmnt {
            Statement::CreateTable(body) => {
                let mut body = body.clone();

                if db.table_to_kv_id(db.this_tx_id, &body.name)?.is_some() {
                    bail!("table {} already exists", body.name)
                }

                if body.readonly {
                    bail!("READ ONLY clause of CREATE TABLE is for internal use only")
                }

                if !body.referenced_by.is_empty() {
                    bail!("REFERENCED BY clause of CREATE TABLE is for internal use only")
                }

                for fk in &body.foreign_keys {
                    if db.table_to_kv_id(db.this_tx_id, &fk.rhs_table)?.is_none() {
                        bail!(
                            "table {} in foreign key constraint doesn't exist",
                            fk.rhs_table
                        )
                    }

                    let rhs_schema = db.get_table_schema(db.this_tx_id, &fk.rhs_table)?;
                    if rhs_schema
                        .indexes
                        .iter()
                        .find(|i| i.exprs == fk.rhs_exprs && i.unique)
                        .is_none()
                        && rhs_schema.primary_key != fk.rhs_exprs
                    {
                        bail!(
                            "table {} does not have index required for foreign key constraint",
                            fk.rhs_table
                        )
                    }

                    if body
                        .indexes
                        .iter()
                        .find(|i| i.exprs == fk.lhs_exprs)
                        .is_none()
                        && body.primary_key != fk.lhs_exprs
                    {
                        body.indexes.push(Index {
                            exprs: fk.lhs_exprs.clone(),
                            unique: false,
                        })
                    }
                }

                db.create_table(&body.name, body.clone())?;

                last_expr = None;
            }
            Statement::DropTable(name) => {
                let schema = db.get_table_schema(db.this_tx_id, &name)?;

                if schema.readonly {
                    bail!("table {name} is read-only and cannot be droped")
                }

                if !schema.referenced_by.is_empty() {
                    bail!("table is referenced by another table in a foreign key constraint")
                }

                db.delete_table(&name)?;

                last_expr = None;
            }
            Statement::Insert(body) => {
                do_insert(db, body, bindings.clone())?;
                last_expr = None;
            }
            Statement::Delete(body) => {
                let schema = db.get_table_schema(db.this_tx_id, &body.table)?;
                if schema.readonly {
                    bail!("table {} is read-only", body.table)
                }

                let mut plan = optimize_delete(db, body)?;

                while let Some(_) =
                    execute_plan_next(&mut plan, db, Context::new(bindings.clone()))?
                {
                }

                last_expr = None;
            }
            Statement::Update(body) => {
                let schema = db.get_table_schema(db.this_tx_id, &body.table)?;
                if schema.readonly {
                    bail!("table {} is read-only", body.table)
                }

                let mut plan = optimize_update(db, body)?;

                while let Some(_) =
                    execute_plan_next(&mut plan, db, Context::new(bindings.clone()))?
                {
                }

                last_expr = None;
            }
            Statement::Select(body) => {
                fn edges(
                    map: &mut BTreeMap<String, (String, Vec<Expr>, Option<Vec<Expr>>)>,
                    e: &Expr,
                ) -> Result<(), String> {
                    match &e {
                        Expr::Binding(_) => Ok(()),
                        Expr::Literal(_) => Ok(()),
                        Expr::Unary(_op, expr) => edges(map, expr),
                        Expr::Bin(lhs, _, rhs) => {
                            edges(map, &lhs)?;
                            edges(map, &rhs)?;
                            Ok(())
                        }
                        Expr::Column(_) => Ok(()),
                        Expr::Edge(lhs, mapping, rhs, _e) => {
                            for e in lhs {
                                edges(map, e)?;
                            }

                            for e in rhs.iter().flatten() {
                                edges(map, e)?;
                            }

                            if let Some((g_table, g_lhs, g_rhs)) = map.get(&mapping.0) {
                                if g_lhs != lhs || g_rhs != rhs || &mapping.1 != g_table {
                                    Err(mapping.0.to_string())
                                } else {
                                    Ok(())
                                }
                            } else {
                                map.insert(
                                    mapping.0.to_string(),
                                    (mapping.1.to_string(), lhs.clone(), rhs.clone()),
                                );
                                Ok(())
                            }
                        }
                    }
                }

                let mut body = body.clone();

                let mut joins = BTreeMap::new();
                for e in &body.expr {
                    edges(&mut joins, e).map_err(|e| {
                        anyhow!("duplicate alias in edge expressions for table {e}")
                    })?;
                }

                for join in joins {
                    if body
                        .table_mappings
                        .iter()
                        .find(|(a, _t)| a == &join.0)
                        .is_some()
                    {
                        bail!("edge expressions and explicit joins conflict on {}", join.0)
                    }

                    let lhs_exprs = join.1 .1;
                    let rhs_exprs = if let Some(e) = join.1 .2 {
                        e
                    } else {
                        let schema = db.get_table_schema(db.this_tx_id, &join.0)?;
                        schema.primary_key
                    };

                    if lhs_exprs.len() != rhs_exprs.len() {
                        bail!("left hand side and right hand side expression lists of the edge expression do not match")
                    }

                    body.table_mappings
                        .push((join.0.clone(), join.1 .0.clone()));

                    body.cond = Some(Expr::Bin(
                        Box::new(body.cond.take().unwrap_or(Expr::Literal(Value::Bool(true)))),
                        BinOp::And,
                        Box::new(
                            lhs_exprs
                                .into_iter()
                                .zip(rhs_exprs)
                                .map(|(l, r)| Expr::Bin(Box::new(l), BinOp::Eq, Box::new(r)))
                                .reduce(|l, r| Expr::Bin(Box::new(l), BinOp::And, Box::new(r)))
                                .unwrap(),
                        ),
                    ));
                }

                let mut plan = optimize_select(db, &body)?;

                if body.explain {
                    // Some(vec![vec![Value::String(format!("{:#?}", plan))]])
                    todo!()
                } else {
                    let mut results = Vec::new();

                    while let Some(ctx) =
                        execute_plan_next(&mut plan, db, Context::new(bindings.clone()))?
                    {
                        results.push(ctx.as_slice().to_vec());
                    }

                    last_expr = Some((
                        match plan {
                            crate::executor::PlanNode::Select(select) => select.headers(),
                            _ => todo!(),
                        },
                        results,
                    ))
                }
            }
        }
    }

    Ok(last_expr)
}

// check types
// check nullability
// check CHECK condition
// check if row with same primary key exists
// check if row with same unique keys exists
// check if foreign keys are valid
fn do_insert(db: &mut Db, body: &InsertStatement, bindings: Vec<Value>) -> Result<()> {
    let schema = db.get_table_schema(db.this_tx_id, &body.table)?;

    if schema.readonly {
        bail!("table {} is read-only", body.table)
    }

    let mut ctx = Context::new(bindings);

    for (short_col_name, expr) in body.values.iter() {
        let Some(col_schema) = schema.columns.iter().find(|c| c.name == *short_col_name) else {
            bail!(
                "table {} does not have a column named {}",
                schema.name,
                short_col_name
            )
        };

        let full = Column(schema.name.clone(), col_schema.name.clone());

        if ctx.get(&full).is_some() {
            bail!("column {} is inputed multiple times", short_col_name)
        }

        let v = ctx.eval(expr)?;

        ctx.set(full, v)
    }

    inner_insert(schema, &mut ctx, db)
}

pub fn inner_insert(
    schema: crate::catalog::TableSchema,
    ctx: &mut Context,
    db: &mut Db,
) -> Result<()> {
    for col_schema in &schema.columns {
        let full = Column(schema.name.clone(), col_schema.name.clone());
        if ctx.get(&full).is_some() {
            continue;
        }

        if !col_schema.nullable {
            bail!("column {} must not be null", col_schema.name)
        }

        ctx.set(full, Value::Null)
    }

    for check in &schema.checks {
        match ctx.eval(check)? {
            Value::Bool(true) => {}
            Value::Bool(false) => bail!("check failed: {}", check),
            _ => bail!("check did not return a boolean value: {}", check),
        }
    }

    let canonical_row = schema
        .columns
        .iter()
        .map(|n| {
            ctx.get(&Column(schema.name.clone(), n.name.to_string()))
                .unwrap()
        })
        .collect::<Vec<_>>();

    for (v, col_schema) in canonical_row.iter().zip(schema.columns.iter()) {
        match (v, col_schema.ty) {
            (Value::Null, _) => {
                if !col_schema.nullable {
                    bail!("column {} must not be null", col_schema.name)
                }
            }
            (_, Type::Any)
            | (Value::Bool(_), Type::Bool)
            | (Value::Int(_), Type::Int)
            | (Value::String(_), Type::String) => {}
            (_v, _t) => {
                bail!(
                    "column {} must be of type {}",
                    col_schema.name,
                    col_schema.ty
                )
            }
        }
    }

    let primary_key_row = schema
        .primary_key
        .iter()
        .map(|e| ctx.eval(e))
        .collect::<Result<Vec<Value>, _>>()?;

    if RangeIterKV::new_simple(schema.name.clone(), db.this_tx_id, primary_key_row.clone())
        .next(db)?
        .is_some()
    {
        bail!("inputed row has duplicate primary key")
    }

    let secondary_key_rows = schema
        .indexes
        .iter()
        .map(|index| -> Result<Vec<Value>> {
            Ok(index
                .exprs
                .iter()
                .map(|e| ctx.eval(e))
                .collect::<Result<Vec<_>, _>>()?
                .into_iter()
                .chain(primary_key_row.iter().cloned())
                .collect::<Vec<_>>())
        })
        .collect::<Result<Vec<_>>>()?;

    for (sk, unique_index) in secondary_key_rows
        .iter()
        .zip(schema.indexes.iter())
        .filter(|(_, index)| index.unique)
    {
        if RangeIterKV::new_simple(unique_index.name(&schema.name), db.this_tx_id, sk.clone())
            .next(db)?
            .is_some()
        {
            bail!(
                "unique constraint violated: {}",
                unique_index
                    .exprs
                    .iter()
                    .map(|e| e.to_string())
                    .collect::<Vec<_>>()
                    .join(",")
            )
        }
    }

    for foreign_key_schema in &schema.foreign_keys {
        let rhs_schema = db.get_table_schema(db.this_tx_id, &foreign_key_schema.rhs_table)?;

        let sk = foreign_key_schema
            .lhs_exprs
            .iter()
            .map(|e| ctx.eval(e))
            .collect::<Result<Vec<_>, _>>()?;

        if RangeIterKV::new_simple(
            if rhs_schema.primary_key == foreign_key_schema.rhs_exprs {
                rhs_schema.name
            } else {
                Index {
                    exprs: foreign_key_schema.rhs_exprs.clone(),
                    unique: false,
                }
                .name(&foreign_key_schema.rhs_table)
            },
            db.this_tx_id,
            sk.clone(),
        )
        .next(db)?
        .is_none()
        {
            bail!("foreign key constraint violated: {}", foreign_key_schema)
        }
    }

    db.insert_key(&schema.name, primary_key_row.clone(), canonical_row.clone())?;

    for (sk, index) in secondary_key_rows.into_iter().zip(schema.indexes.iter()) {
        db.insert_key(&index.name(&schema.name), sk.clone(), sk)?;
    }

    Ok(())
}