rustmemodb 0.1.0

In-memory SQL database with transaction support, connection pooling, and MVCC
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
# RustMemDB

[![Rust](https://img.shields.io/badge/rust-1.70%2B-orange.svg)](https://www.rust-lang.org/)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Build Status](https://img.shields.io/badge/build-passing-brightgreen.svg)]()

**A lightweight, in-memory SQL database engine written in pure Rust with a focus on educational clarity and extensibility.**

---

## 📖 Table of Contents

- [Overview]#overview
- [Mission & Purpose]#mission--purpose
- [Architecture]#architecture
- [Features]#features
- [Installation]#installation
- [Quick Start]#quick-start
- [Usage Examples]#usage-examples
- [API Documentation]#api-documentation
- [Performance Characteristics]#performance-characteristics
- [Design Patterns]#design-patterns
- [Extensibility]#extensibility
- [Limitations]#limitations
- [Roadmap]#roadmap
- [Contributing]#contributing
- [Educational Resources]#educational-resources
- [License]#license

### 📚 Additional Documentation

- **[DEVELOPER_GUIDE.md]docs/DEVELOPER_GUIDE.md** - Complete guide for adding new features to RustMemoDB
- **[PRODUCTION_READINESS_ANALYSIS.md]docs/PRODUCTION_READINESS_ANALYSIS.md** - Production readiness assessment
---

## 🎯 Overview

RustMemDB is an **educational in-memory SQL database** that demonstrates how modern relational databases work under the hood. Built entirely in Rust, it implements a complete SQL query execution pipeline from parsing to result generation, while maintaining clean architecture and extensible design.

Unlike production databases (PostgreSQL, MySQL), RustMemDB prioritizes:
- **Code Clarity** - Easy to understand implementation
- **Educational Value** - Learn database internals by reading/modifying code
- **Extensibility** - Plugin-based architecture for adding features
- **Type Safety** - Leveraging Rust's strong type system

### What Makes It Unique?

```rust
// Simple, clean API
let mut db = InMemoryDB::new();

db.execute("CREATE TABLE users (id INTEGER, name TEXT, age INTEGER)")?;
db.execute("INSERT INTO users VALUES (1, 'Alice', 30)")?;

let result = db.execute("SELECT * FROM users WHERE age > 25")?;
result.print();
```

Under the hood, this simple query goes through a **complete database pipeline**:
1. **SQL Parsing** → AST (Abstract Syntax Tree)
2. **Query Planning** → Logical execution plan
3. **Optimization** → (Future: predicate pushdown, join ordering)
4. **Execution** → Physical operators (scan, filter, project, sort)
5. **Result Formatting** → User-friendly output

---

## 🎯 Mission & Purpose

### Primary Mission

**"Make database internals accessible and understandable through clean, well-documented Rust code."**

### Target Audience

1. **Students & Educators**
   - Learn how SQL databases work internally
   - Understand query processing pipelines
   - Study classic database algorithms (sorting, filtering, etc.)

2. **Rust Developers**
   - See real-world application of design patterns
   - Learn concurrent data structure design
   - Understand plugin architectures

3. **Database Enthusiasts**
   - Prototype new database features
   - Experiment with query optimization algorithms
   - Build custom storage engines

4. **Embedded Systems**
   - Lightweight SQL for resource-constrained environments
   - No external dependencies (pure Rust)
   - Small memory footprint

### What This Project Is For

✅ **Learning** - Study database architecture
✅ **Prototyping** - Test database algorithms quickly
✅ **Testing** - In-memory database for unit tests
✅ **Embedded SQL** - Simple queries in Rust applications
✅ **Research** - Academic database research projects

### What This Project Is NOT For

❌ **Production Databases** - Use PostgreSQL, MySQL, SQLite instead
❌ **Persistent Storage** - Data lost on shutdown (in-memory only)
❌ **High Performance** - Educational focus over optimization
❌ **Full SQL Compliance** - Subset of SQL features

---

## 🏗️ Architecture

RustMemDB follows the classic **three-stage database architecture** used by most relational databases:

```
┌─────────────────────────────────────────────────────────────┐
│                          SQL Query                          │
│              "SELECT * FROM users WHERE age > 25"           │
└──────────────────────┬──────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│                    PARSER LAYER                             │
│  ┌────────────────────────────────────────────────────┐     │
│  │ SqlParserAdapter (Facade Pattern)                  │     │
│  │  - Uses sqlparser crate for SQL parsing            │     │
│  │  - Converts external AST → Internal AST            │     │
│  │  - Plugin-based expression conversion              │     │
│  └────────────────────────────────────────────────────┘     │
└──────────────────────┬──────────────────────────────────────┘
                       ▼  Statement AST
┌─────────────────────────────────────────────────────────────┐
│                    PLANNER LAYER                            │
│  ┌────────────────────────────────────────────────────┐     │
│  │ QueryPlanner (Strategy Pattern)                    │     │
│  │  - AST → LogicalPlan transformation                │     │
│  │  - Logical operators: Scan, Filter, Project, Sort  │     │
│  │  - Future: Query optimization                      │     │
│  └────────────────────────────────────────────────────┘     │
└──────────────────────┬──────────────────────────────────────┘
                       ▼  LogicalPlan
┌─────────────────────────────────────────────────────────────┐
│                   EXECUTOR LAYER                            │
│  ┌────────────────────────────────────────────────────┐     │
│  │ ExecutorPipeline (Chain of Responsibility)         │     │
│  │  ┌──────────────────────────────────────────────┐  │     │
│  │  │ DDL: CreateTableExecutor, DropTableExecutor  │  │     │
│  │  │ DML: InsertExecutor, UpdateExecutor,         │  │     │
│  │  │      DeleteExecutor                          │  │     │
│  │  │ DQL: QueryExecutor                           │  │     │
│  │  │      - TableScan → Filter → Aggregate/Sort   │  │     │
│  │  │      - Project → Limit                       │  │     │
│  │  └──────────────────────────────────────────────┘  │     │
│  └────────────────────────────────────────────────────┘     │
└──────────────────────┬──────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│                    STORAGE LAYER                            │
│  ┌───────────────────┐        ┌─────────────────────┐       │
│  │ Catalog           │        │ InMemoryStorage     │       │
│  │ (Copy-on-Write)   │        │ (Row-based)         │       │
│  │                   │        │                     │       │
│  │ - Table schemas   │        │ - Per-table RwLock  │       │
│  │ - Arc<HashMap>    │        │ - Concurrent access │       │
│  │ - Lock-free reads │        │ - Vec<Row> storage  │       │
│  └───────────────────┘        └─────────────────────┘       │
└─────────────────────────────────────────────────────────────┘
               ┌───────────────┐
               │ QueryResult   │
               │  - Columns    │
               │  - Rows       │
               └───────────────┘
```

### Key Components

#### 1. Parser (`src/parser/`)
Converts SQL text into an Abstract Syntax Tree (AST).

- **SqlParserAdapter** - Facade over `sqlparser` crate
- **Plugin System** - Extensible expression conversion
- **AST Definition** - Internal representation optimized for our needs

#### 2. Planner (`src/planner/`)
Transforms AST into a logical execution plan.

- **QueryPlanner** - AST → LogicalPlan converter
- **LogicalPlan Nodes** - TableScan, Filter, Projection, Sort, Limit
- **Future** - Query optimization passes

#### 3. Executor (`src/executor/`)
Executes logical plans against storage.

- **ExecutorPipeline** - Chain of Responsibility pattern
- **Specialized Executors** - DDL, DML, DQL handlers
- **Physical Operators** - Actual data processing
- **EvaluatorRegistry** - Plugin-based expression evaluation

#### 4. Storage (`src/storage/`)
In-memory data storage with concurrent access.

- **Catalog** - Metadata (schemas) with lock-free reads
- **InMemoryStorage** - Actual row data with fine-grained locking
- **TableSchema** - Column definitions and constraints

#### 5. Evaluator (`src/evaluator/`)
Runtime expression evaluation system.

- **Plugin Architecture** - Extensible evaluators
- **Built-in Evaluators** - Arithmetic, comparison, logical, LIKE, BETWEEN, IS NULL
- **EvaluationContext** - Thread-safe expression evaluation

---

## ✨ Features

### Currently Implemented

#### SQL Support
- **DDL (Data Definition Language)**
  - `CREATE TABLE` with column types and constraints
  - `DROP TABLE` with `IF EXISTS` support
  - `CREATE INDEX` for faster lookups
  - `ALTER TABLE` (Basic support: Add/Drop column)
-**Constraints**
  - `PRIMARY KEY` (enforces uniqueness and NOT NULL)
  - `UNIQUE` (enforces uniqueness, allows multiple NULLs)
-**DML (Data Manipulation Language)**
  - `INSERT INTO` with multiple rows
  - `UPDATE` with `SET` and `WHERE` clauses
  - `DELETE FROM` with conditional filtering
-**DQL (Data Query Language)**
  - `SELECT` with full query capabilities
  - Aggregate functions (`COUNT`, `SUM`, `AVG`, `MIN`, `MAX`)
-**Transaction Control**
  - `BEGIN` / `START TRANSACTION` - Start a new transaction
  - `COMMIT` - Commit all changes atomically
  - `ROLLBACK` - Undo all changes in the transaction
  - Full MVCC support with snapshot isolation
  - Manual `close()` required for safety (Warning on connection drop)

#### Query Capabilities
- **Projection** - `SELECT col1, col2` or `SELECT *`
-**Filtering** - `WHERE` with complex predicates and parentheses
-**Aggregation** - `COUNT(*)`, `SUM(col)`, `AVG(col)`, `MIN(col)`, `MAX(col)`
-**Sorting** - `ORDER BY col1 ASC, col2 DESC` (multiple columns)
-**Limiting** - `LIMIT n` for result pagination
-**Indexing** - B-Tree backed indexes for O(log n) lookups
-**Expressions** - Full arithmetic and logical expressions in all clauses

#### Operators & Functions
- **Arithmetic** - `+`, `-`, `*`, `/`, `%`
-**Comparison** - `=`, `!=`, `<`, `<=`, `>`, `>=`
-**Logical** - `AND`, `OR`, `NOT` with parentheses support
-**Pattern Matching** - `LIKE`, `NOT LIKE` (with `%`, `_` wildcards)
-**Range** - `BETWEEN x AND y`
-**Null Checking** - `IS NULL`, `IS NOT NULL`
-**List Membership** - `IN (value1, value2, ...)`
-**Aggregate Functions** - `COUNT`, `SUM`, `AVG`, `MIN`, `MAX`

#### Data Types
- **INTEGER** - 64-bit signed integers
-**FLOAT** - 64-bit floating point
-**TEXT** - Variable-length strings
-**BOOLEAN** - true/false values
-**NULL** - Null value support with proper handling

#### Advanced Features
- **Multi-column sorting** with NULL handling
-**Expression evaluation** in WHERE, ORDER BY, SELECT, UPDATE
-**Concurrent access** - Fine-grained table locking with global singleton
-**Plugin system** - Extensible parsers and evaluators
-**Type coercion** - Automatic INTEGER ↔ FLOAT conversion
-**Client API** - PostgreSQL/MySQL-like connection interface
-**Connection pooling** - Efficient connection management
-**User management** - Authentication and authorization system
-**Persistence** - WAL-based durability and snapshots

### Performance Features
- **Per-table locking** - Concurrent access to different tables
-**Lock-free catalog reads** - Copy-on-Write metadata
-**Stable sorting** - Predictable ORDER BY results
-**Efficient aggregation** - Single-pass aggregate computation
-**Global singleton** - Shared state for all connections
-**Indexing** - High-performance data retrieval

### Performance Metrics
```
Sequential UPDATE:     2.9M updates/sec (5,000 rows)
Mixed operations:      7,083 ops/sec (UPDATE + SELECT)
Concurrent access:     Stable with 4 threads
Aggregate functions:   Fast single-pass computation
Index Scan:            O(log n) retrieval vs O(n) full scan
```

---

## 🚀 Installation

### Prerequisites
- Rust 1.70 or higher
- Cargo (comes with Rust)

### From Source

```bash
# Clone the repository
git clone https://github.com/yourusername/rustmemodb.git
cd rustmemodb

# Build the project
cargo build --release

# Run tests
cargo test

# Run the demo application
cargo run
```

### As a Library

Add to your `Cargo.toml`:

```toml
[dependencies]
rustmemodb = { path = "../rustmemodb" }  # or from crates.io when published
```

---

## ⚡ Quick Start

### Basic Example

```rust
use rustmemodb::InMemoryDB;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create a new database instance
    let mut db = InMemoryDB::new();

    // Create a table
    db.execute(
        "CREATE TABLE users (
            id INTEGER,
            name TEXT,
            age INTEGER
        )"
    )?;
    
    // Create an index for performance
    db.execute("CREATE INDEX idx_age ON users (age)")?;

    // Insert data
    db.execute("INSERT INTO users VALUES (1, 'Alice', 30)")?;
    db.execute("INSERT INTO users VALUES (2, 'Bob', 25)")?;
    db.execute("INSERT INTO users VALUES (3, 'Charlie', 35)")?;

    // Query data
    let result = db.execute("SELECT * FROM users WHERE age > 25")?;
    result.print();

    Ok(())
}
```

Output:
```
┌────┬─────────┬─────┐
│ id │ name    │ age │
├────┼─────────┼─────┤
│ 1  │ Alice   │ 30  │
│ 3  │ Charlie │ 35  │
└────┴─────────┴─────┘
```

---

## 📚 Usage Examples

### Example 1: User Management System

```rust
use rustmemodb::InMemoryDB;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut db = InMemoryDB::new();

    // Create users table
    db.execute(
        "CREATE TABLE users (
            id INTEGER,
            username TEXT,
            email TEXT,
            age INTEGER,
            active BOOLEAN
        )"
    )?;

    // Insert users
    db.execute("INSERT INTO users VALUES (1, 'alice', 'alice@example.com', 30, true)")?;
    db.execute("INSERT INTO users VALUES (2, 'bob', 'bob@example.com', 25, true)")?;
    db.execute("INSERT INTO users VALUES (3, 'charlie', 'charlie@example.com', 35, false)")?;
    db.execute("INSERT INTO users VALUES (4, 'diana', 'diana@example.com', 28, true)")?;

    // Find active users over 26
    println!("\n=== Active users over 26 ===");
    let result = db.execute(
        "SELECT username, email, age
         FROM users
         WHERE active = true AND age > 26"
    )?;
    result.print();

    // Find users with email matching pattern
    println!("\n=== Users with 'example.com' email ===");
    let result = db.execute(
        "SELECT username, email
         FROM users
         WHERE email LIKE '%@example.com'"
    )?;
    result.print();

    // Top 3 oldest users
    println!("\n=== Top 3 oldest users ===");
    let result = db.execute(
        "SELECT username, age
         FROM users
         ORDER BY age DESC
         LIMIT 3"
    )?;
    result.print();

    Ok(())
}
```

### Example 2: Product Catalog

```rust
use rustmemodb::InMemoryDB;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut db = InMemoryDB::new();

    // Create products table
    db.execute(
        "CREATE TABLE products (
            id INTEGER,
            name TEXT,
            category TEXT,
            price FLOAT,
            stock INTEGER
        )"
    )?;

    // Insert products
    db.execute("INSERT INTO products VALUES (1, 'Laptop', 'Electronics', 999.99, 10)")?;
    db.execute("INSERT INTO products VALUES (2, 'Mouse', 'Electronics', 29.99, 50)")?;
    db.execute("INSERT INTO products VALUES (3, 'Desk', 'Furniture', 299.99, 5)")?;
    db.execute("INSERT INTO products VALUES (4, 'Chair', 'Furniture', 199.99, 15)")?;
    db.execute("INSERT INTO products VALUES (5, 'Monitor', 'Electronics', 399.99, 8)")?;

    // Find expensive electronics
    println!("\n=== Electronics over $100 ===");
    let result = db.execute(
        "SELECT name, price, stock
         FROM products
         WHERE category = 'Electronics' AND price > 100
         ORDER BY price DESC"
    )?;
    result.print();

    // Products in price range
    println!("\n=== Products between $50 and $400 ===");
    let result = db.execute(
        "SELECT name, category, price
         FROM products
         WHERE price BETWEEN 50 AND 400
         ORDER BY price ASC"
    )?;
    result.print();

    // Low stock items
    println!("\n=== Low stock (< 10 items) ===");
    let result = db.execute(
        "SELECT name, stock
         FROM products
         WHERE stock < 10
         ORDER BY stock ASC"
    )?;
    result.print();

    Ok(())
}
```

### Example 3: Advanced Queries

```rust
use rustmemodb::InMemoryDB;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut db = InMemoryDB::new();

    db.execute(
        "CREATE TABLE employees (
            id INTEGER,
            name TEXT,
            department TEXT,
            salary FLOAT,
            years_employed INTEGER
        )"
    )?;

    // Insert data
    db.execute("INSERT INTO employees VALUES (1, 'Alice', 'Engineering', 95000.0, 5)")?;
    db.execute("INSERT INTO employees VALUES (2, 'Bob', 'Sales', 75000.0, 3)")?;
    db.execute("INSERT INTO employees VALUES (3, 'Charlie', 'Engineering', 110000.0, 8)")?;
    db.execute("INSERT INTO employees VALUES (4, 'Diana', 'Marketing', 80000.0, 4)")?;
    db.execute("INSERT INTO employees VALUES (5, 'Eve', 'Engineering', 105000.0, 6)")?;

    // Complex WHERE with multiple conditions
    println!("\n=== Senior Engineering employees ===");
    let result = db.execute(
        "SELECT name, salary, years_employed
         FROM employees
         WHERE department = 'Engineering'
           AND years_employed > 5
           AND salary > 100000
         ORDER BY salary DESC"
    )?;
    result.print();

    // Using expressions in SELECT
    println!("\n=== Salary after 10% raise ===");
    let result = db.execute(
        "SELECT name, department, salary * 1.1
         FROM employees
         ORDER BY salary DESC"
    )?;
    result.print();

    // Multi-level sorting
    println!("\n=== All employees by dept and salary ===");
    let result = db.execute(
        "SELECT name, department, salary
         FROM employees
         ORDER BY department ASC, salary DESC"
    )?;
    result.print();

    Ok(())
}
```

### Example 4: NULL Value Handling

```rust
use rustmemodb::InMemoryDB;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut db = InMemoryDB::new();

    db.execute(
        "CREATE TABLE contacts (
            id INTEGER,
            name TEXT,
            email TEXT,
            phone TEXT
        )"
    )?;

    // Some contacts have missing information
    db.execute("INSERT INTO contacts VALUES (1, 'Alice', 'alice@example.com', '555-1234')")?;
    db.execute("INSERT INTO contacts VALUES (2, 'Bob', NULL, '555-5678')")?;
    db.execute("INSERT INTO contacts VALUES (3, 'Charlie', 'charlie@example.com', NULL)")?;

    // Find contacts without email
    println!("\n=== Contacts without email ===");
    let result = db.execute(
        "SELECT name, phone
         FROM contacts
         WHERE email IS NULL"
    )?;
    result.print();

    // Find contacts with complete information
    println!("\n=== Contacts with complete info ===");
    let result = db.execute(
        "SELECT name, email, phone
         FROM contacts
         WHERE email IS NOT NULL AND phone IS NOT NULL"
    )?;
    result.print();

    Ok(())
}
```

### Example 5: UPDATE and DELETE Operations

```rust
use rustmemodb::Client;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::connect("admin", "admin")?;

    // Create table
    client.execute(
        "CREATE TABLE inventory (
            id INTEGER,
            product TEXT,
            quantity INTEGER,
            price FLOAT
        )"
    )?;

    // Insert initial data
    client.execute("INSERT INTO inventory VALUES (1, 'Laptop', 10, 999.99)")?;
    client.execute("INSERT INTO inventory VALUES (2, 'Mouse', 50, 29.99)")?;
    client.execute("INSERT INTO inventory VALUES (3, 'Keyboard', 30, 79.99)")?;
    client.execute("INSERT INTO inventory VALUES (4, 'Monitor', 15, 399.99)")?;

    // Update prices (10% discount)
    println!("\n=== Applying 10% discount ===");
    let result = client.execute("UPDATE inventory SET price = price * 0.9")?;
    println!("Updated {} products", result.affected_rows().unwrap_or(0));

    // Update specific item
    println!("\n=== Restocking mice ===");
    let result = client.execute("UPDATE inventory SET quantity = 100 WHERE product = 'Mouse'")?;
    println!("Updated {} rows", result.affected_rows().unwrap_or(0));

    // Delete low stock items
    println!("\n=== Removing low stock items ===");
    let result = client.execute("DELETE FROM inventory WHERE quantity < 20")?;
    println!("Deleted {} items", result.affected_rows().unwrap_or(0));

    // View remaining inventory
    println!("\n=== Current Inventory ===");
    let result = client.query("SELECT * FROM inventory ORDER BY product")?;
    result.print();

    Ok(())
}
```

### Example 6: Transactions (ACID Support)

```rust
use rustmemodb::Client;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::connect("admin", "adminpass")?;

    // Create accounts table
    client.execute(
        "CREATE TABLE accounts (
            id INTEGER,
            name TEXT,
            balance FLOAT
        )"
    )?;

    // Insert initial data
    client.execute("INSERT INTO accounts VALUES (1, 'Alice', 1000.0)")?;
    client.execute("INSERT INTO accounts VALUES (2, 'Bob', 500.0)")?;

    // Get a connection from the pool
    let mut conn = client.get_connection()?;

    // Start a transaction
    println!("=== Starting Transaction ===");
    conn.begin()?;

    // Transfer money from Alice to Bob
    conn.execute("UPDATE accounts SET balance = balance - 200.0 WHERE id = 1")?;
    conn.execute("UPDATE accounts SET balance = balance + 200.0 WHERE id = 2")?;

    // Check balances within transaction
    let result = conn.execute("SELECT name, balance FROM accounts ORDER BY id")?;
    println!("Balances after transfer:");
    result.print();

    // Commit the transaction
    conn.commit()?;
    println!("=== Transaction Committed ===");

    // Verify final state
    let result = client.query("SELECT name, balance FROM accounts ORDER BY id")?;
    println!("Final balances:");
    result.print();

    Ok(())
}
```

### Example 7: Transaction Rollback

```rust
use rustmemodb::Client;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::connect("admin", "adminpass")?;

    client.execute("CREATE TABLE inventory (id INTEGER, product TEXT, stock INTEGER)")?;
    client.execute("INSERT INTO inventory VALUES (1, 'Widget', 100)")?;
    client.execute("INSERT INTO inventory VALUES (2, 'Gadget', 50)")?;

    let mut conn = client.get_connection()?;

    // Transaction that will be rolled back
    println!("=== Starting Transaction ===");
    conn.begin()?;

    conn.execute("UPDATE inventory SET stock = stock - 20 WHERE product = 'Widget'")?;
    conn.execute("DELETE FROM inventory WHERE product = 'Gadget'")?;

    println!("Changes within transaction:");
    let result = conn.execute("SELECT * FROM inventory")?;
    result.print();

    // Rollback instead of commit
    println!("\n=== Rolling Back Transaction ===");
    conn.rollback()?;

    // Verify data was restored
    println!("After rollback:");
    let result = client.query("SELECT * FROM inventory")?;
    result.print();

    Ok(())
}
```

### Example 8: Aggregate Functions

```rust
use rustmemodb::Client;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::connect("admin", "admin")?;

    // Create sales table
    client.execute(
        "CREATE TABLE sales (
            id INTEGER,
            product TEXT,
            quantity INTEGER,
            revenue FLOAT
        )"
    )?;

    // Insert sales data
    client.execute("INSERT INTO sales VALUES (1, 'Laptop', 5, 4999.95)")?;
    client.execute("INSERT INTO sales VALUES (2, 'Mouse', 50, 1499.50)")?;
    client.execute("INSERT INTO sales VALUES (3, 'Keyboard', 30, 2399.70)")?;
    client.execute("INSERT INTO sales VALUES (4, 'Monitor', 10, 3999.90)")?;

    // Get comprehensive statistics
    println!("\n=== Sales Statistics ===");
    let result = client.query(
        "SELECT COUNT(*), SUM(revenue), AVG(revenue), MIN(revenue), MAX(revenue)
         FROM sales"
    )?;
    result.print();

    // Count total items sold
    println!("\n=== Total Items Sold ===");
    let result = client.query("SELECT SUM(quantity) FROM sales")?;
    result.print();

    // Find highest revenue
    println!("\n=== Highest Single Sale ===");
    let result = client.query("SELECT MAX(revenue) FROM sales")?;
    result.print();

    // Average quantity per order
    println!("\n=== Average Order Size ===");
    let result = client.query("SELECT AVG(quantity) FROM sales")?;
    result.print();

    Ok(())
}
```

### Example 7: Database Statistics

```rust
use rustmemodb::InMemoryDB;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut db = InMemoryDB::new();

    // Create multiple tables
    db.execute("CREATE TABLE users (id INTEGER, name TEXT)")?;
    db.execute("CREATE TABLE products (id INTEGER, name TEXT, price FLOAT)")?;

    // Insert data
    for i in 1..=100 {
        db.execute(&format!("INSERT INTO users VALUES ({}, 'user_{}')", i, i))?;
    }

    for i in 1..=50 {
        db.execute(&format!(
            "INSERT INTO products VALUES ({}, 'product_{}', {})",
            i, i, i as f64 * 10.0
        ))?;
    }

    // Get database statistics
    println!("\n=== Database Statistics ===");
    println!("Tables: {:?}", db.list_tables());

    if let Ok(stats) = db.table_stats("users") {
        println!("{}", stats);
    }

    if let Ok(stats) = db.table_stats("products") {
        println!("{}", stats);
    }

    Ok(())
}
```

---

## 📖 API Documentation

### Core Types

#### `InMemoryDB`

The main database facade providing a simple API.

```rust
pub struct InMemoryDB { /* private fields */ }

impl InMemoryDB {
    /// Create a new empty database
    pub fn new() -> Self;

    /// Get the global database instance (singleton)
    pub fn global() -> &'static Arc<RwLock<InMemoryDB>>;

    /// Execute a SQL statement (returns QueryResult for all statement types)
    pub fn execute(&mut self, sql: &str) -> Result<QueryResult>;

    /// Check if a table exists
    pub fn table_exists(&self, name: &str) -> bool;

    /// List all table names
    pub fn list_tables(&self) -> Vec<String>;

    /// Get statistics for a table
    pub fn table_stats(&self, name: &str) -> Result<TableStats>;
}
```

#### `Client`

PostgreSQL/MySQL-style client API with connection pooling.

```rust
pub struct Client { /* private fields */ }

impl Client {
    /// Connect with username and password
    pub fn connect(username: &str, password: &str) -> Result<Self>;

    /// Connect using connection URL
    /// Format: "rustmemodb://username:password@localhost"
    pub fn connect_url(url: &str) -> Result<Self>;

    /// Execute a SQL statement (UPDATE/DELETE/INSERT/CREATE/DROP)
    pub fn execute(&self, sql: &str) -> Result<QueryResult>;

    /// Execute a query (SELECT)
    pub fn query(&self, sql: &str) -> Result<QueryResult>;

    /// Get the authentication manager
    pub fn auth_manager(&self) -> Arc<AuthManager>;
}
```

#### `QueryResult`

Result of a query execution.

```rust
pub struct QueryResult {
    columns: Vec<String>,
    rows: Vec<Row>,
    affected_rows: Option<usize>,
}

impl QueryResult {
    /// Get column names
    pub fn columns(&self) -> &[String];

    /// Get rows
    pub fn rows(&self) -> &[Row];

    /// Get number of rows
    pub fn row_count(&self) -> usize;

    /// Get number of affected rows (for UPDATE/DELETE)
    pub fn affected_rows(&self) -> Option<usize>;

    /// Print formatted result to stdout
    pub fn print(&self);
}
```

#### `Value`

Represents a SQL value.

```rust
pub enum Value {
    Null,
    Integer(i64),
    Float(f64),
    Text(String),
    Boolean(bool),
}
```

#### `DataType`

Column data type.

```rust
pub enum DataType {
    Integer,
    Float,
    Text,
    Boolean,
}
```

### Error Handling

All operations return `Result<T, DbError>`:

```rust
pub enum DbError {
    ParseError(String),
    TableExists(String),
    TableNotFound(String),
    ColumnNotFound(String, String),
    TypeMismatch(String),
    ConstraintViolation(String),
    ExecutionError(String),
    UnsupportedOperation(String),
    LockError(String),
}
```

---

## ⚡ Performance Characteristics

### Time Complexity

| Operation | Complexity | Notes |
|-----------|-----------|-------|
| CREATE TABLE | O(n) | Clones entire catalog (n = tables) |
| DROP TABLE | O(1) | HashMap removal |
| INSERT | O(1) | Amortized vector push |
| UPDATE | O(n) | n = rows in table (full scan) |
| DELETE | O(n + m log m) | n = scan, m = matches to delete |
| SELECT (full scan) | O(n) | n = rows in table |
| SELECT (with WHERE) | O(n) | No indexes yet |
| SELECT (with ORDER BY) | O(n log n) | Stable sort |
| SELECT (with LIMIT) | O(n) | Must scan before limiting |
| SELECT (with aggregates) | O(n) | Single-pass computation |

### Space Complexity

| Structure | Space | Notes |
|-----------|-------|-------|
| Row | O(columns) | Vector of values |
| Table | O(rows × columns) | Vector of rows |
| Catalog | O(tables × columns) | Metadata only |

### Concurrency

- **Catalog Reads**: Lock-free (Copy-on-Write via Arc)
- **Table Reads**: Multiple concurrent readers (RwLock)
- **Table Writes**: Exclusive lock per table
- **Cross-Table**: Different tables can be accessed concurrently

### Benchmark Results

```
Concurrent reads (different tables): ~145ms
Operations: 800 SELECTs
Throughput: ~5,500 ops/sec

Mixed read/write (different tables): ~85ms
Operations: 400 SELECTs + 100 INSERTs
```

*Note: Benchmarks run on M1 Mac, results vary by hardware*

---

## 🎨 Design Patterns

RustMemDB demonstrates several classic software design patterns:

### 1. **Facade Pattern** (`InMemoryDB`)
Provides a simple interface to a complex subsystem.

```rust
// Simple facade hides parser, planner, executor complexity
db.execute("SELECT * FROM users")?;
```

### 2. **Chain of Responsibility** (`ExecutorPipeline`)
Each executor decides if it can handle a statement.

```rust
for executor in &self.executors {
    if executor.can_handle(stmt) {
        return executor.execute(stmt, ctx);
    }
}
```

### 3. **Strategy Pattern** (`QueryPlanner`, Executors)
Different strategies for different statement types.

### 4. **Plugin/Registry Pattern** (Expression Evaluators)
Extensible evaluation system.

```rust
registry.register(Box::new(ArithmeticEvaluator));
registry.register(Box::new(ComparisonEvaluator));
// Users can add custom evaluators
```

### 5. **Adapter Pattern** (`SqlParserAdapter`)
Adapts external sqlparser API to internal AST.

### 6. **Copy-on-Write** (`Catalog`)
Immutable data structure for lock-free reads.

### 7. **Builder Pattern** (Logical Plan construction)
Composable query plans.

---

## 🔧 Extensibility

RustMemDB uses a **plugin-based architecture** that makes it easy to add new SQL operators, functions, and statement types without modifying the core engine.

### Developer Guide

📚 **See [DEVELOPER_GUIDE.md](docs/DEVELOPER_GUIDE.md) for comprehensive instructions on:**

- Understanding the two plugin systems (conversion + evaluation)
- Adding new SQL operators and functions (step-by-step)
- Adding new statement types (e.g., CREATE INDEX)
- Best practices and common pitfalls
- Testing guidelines
- Complete working examples

### Quick Example: Adding UPPER() Function

**Step 1: Create Conversion Plugin** (`src/plugins/string_functions.rs`)
```rust
impl ExpressionPlugin for StringFunctionPlugin {
    fn convert(&self, expr: sql_ast::Expr, converter: &ExpressionConverter) -> Result<Expr> {
        // Convert SQL UPPER() to internal AST
        Ok(Expr::Function { name: "UPPER".to_string(), args })
    }
}
```

**Step 2: Create Evaluation Plugin** (`src/evaluator/plugins/string_functions.rs`)
```rust
impl ExpressionEvaluator for StringFunctionEvaluator {
    fn evaluate(&self, expr: &Expr, row: &Row, schema: &Schema, context: &EvaluationContext) -> Result<Value> {
        // Execute UPPER() at runtime
        match value {
            Value::Text(s) => Ok(Value::Text(s.to_uppercase())),
            _ => Err(DbError::TypeMismatch(/* ... */))
        }
    }
}
```

**Step 3: Register Both Plugins**
```rust
// In src/plugins/mod.rs
registry.register(Box::new(StringFunctionPlugin));

// In src/evaluator/plugins/mod.rs
registry.register(Box::new(StringFunctionEvaluator));
```

That's it! Now you can use `SELECT UPPER(name) FROM users`.

For detailed instructions, examples, and best practices, see [DEVELOPER_GUIDE.md](docs/DEVELOPER_GUIDE.md).

---

## ⚠️ Limitations

### Current Limitations

❌ **No JOINs** - Single table queries only
❌ **No GROUP BY/HAVING** - Aggregates work on full result set only
❌ **No FOREIGN KEY constraints** - Referential integrity not enforced
❌ **No views** - No CREATE VIEW
❌ **Limited SQL** - Subset of SQL-92
❌ **No query optimization** - Plans not optimized (basic index usage only)
❌ **Single process** - No client-server architecture

### What We Have ✅

✅ **Transactions** - Full ACID transaction support with MVCC
✅ **Connection Pooling** - Efficient connection management
✅ **User Authentication** - Secure password hashing with bcrypt
✅ **Concurrent Access** - Fine-grained locking for multiple connections
✅ **Manual Rollback** - Safety via explicit `close()` or `rollback()` on drop warning
✅ **Indexes** - B-Tree indexes for fast lookups
✅ **Persistence** - Write-Ahead Log (WAL) and Snapshots

### Known Issues

See [CODE_REVIEW_REPORT.md](docs/CODE_REVIEW_REPORT.md) for detailed issue analysis.

**Critical:**
- Float comparison uses fixed epsilon (incorrect for large numbers)
- Benchmarks use write locks instead of read locks
- Silent error swallowing in sort comparisons

**High:**
- Catalog clones entire HashMap on schema changes
- Transaction system exists but not integrated

---

## 🗺️ Roadmap

### Phase 1: Stability ✅ (Completed)
- [x] Basic SELECT, INSERT, CREATE TABLE
- [x] WHERE clause with complex predicates
- [x] ORDER BY with multiple columns
- [x] Plugin-based architecture
- [x] DROP TABLE support
- [x] UPDATE and DELETE statements
- [x] Aggregate functions (COUNT, SUM, AVG, MIN, MAX)
- [x] Client API and connection pooling
- [x] User management system
- [x] Comprehensive test coverage (380+ passing tests)
- [x] Performance benchmarks (load tests)
- [x] Password hashing with bcrypt
- [x] **Transaction support (BEGIN, COMMIT, ROLLBACK)**
- [x] **MVCC with snapshot isolation**
- [x] **Basic Indexes (CREATE INDEX)**
- [x] **Persistence (WAL + Snapshots)**

### Phase 2: Core Features (Current)
- [ ] GROUP BY and HAVING
- [ ] Subqueries
- [ ] Fix remaining bugs from code review
- [ ] `ALTER TABLE` full support

### Phase 3: Advanced Features
- [ ] INNER JOIN support
- [ ] LEFT/RIGHT JOIN support
- [ ] Query optimizer (predicate pushdown, join ordering)
- [ ] Secondary indexes (optimization)
- [ ] Views (CREATE VIEW)
- [ ] Constraints (PRIMARY KEY, FOREIGN KEY, UNIQUE)

### Phase 4: Production Readiness (Future)
- [ ] Query caching
- [ ] SQL-92 compliance

### Phase 5: Ecosystem
- [ ] Client-server architecture
- [ ] Wire protocol
- [ ] Language bindings (Python, JavaScript)
- [ ] SQL shell/REPL
- [ ] Migration tools
- [ ] Performance profiling tools

---

## 🤝 Contributing

Contributions are welcome! This is an educational project, so clear, well-documented code is more valuable than clever optimizations.

### Developer Resources

📚 **New to the codebase?** Start with these guides:
- **[DEVELOPER_GUIDE.md]docs/DEVELOPER_GUIDE.md** - Complete guide to adding new features
- **[PRODUCTION_READINESS_ANALYSIS.md]docs/PRODUCTION_READINESS_ANALYSIS.md** - Architecture analysis and known issues
- **[CODE_REVIEW_REPORT.md]docs/CODE_REVIEW_REPORT.md** - Detailed code review findings

### How to Contribute

1. **Read [DEVELOPER_GUIDE.md]docs/DEVELOPER_GUIDE.md** for architecture overview
2. **Fork the repository**
3. **Create a feature branch** (`git checkout -b feature/amazing-feature`)
4. **Write tests** for your changes
5. **Ensure all tests pass** (`cargo test`)
6. **Run clippy** (`cargo clippy -- -D warnings`)
7. **Format code** (`cargo fmt`)
8. **Commit changes** (`git commit -m 'Add amazing feature'`)
9. **Push to branch** (`git push origin feature/amazing-feature`)
10. **Open a Pull Request**

### Development Guidelines

- **Code Clarity** > Performance (unless critical path)
- **Add tests** for all new features (see [DEVELOPER_GUIDE.md]docs/DEVELOPER_GUIDE.md for test checklist)
- **Document public APIs** with `///` comments
- **Follow Rust conventions** (cargo fmt, clippy)
- **Update README** if adding user-facing features
- **Update DEVELOPER_GUIDE.md** if changing plugin architecture
- **Reference issues** in commits when applicable

### Good First Issues

Looking to contribute? Try these:

- **CRITICAL**: Implement password hashing (bcrypt/argon2) to replace plaintext storage
- Add missing documentation comments
- Implement GROUP BY and HAVING clauses
- Add more expression evaluators (string functions, date functions)
- Improve error messages
- Add more integration tests
- Fix issues from CODE_REVIEW_REPORT.md

---

## 📚 Educational Resources

### Understanding the Code

1. **Start Here**: Read `src/main.rs` for a complete example
2. **Architecture**: Review the architecture diagram above
3. **Query Flow**: Follow a query through parser → planner → executor
4. **Tests**: Read tests in `src/executor/query.rs` for examples

### Learning Database Internals

**Recommended Reading:**
- "Database Internals" by Alex Petrov
- "Database System Concepts" by Silberschatz, Korth, Sudarshan
- "Architecture of a Database System" (Hellerstein, Stonebraker, Hamilton)
- CMU Database Systems Course (free online)

**Related Projects:**
- [SQLite]https://www.sqlite.org/ - Simple, embedded SQL database
- [DuckDB]https://duckdb.org/ - In-process OLAP database
- [ToyDB]https://github.com/erikgrinaker/toydb - Educational distributed SQL database in Rust

### Rust Resources

- [The Rust Book]https://doc.rust-lang.org/book/
- [Rust by Example]https://doc.rust-lang.org/rust-by-example/
- [Rust Design Patterns]https://rust-unofficial.github.io/patterns/

---

## 📝 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

---

## 🙏 Acknowledgments

- **sqlparser-rs** - SQL parsing library
- **Rust Community** - Excellent documentation and tools
- **Database Research** - Decades of academic research in database systems

---

## 📧 Contact

- **GitHub Issues**: For bugs and feature requests
- **Discussions**: For questions and ideas
- **Pull Requests**: For contributions

---

## ⭐ Star History

If you find this project useful for learning, please consider giving it a star!

---

**Built with ❤️ in Rust**