Skip to content

Commit

Permalink
Very basic initial implementation
Browse files Browse the repository at this point in the history
All data is stored in a single file and the most basic forms of
CREATE TABLE, DELETE, DROP TABLE, INSERT, SELECT and UPDATE.

Only two data types: CHARACTER VARYING(n) and FLOAT are supported.
  • Loading branch information
elliotchance committed Jul 22, 2021
0 parents commit 14f0dc5
Show file tree
Hide file tree
Showing 31 changed files with 1,511 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
**/.DS_Store

21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Elliot Chance

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
169 changes: 169 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
vdb
===

vdb is an in-memory SQL database written in pure [V](https://vlang.io) with no
dependencies.

- [Installation](#installation)
- [Usage](#usage)
- [SQL Commands](#sql-commands)
- [CREATE TABLE](#create-table)
- [DELETE](#delete)
- [DROP TABLE](#drop-table)
- [INSERT](#insert)
- [SELECT](#select)
- [UPDATE](#update)
- [Appendix](#appendix)
- [Data Types](#data-types)
- [Testing](#testing)

Installation
------------

```bash
v install elliotchance.vdb
```

Usage
-----

```v
import elliotchance.vdb
fn example() ? {
mut db := vdb.open('/tmp/test.vdb') ?
// All SQL commands use query():
db.query('CREATE TABLE foo (a FLOAT)') ?
db.query('INSERT INTO foo (a) VALUES (1.23)') ?
db.query('INSERT INTO foo (a) VALUES (4.56)') ?
// Iterate through a result:
result1 := db.query('SELECT * FROM foo') ?
for row in result1 {
println(row.get_f64('a'))
}
// Handling specific errors:
db.query('SELECT * FROM bar') or {
match err {
vdb.SQLState42P01 { // 42P01 = table not found
println("I knew '$err.table_name' did not exist!")
}
else { panic(err) }
}
}
}
```

Outputs:

```
1.23
4.56
I knew 'bar' did not exist!
```

# SQL Commands

## CREATE TABLE

```
CREATE TABLE <table_name> ( <column> , ... )
column := <column_name> <column_type>
```

Example:

```sql
CREATE TABLE products (
title CHARACTER VARYING(100),
price FLOAT
)
```

## DELETE

```
DROP FROM <table_name>
[ WHERE <expr> ]
```

If `WHERE` is not provided, all records will be deleted.

## DROP TABLE

```
DROP TABLE <table_name>
```

## INSERT

```
INSERT INTO <table_name> ( <col> , ... )
VALUES ( <value> , ... )
```

The number of `col`s and `value`s must match.

Example:

```sql
INSERT INTO products (title, price) VALUES ('Instant Pot', 144.89)
```

## SELECT

```
SELECT <field> , ...
[ FROM <table_name> ]
[ WHERE <expr> ]
```

Examples:

```sql
SELECT * FROM products
```

## UPDATE

```
UPDATE <table_name>
SET <col> = <value> , ...
[ WHERE <expr> ]
```

If `WHERE` is not provided, all records will be updated.

The result (eg. `UPDATE 8`) contains the number of records actually updated.
That is, more than this number of records may have matched, but only those that
were changed will increment this counter.

Appendix
--------

### Data Types

- `CHARACTER VARYING(n)` for strings that can contain up to *n* characters.
- `FLOAT` for a 64bit floating-point value.

Testing
-------

All tests are in the `tests/` directory and each file contains individual tests
separated by an empty line:

```sql
SELECT 1
-- col1: 1

SELECT 2
SELECT 3
-- col2: 2
-- col1: 3
```

This is two tests where each test is given an a brand new database. All SQL statements are executed and each of the results collected and compared to the
comment immediately below.
50 changes: 50 additions & 0 deletions db/ast.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// ast.v contains the AST structures that represent the parsed SQL.

module vdb

// All possible root statments
type Stmt = CreateTableStmt | DeleteStmt | DropTableStmt | InsertStmt | SelectStmt | UpdateStmt

// CREATE TABLE ...
struct CreateTableStmt {
table_name string
columns []Column
}

// DELETE ...
struct DeleteStmt {
table_name string
where BinaryExpr
}

// DROP TABLE ...
struct DropTableStmt {
table_name string
}

// INSERT INTO ...
struct InsertStmt {
table_name string
columns []string
values []Value
}

// SELECT ...
struct SelectStmt {
value Value
from string
where BinaryExpr
}

// UPDATE ...
struct UpdateStmt {
table_name string
set map[string]Value
where BinaryExpr
}

struct BinaryExpr {
col string
op string
value Value
}
13 changes: 13 additions & 0 deletions db/create_table.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// create_table.v contains the implementation for the CREATE TABLE statement.

module vdb

fn (mut db Vdb) create_table(stmt CreateTableStmt) ?Result {
if stmt.table_name in db.storage.tables {
return sqlstate_42p07(stmt.table_name) // duplicate table
}

db.storage.create_table(stmt.table_name, stmt.columns) ?

return new_result_msg('CREATE TABLE 1')
}
27 changes: 27 additions & 0 deletions db/delete.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// delete.v contains the implementation for the DELETE statement.

module vdb

fn (mut db Vdb) delete(stmt DeleteStmt) ?Result {
if stmt.table_name !in db.storage.tables {
return sqlstate_42p01(stmt.table_name) // table not found
}

table := db.storage.tables[stmt.table_name]
mut rows := db.storage.read_rows(table.index) ?

mut deleted := 0
for row in rows {
mut ok := true
if stmt.where.op != '' {
ok = eval(row, stmt.where) ?
}

if ok {
deleted++
db.storage.delete_row(row) ?
}
}

return new_result_msg('DELETE $deleted')
}
14 changes: 14 additions & 0 deletions db/drop_table.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// drop_table.v contains the implementation for the DROP TABLE statement.

module vdb

fn (mut db Vdb) drop_table(stmt DropTableStmt) ?Result {
if stmt.table_name !in db.storage.tables {
return sqlstate_42p01(stmt.table_name) // table does not exist
}

// TODO(elliotchance): Also delete rows.
db.storage.delete_table(stmt.table_name) ?

return new_result_msg('DROP TABLE 1')
}
29 changes: 29 additions & 0 deletions db/eval.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// eval.v executes expressions (such as you would find in a WHERE condition).

module vdb

fn eval(data Row, e BinaryExpr) ?bool {
return eval_binary(data, e)
}

fn eval_binary(data Row, e BinaryExpr) ?bool {
if data.data[e.col].typ == .is_f64 && e.value.typ == .is_f64 {
return eval_cmp<f64>(data.get_f64(e.col), e.value.f64_value, e.op)
}

return error('cannot $e.col $e.op $e.value')
}

fn eval_cmp<T>(lhs T, rhs T, op string) bool {
return match op {
'=' { lhs == rhs }
'!=' { lhs != rhs }
'>' { lhs > rhs }
'>=' { lhs >= rhs }
'<' { lhs < rhs }
'<=' { lhs <= rhs }
// This should not be possible because the parser has already verified
// this.
else { false }
}
}
14 changes: 14 additions & 0 deletions db/insert.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// insert.v contains the implementation for the INSERT statement.

module vdb

fn (mut db Vdb) insert(stmt InsertStmt) ?Result {
mut row := Row{
data: map[string]Value{}
}
row.data[stmt.columns[0]] = stmt.values[0]

db.storage.write_row(row, db.storage.tables[stmt.table_name]) ?

return new_result_msg('INSERT 1')
}
Loading

0 comments on commit 14f0dc5

Please sign in to comment.