overdrive-db 0.2.0

Hybrid SQL+NoSQL database with Git-like versioning
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
# OverDrive-DB SQL Reference


> **Complete SQL dialect reference for OverDrive-DB v1.0**

---

## Table of Contents


1. [Data Types & JSON Model]#data-types--json-model
2. [Database Commands]#database-commands
3. [Table Commands]#table-commands
4. [Data Manipulation (CRUD)]#data-manipulation-crud
5. [Query Features]#query-features
6. [Transaction Commands]#transaction-commands
7. [Version Control]#version-control
8. [Security & Access Control]#security--access-control
9. [Backup & Restore]#backup--restore
10. [Utility Commands]#utility-commands
11. [Connection]#connection

---

## Data Types & JSON Model


OverDrive-DB is a **document-oriented database** where every record is a JSON object. There is no rigid schema — each record can have different fields.

### Automatic Fields


Every inserted record automatically receives:

| Field  | Type      | Description                         |
|--------|-----------|-------------------------------------|
| `_id`  | `string`  | Unique record identifier (UUID)     |
| `_ver` | `integer` | Version counter (increments on update) |
| `_ts`  | `integer` | Timestamp of last modification      |

### Supported JSON Value Types


| Type      | Example                          |
|-----------|----------------------------------|
| String    | `"hello world"`                  |
| Number    | `42`, `3.14`, `-1`               |
| Boolean   | `true`, `false`                  |
| Null      | `null`                           |
| Array     | `[1, 2, 3]`                      |
| Object    | `{"nested": {"key": "value"}}`   |

---

## Database Commands


### SHOW DATABASES


Lists all databases on the server.

```sql
SHOW DATABASES;
SHOW DBS;          -- alias
SHOW DB;           -- alias
```

### CREATE DATABASE


Creates a new `.odb` database file.

```sql
CREATE DATABASE <name>;
CREATE DBS <name>;       -- alias
CREATE DB <name>;        -- alias
```

**Example:**
```sql
CREATE DB myapp;
-- ✅ Database 'myapp' created successfully
```

### USE


Switches the active database context.

```sql
USE <name>;
```

**Example:**
```sql
USE myapp;
-- ✅ Now using database 'myapp'
-- Prompt changes to: OverDrive [myapp]>
```

### DROP DATABASE


Permanently deletes a database file.

```sql
DROP DATABASE <name>;
DROP DBS <name>;         -- alias
DROP DB <name>;          -- alias
```

> **⚠️ Warning:** This permanently deletes the `.odb` file and all data inside it.

---

## Table Commands


### SHOW TABLES


Lists all tables in the current database.

```sql
SHOW TABLES;
SHOW TABLE;        -- alias
SHOW TB;           -- alias
```

**Requires:** An active database (`USE <db>` first).

### CREATE TABLE


Creates a new table. Three modes are available:

#### Unstructured (Schema-free)

```sql
CREATE TABLE <name>;
CREATE TB <name>;        -- alias
```

#### Structured (With Schema)

```sql
CREATE TABLE <name> {
  <field>: <type>,
  <field>: <type>
};
```

Supported types: `string`, `int`, `float`, `bool`

#### From Template

```sql
CREATE TABLE <name> FROM TEMPLATE <template>;
```

Available templates:

| Template   | Fields                                              |
|------------|-----------------------------------------------------|
| `USERS`    | email, password_hash, created_at, roles             |
| `SESSIONS` | session_id, token, expires (24h)                    |
| `OTP`      | phone, code, expires (5min), max_attempts (3)       |

**Example:**
```sql
CREATE TB products {name: string, price: float, stock: int};
CREATE TB auth FROM TEMPLATE USERS;
```

> **Note:** Creating a table that already exists is idempotent (no error).

### DESCRIBE


Shows table schema and metadata.

```sql
DESCRIBE <table>;
DESC <table>;            -- alias
```

### DROP TABLE


Deletes a table and all its records.

```sql
DROP TABLE <name>;
DROP TB <name>;          -- alias
```

> **Note:** Dropping a nonexistent table is idempotent (no error).

---

## Data Manipulation (CRUD)


### INSERT INTO


Inserts a JSON record into a table.

```sql
INSERT INTO <table> {<json>};
```

**Examples:**
```sql
INSERT INTO users {
  name: "Alice",
  email: "alice@example.com",
  age: 30,
  active: true
};
-- ✅ 1 row inserted (returns generated _id)

-- Nested objects and arrays
INSERT INTO products {
  name: "Widget",
  tags: ["sale", "new"],
  specs: {weight: 1.5, color: "blue"}
};
```

> **Note:** Inserting into a nonexistent table auto-creates it.

### SELECT


Retrieves records from a table.

```sql
-- All records
SELECT * FROM <table>;

-- With WHERE filter
SELECT * FROM <table> WHERE <condition>;

-- With specific columns
SELECT <col1>, <col2> FROM <table>;

-- Full query with all clauses
SELECT * FROM <table>
  WHERE <condition>
  GROUP BY <column>
  ORDER BY <column> ASC|DESC
  LIMIT <n>;
```

#### WHERE Conditions


| Operator | Example                        | Description       |
|----------|--------------------------------|-------------------|
| `=`      | `WHERE name = "Alice"`         | Equals            |
| `!=`     | `WHERE status != "deleted"`    | Not equals        |
| `>`      | `WHERE age > 21`               | Greater than      |
| `<`      | `WHERE price < 100`            | Less than         |
| `>=`     | `WHERE score >= 90`            | Greater or equal  |
| `<=`     | `WHERE count <= 5`             | Less or equal     |

**Examples:**
```sql
SELECT * FROM users WHERE age > 25;
SELECT name, email FROM users WHERE active = true;
SELECT * FROM products WHERE price < 50 ORDER BY price ASC;
SELECT * FROM logs LIMIT 10;
```

### UPDATE


Updates records matching a condition.

```sql
UPDATE <table> SET {<json>} WHERE <condition>;
```

**Example:**
```sql
UPDATE users SET {
  active: false,
  deactivated_at: "2026-02-21"
} WHERE email = "alice@example.com";
-- ✅ 1 row updated (_ver incremented)
```

> **Note:** Updates increment `_ver` and update `_ts`.

### DELETE


Removes records matching a condition.

```sql
DELETE FROM <table> WHERE <condition>;
```

**Example:**
```sql
DELETE FROM sessions WHERE expired = true;
-- ✅ 3 rows deleted
```

### GET (by ID)


Retrieve a single record by its `_id`.

```sql
GET <table> <id>;
```

**Example:**
```sql
GET users u001;
-- {"_id": "u001", "name": "Alice", ...}
```

### SEARCH


Full-text search across all fields in a table.

```sql
SEARCH '<query>';
```

**Example:**
```sql
SEARCH 'alice';
-- Found in users:
--   {"_id": "u001", "name": "Alice", "email": "alice@example.com"}
```

---

## Query Features


### Aggregation Functions


Used with `SELECT` queries:

| Function         | Syntax                                      | Description              |
|------------------|---------------------------------------------|--------------------------|
| `COUNT(*)`       | `SELECT COUNT(*) FROM <table>`              | Total record count       |
| `COUNT(<col>)`   | `SELECT COUNT(score) FROM <table>`          | Non-null value count     |
| `SUM(<col>)`     | `SELECT SUM(amount) FROM <table>`           | Numeric sum              |
| `AVG(<col>)`     | `SELECT AVG(score) FROM <table>`            | Numeric average          |
| `MIN(<col>)`     | `SELECT MIN(price) FROM <table>`            | Minimum value            |
| `MAX(<col>)`     | `SELECT MAX(price) FROM <table>`            | Maximum value            |

### GROUP BY


Groups records and applies aggregate functions per group.

```sql
SELECT dept, COUNT(*) FROM employees GROUP BY dept;
```

### ORDER BY


Sorts results by one or more columns.

```sql
SELECT * FROM products ORDER BY price ASC;
SELECT * FROM users ORDER BY dept ASC, name DESC;
```

Directions: `ASC` (ascending, default), `DESC` (descending).

### LIMIT


Restricts the number of returned records.

```sql
SELECT * FROM logs ORDER BY _ts DESC LIMIT 100;
```

### JOIN


Combines records from two tables.

```sql
-- Inner Join
SELECT * FROM users
  JOIN orders ON users.id = orders.user_id;

-- Left Join (keeps all left-side rows)
SELECT * FROM users
  LEFT JOIN orders ON users.id = orders.user_id;
```

---

## Transaction Commands


### BEGIN / COMMIT / ROLLBACK


```sql
BEGIN;                     -- Start transaction
BEGIN ISOLATION SERIALIZABLE;  -- With isolation level

-- ... make changes ...

COMMIT;                    -- Persist all changes
ROLLBACK;                  -- Discard all changes
```

### Savepoints


```sql
BEGIN;
INSERT INTO users {name: "Alice"};
SAVEPOINT sp1;
INSERT INTO users {name: "Bob"};
ROLLBACK TO SAVEPOINT sp1;   -- Undo Bob, keep Alice
COMMIT;
```

### Isolation Levels


| Level              | Dirty Reads | Non-repeatable | Phantoms |
|--------------------|-------------|----------------|----------|
| `READ UNCOMMITTED` | Possible    | Possible       | Possible |
| `READ COMMITTED`   | No          | Possible       | Possible |
| `REPEATABLE READ`  | No          | No             | Possible |
| `SERIALIZABLE`     | No          | No             | No       |

---

## Version Control


OverDrive-DB has built-in Git-like version control using hash chains.

### HISTORY


Shows commit log.

```sql
HISTORY;                   -- All commits
HISTORY <table>;           -- Table-specific
```

### ROLLBACK TO


Restores database state to a previous commit.

```sql
ROLLBACK TO <commit_id>;
```

### DIFF


Compares two commits.

```sql
DIFF <commit1> <commit2>;
```

### VERIFY


Validates the hash chain integrity.

```sql
VERIFY;
-- ✅ Hash chain verified - 42 commits, all valid
```

---

## Security & Access Control


### Authentication


Connects and authenticates to a server.

```sql
CONNECT '<host>:<port>' USER <username> PASSWORD '<password>' [TLS] [INSECURE];
```

### User Management (Admin only)


```sql
-- Create user
CREATE USER <username> PASSWORD '<password>';

-- Remove user
DROP USER <username>;

-- List users
SHOW USERS;
```

### Role-Based Access Control (RBAC)


```sql
-- Grant role
GRANT <role> TO <username>;

-- Revoke role
REVOKE <role> FROM <username>;
```

#### Built-in Roles


| Role       | Permissions                        |
|------------|------------------------------------|
| `admin`    | All operations (Read, Write, Delete, CreateTable, DropTable, DropDb, Admin) |
| `user`     | Read, Write, CreateTable           |
| `readonly` | Read only                          |

### Security Features


- **Argon2id** password hashing (OWASP recommended)
- **Brute-force protection**: Account locks after 5 failed attempts (30-second lockout)
- **Progressive delays**: Exponential backoff on failed login attempts
- **TLS 1.3** encrypted connections
- **Session tokens**: 24-hour TTL with 30-minute idle timeout

---

## Backup & Restore


### BACKUP


Exports the current database to a JSON file.

```sql
.BACKUP <filename>;
```

### RESTORE


Imports a database from a JSON backup file.

```sql
.RESTORE <filename>;
```

---

## Utility Commands


| Command     | Alias   | Description                     |
|-------------|---------|--------------------------------|
| `STATS`     | -       | Show database statistics        |
| `HELP`      | -       | Display command reference       |
| `EXPLAIN`   | -       | Show query execution plan       |
| `CLEAR`     | `CLS`   | Clear screen                    |
| `EXIT`      | `QUIT`  | Exit the shell                  |

### STATS


```sql
STATS;
-- Database: myapp
-- Tables: 5
-- Total Records: 1,234
-- DB Size: 15.3 MB
```

### EXPLAIN


Shows the query optimizer's execution plan.

```sql
EXPLAIN SELECT * FROM users WHERE age > 25;
```

---

## Connection Modes


### Embedded Mode


Direct file access (single process):

```bash
overdrive              # Interactive shell
overdrive --db myapp   # Open specific database
```

### Client-Server Mode


Multi-client access over the network:

```bash
# Start server

overdrive-serve --port 6969

# Connect client

overdrive --connect "localhost:6969" --user admin --password secret
```

### Connection Flags


| Flag         | Description                              |
|--------------|------------------------------------------|
| `TLS`        | Enable TLS 1.3 encryption (default)      |
| `INSECURE`   | Skip certificate validation (dev only)   |

---

## Command Aliases Quick Reference


| Full Command       | Short Aliases                    |
|--------------------|----------------------------------|
| `SHOW DATABASES`   | `SHOW DBS`, `SHOW DB`            |
| `CREATE DATABASE`  | `CREATE DBS`, `CREATE DB`        |
| `DROP DATABASE`    | `DROP DBS`, `DROP DB`            |
| `SHOW TABLES`      | `SHOW TABLE`, `SHOW TB`          |
| `CREATE TABLE`     | `CREATE TABLES`, `CREATE TB`     |
| `DROP TABLE`       | `DROP TABLES`, `DROP TB`         |
| `DESCRIBE`         | `DESC`                           |
| `CLEAR`            | `CLS`                            |
| `EXIT`             | `QUIT`                           |

---

## File Format


- **Extension:** `.odb` (OverDrive Database)
- **Storage:** Binary format with B-tree indexing and WAL (Write-Ahead Log)
- **Default Location:** `databases/` directory relative to the server binary
- **Default Port:** `6969`