velocidb 0.1.0

A high-performance SQLite reimplementation in Rust optimized for modern hardware
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
// SQL Parser

use crate::types::{Column, DataType, Result, Value, VelociError};
use regex::Regex;
use std::collections::HashMap;

#[derive(Debug, Clone, PartialEq)]
pub enum Statement {
    CreateTable {
        name: String,
        columns: Vec<Column>,
    },
    DropTable {
        name: String,
    },
    Insert {
        table: String,
        columns: Option<Vec<String>>,
        values: Vec<Value>,
    },
    Select {
        table: String,
        columns: Vec<String>,
        where_clause: Option<WhereClause>,
    },
    Update {
        table: String,
        assignments: HashMap<String, Value>,
        where_clause: Option<WhereClause>,
    },
    Delete {
        table: String,
        where_clause: Option<WhereClause>,
    },
}

#[derive(Debug, Clone, PartialEq)]
pub struct WhereClause {
    pub conditions: Vec<Condition>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Condition {
    pub column: String,
    pub operator: Operator,
    pub value: Value,
}

#[derive(Debug, Clone, PartialEq)]
pub enum Operator {
    Equal,
    NotEqual,
    GreaterThan,
    LessThan,
    GreaterThanOrEqual,
    LessThanOrEqual,
    Like,
}

impl Operator {
    pub fn from_str(s: &str) -> Result<Self> {
        match s {
            "=" => Ok(Operator::Equal),
            "!=" | "<>" => Ok(Operator::NotEqual),
            ">" => Ok(Operator::GreaterThan),
            "<" => Ok(Operator::LessThan),
            ">=" => Ok(Operator::GreaterThanOrEqual),
            "<=" => Ok(Operator::LessThanOrEqual),
            "LIKE" => Ok(Operator::Like),
            _ => Err(VelociError::ParseError(format!("Unknown operator: {}", s))),
        }
    }

    pub fn evaluate(&self, left: &Value, right: &Value) -> Result<bool> {
        match (self, left, right) {
            (Operator::Equal, Value::Integer(a), Value::Integer(b)) => Ok(a == b),
            (Operator::NotEqual, Value::Integer(a), Value::Integer(b)) => Ok(a != b),
            (Operator::GreaterThan, Value::Integer(a), Value::Integer(b)) => Ok(a > b),
            (Operator::LessThan, Value::Integer(a), Value::Integer(b)) => Ok(a < b),
            (Operator::GreaterThanOrEqual, Value::Integer(a), Value::Integer(b)) => Ok(a >= b),
            (Operator::LessThanOrEqual, Value::Integer(a), Value::Integer(b)) => Ok(a <= b),
            
            (Operator::Equal, Value::Text(a), Value::Text(b)) => Ok(a == b),
            (Operator::NotEqual, Value::Text(a), Value::Text(b)) => Ok(a != b),
            (Operator::Like, Value::Text(a), Value::Text(pattern)) => {
                let regex_pattern = pattern
                    .replace("%", ".*")
                    .replace("_", ".");
                let regex = Regex::new(&format!("^{}$", regex_pattern))
                    .map_err(|e| VelociError::ParseError(format!("Invalid LIKE pattern: {}", e)))?;
                Ok(regex.is_match(a))
            }
            
            (Operator::Equal, Value::Null, Value::Null) => Ok(true),
            (Operator::NotEqual, Value::Null, _) | (Operator::NotEqual, _, Value::Null) => Ok(true),
            _ => Err(VelociError::TypeMismatch {
                expected: format!("{:?}", right),
                actual: format!("{:?}", left),
            }),
        }
    }
}

pub struct Parser {
    // Parser state can be added here if needed
}

impl Parser {
    pub fn new() -> Self {
        Self {}
    }

    pub fn parse(&self, sql: &str) -> Result<Statement> {
        let sql = sql.trim();
        let upper = sql.to_uppercase();

        if upper.starts_with("CREATE TABLE") {
            self.parse_create_table(sql)
        } else if upper.starts_with("DROP TABLE") {
            self.parse_drop_table(sql)
        } else if upper.starts_with("INSERT INTO") {
            self.parse_insert(sql)
        } else if upper.starts_with("SELECT") {
            self.parse_select(sql)
        } else if upper.starts_with("UPDATE") {
            self.parse_update(sql)
        } else if upper.starts_with("DELETE FROM") {
            self.parse_delete(sql)
        } else {
            Err(VelociError::ParseError(format!(
                "Unsupported statement: {}",
                sql
            )))
        }
    }

    fn parse_create_table(&self, sql: &str) -> Result<Statement> {
        // CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)
        let re = Regex::new(r"(?i)CREATE\s+TABLE\s+(\w+)\s*\((.+)\)")
            .map_err(|e| VelociError::ParseError(format!("Regex error: {}", e)))?;

        let captures = re
            .captures(sql)
            .ok_or_else(|| VelociError::ParseError("Invalid CREATE TABLE syntax".to_string()))?;

        let table_name = captures.get(1).unwrap().as_str().to_string();
        let columns_str = captures.get(2).unwrap().as_str();

        let mut columns = Vec::new();
        for col_def in columns_str.split(',') {
            let col_def = col_def.trim();
            if col_def.is_empty() {
                continue;
            }

            // Parse column name (handle quoted identifiers)
            let (col_name, remainder) = self.parse_identifier(col_def)?;

            // Parse data type and constraints
            let remainder = remainder.trim();
            if remainder.is_empty() {
                return Err(VelociError::ParseError(format!(
                    "Missing data type for column '{}'",
                    col_name
                )));
            }

            // Split remainder into parts, handling quoted strings
            let parts = self.split_sql_parts(remainder);
            if parts.is_empty() {
                return Err(VelociError::ParseError(format!(
                    "Invalid column definition: {}",
                    col_def
                )));
            }

            let data_type = DataType::from_str(&parts[0]);
            let mut primary_key = false;
            let mut not_null = false;
            let mut unique = false;

            // Check for constraints
            let upper_parts: Vec<String> = parts.iter().map(|s| s.to_uppercase()).collect();
            if upper_parts.contains(&"PRIMARY".to_string())
                && upper_parts.contains(&"KEY".to_string())
            {
                primary_key = true;
                not_null = true;
            }
            if upper_parts.contains(&"NOT".to_string())
                && upper_parts.contains(&"NULL".to_string())
            {
                not_null = true;
            }
            if upper_parts.contains(&"UNIQUE".to_string()) {
                unique = true;
            }

            columns.push(Column {
                name: col_name,
                data_type,
                primary_key,
                not_null,
                unique,
            });
        }

        Ok(Statement::CreateTable {
            name: table_name,
            columns,
        })
    }

    fn parse_drop_table(&self, sql: &str) -> Result<Statement> {
        // DROP TABLE users
        let re = Regex::new(r"(?i)DROP\s+TABLE\s+(\w+)")
            .map_err(|e| VelociError::ParseError(format!("Regex error: {}", e)))?;

        let captures = re
            .captures(sql)
            .ok_or_else(|| VelociError::ParseError("Invalid DROP TABLE syntax".to_string()))?;

        let table_name = captures.get(1).unwrap().as_str().to_string();

        Ok(Statement::DropTable { name: table_name })
    }

    fn parse_insert(&self, sql: &str) -> Result<Statement> {
        // INSERT INTO users (id, name, age) VALUES (1, 'Alice', 30)
        // INSERT INTO users VALUES (1, 'Alice', 30)
        
        let re = Regex::new(r"(?i)INSERT\s+INTO\s+(\w+)(?:\s*\(([^)]+)\))?\s+VALUES\s*\(([^)]+)\)")
            .map_err(|e| VelociError::ParseError(format!("Regex error: {}", e)))?;

        let captures = re
            .captures(sql)
            .ok_or_else(|| VelociError::ParseError("Invalid INSERT syntax".to_string()))?;

        let table_name = captures.get(1).unwrap().as_str().to_string();
        
        let columns = captures.get(2).map(|m| {
            m.as_str()
                .split(',')
                .map(|s| s.trim().to_string())
                .collect()
        });

        let values_str = captures.get(3).unwrap().as_str();
        let values = self.parse_values(values_str)?;

        Ok(Statement::Insert {
            table: table_name,
            columns,
            values,
        })
    }

    fn parse_select(&self, sql: &str) -> Result<Statement> {
        // SELECT * FROM users WHERE age > 25
        // SELECT id, name FROM users
        
        let re = Regex::new(r"(?i)SELECT\s+(.+?)\s+FROM\s+(\w+)(?:\s+WHERE\s+(.+))?")
            .map_err(|e| VelociError::ParseError(format!("Regex error: {}", e)))?;

        let captures = re
            .captures(sql)
            .ok_or_else(|| VelociError::ParseError("Invalid SELECT syntax".to_string()))?;

        let columns_str = captures.get(1).unwrap().as_str().trim();
        let columns = if columns_str == "*" {
            vec!["*".to_string()]
        } else {
            columns_str
                .split(',')
                .map(|s| s.trim().to_string())
                .collect()
        };

        let table_name = captures.get(2).unwrap().as_str().to_string();

        let where_clause = if let Some(where_match) = captures.get(3) {
            Some(self.parse_where_clause(where_match.as_str())?)
        } else {
            None
        };

        Ok(Statement::Select {
            table: table_name,
            columns,
            where_clause,
        })
    }

    fn parse_update(&self, sql: &str) -> Result<Statement> {
        // UPDATE users SET age = 31 WHERE name = 'Alice'
        
        let re = Regex::new(r"(?i)UPDATE\s+(\w+)\s+SET\s+(.+?)(?:\s+WHERE\s+(.+))?$")
            .map_err(|e| VelociError::ParseError(format!("Regex error: {}", e)))?;

        let captures = re
            .captures(sql)
            .ok_or_else(|| VelociError::ParseError("Invalid UPDATE syntax".to_string()))?;

        let table_name = captures.get(1).unwrap().as_str().to_string();
        let assignments_str = captures.get(2).unwrap().as_str();

        let mut assignments = HashMap::new();
        for assignment in assignments_str.split(',') {
            let parts: Vec<&str> = assignment.split('=').collect();
            if parts.len() != 2 {
                return Err(VelociError::ParseError(format!(
                    "Invalid assignment: {}",
                    assignment
                )));
            }

            let column = parts[0].trim().to_string();
            let value = self.parse_value(parts[1].trim())?;
            assignments.insert(column, value);
        }

        let where_clause = if let Some(where_match) = captures.get(3) {
            Some(self.parse_where_clause(where_match.as_str())?)
        } else {
            None
        };

        Ok(Statement::Update {
            table: table_name,
            assignments,
            where_clause,
        })
    }

    fn parse_delete(&self, sql: &str) -> Result<Statement> {
        // DELETE FROM users WHERE id = 2
        
        let re = Regex::new(r"(?i)DELETE\s+FROM\s+(\w+)(?:\s+WHERE\s+(.+))?")
            .map_err(|e| VelociError::ParseError(format!("Regex error: {}", e)))?;

        let captures = re
            .captures(sql)
            .ok_or_else(|| VelociError::ParseError("Invalid DELETE syntax".to_string()))?;

        let table_name = captures.get(1).unwrap().as_str().to_string();

        let where_clause = if let Some(where_match) = captures.get(2) {
            Some(self.parse_where_clause(where_match.as_str())?)
        } else {
            None
        };

        Ok(Statement::Delete {
            table: table_name,
            where_clause,
        })
    }

    fn parse_where_clause(&self, clause: &str) -> Result<WhereClause> {
        // Simple WHERE clause parser - supports single conditions for now
        // age > 25
        // name = 'Alice'
        
        let re = Regex::new(r"(\w+)\s*(>=|<=|!=|<>|LIKE|=|>|<)\s*(.+)")
            .map_err(|e| VelociError::ParseError(format!("Regex error: {}", e)))?;

        let captures = re
            .captures(clause)
            .ok_or_else(|| VelociError::ParseError(format!("Invalid WHERE clause: {}", clause)))?;

        let column = captures.get(1).unwrap().as_str().to_string();
        let operator_str = captures.get(2).unwrap().as_str();
        let operator = Operator::from_str(operator_str)?;
        let value = self.parse_value(captures.get(3).unwrap().as_str())?;

        Ok(WhereClause {
            conditions: vec![Condition {
                column,
                operator,
                value,
            }],
        })
    }

    fn parse_values(&self, values_str: &str) -> Result<Vec<Value>> {
        values_str
            .split(',')
            .map(|s| self.parse_value(s.trim()))
            .collect()
    }

    fn parse_value(&self, s: &str) -> Result<Value> {
        let s = s.trim();

        // NULL
        if s.to_uppercase() == "NULL" {
            return Ok(Value::Null);
        }

        // String (quoted) - handle escaped quotes
        if (s.starts_with('\'') && s.ends_with('\''))
            || (s.starts_with('"') && s.ends_with('"'))
        {
            let quote_char = s.chars().next().unwrap();
            let content = &s[1..s.len() - 1];

            // Handle escaped quotes
            let unescaped = content.replace(&format!("\\{}", quote_char), &quote_char.to_string())
                                   .replace("\\\\", "\\");

            return Ok(Value::Text(unescaped));
        }

        // Try integer
        if let Ok(i) = s.parse::<i64>() {
            return Ok(Value::Integer(i));
        }

        // Try float
        if let Ok(f) = s.parse::<f64>() {
            return Ok(Value::Float(f));
        }

        // BLOB literal (X'hexdigits' or x'hexdigits')
        if s.len() >= 3 && (s.starts_with("X'") || s.starts_with("x'")) && s.ends_with('\'') {
            let hex_part = &s[2..s.len() - 1];
            if hex_part.len() % 2 != 0 {
                return Err(VelociError::ParseError("Invalid BLOB literal: odd number of hex digits".to_string()));
            }

            let mut blob = Vec::new();
            for i in (0..hex_part.len()).step_by(2) {
                let byte_str = &hex_part[i..i + 2];
                match u8::from_str_radix(byte_str, 16) {
                    Ok(byte) => blob.push(byte),
                    Err(_) => return Err(VelociError::ParseError(format!("Invalid hex digit in BLOB: {}", byte_str))),
                }
            }
            return Ok(Value::Blob(blob));
        }

        // Default to text without quotes
        Ok(Value::Text(s.to_string()))
    }

    fn parse_identifier<'a>(&self, s: &'a str) -> Result<(String, &'a str)> {
        let s = s.trim();

        // Quoted identifier
        if s.starts_with('"') || s.starts_with('`') || s.starts_with('[') {
            let quote_char = s.chars().next().unwrap();
            let end_quote = match quote_char {
                '"' => '"',
                '`' => '`',
                '[' => ']',
                _ => return Err(VelociError::ParseError("Invalid quote character".to_string())),
            };

            let mut identifier = String::new();
            let mut escaped = false;

            // Iterate over chars with their byte positions
            let mut chars_iter = s.char_indices();
            
            // Skip the opening quote
            chars_iter.next();

            for (pos, ch) in chars_iter {
                if escaped {
                    identifier.push(ch);
                    escaped = false;
                } else if ch == '\\' {
                    escaped = true;
                } else if ch == end_quote {
                    // Calculate the remainder starting after the closing quote
                    let rest_start = pos + ch.len_utf8();
                    return Ok((identifier, &s[rest_start..]));
                } else {
                    identifier.push(ch);
                }
            }

            return Err(VelociError::ParseError("Unterminated quoted identifier".to_string()));
        }

        // Unquoted identifier (stops at first whitespace)
        if let Some(space_pos) = s.find(char::is_whitespace) {
            let (ident, rest) = s.split_at(space_pos);
            Ok((ident.to_string(), rest))
        } else {
            Ok((s.to_string(), ""))
        }
    }

    fn split_sql_parts(&self, s: &str) -> Vec<String> {
        let mut parts = Vec::new();
        let mut current = String::new();
        let mut in_string = false;
        let mut string_char = '"';
        let mut escaped = false;

        for ch in s.chars() {
            if escaped {
                current.push(ch);
                escaped = false;
            } else if ch == '\\' {
                escaped = true;
                current.push(ch);
            } else if !in_string && (ch == '"' || ch == '\'') {
                in_string = true;
                string_char = ch;
                current.push(ch);
            } else if in_string && ch == string_char {
                in_string = false;
                current.push(ch);
            } else if !in_string && ch.is_whitespace() {
                if !current.is_empty() {
                    parts.push(current);
                    current = String::new();
                }
            } else {
                current.push(ch);
            }
        }

        if !current.is_empty() {
            parts.push(current);
        }

        parts
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_create_table() {
        let parser = Parser::new();
        let stmt = parser
            .parse("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)")
            .unwrap();

        match stmt {
            Statement::CreateTable { name, columns } => {
                assert_eq!(name, "users");
                assert_eq!(columns.len(), 3);
                assert_eq!(columns[0].name, "id");
                assert!(columns[0].primary_key);
            }
            _ => panic!("Wrong statement type"),
        }
    }

    #[test]
    fn test_parse_insert() {
        let parser = Parser::new();
        let stmt = parser
            .parse("INSERT INTO users (id, name, age) VALUES (1, 'Alice', 30)")
            .unwrap();

        match stmt {
            Statement::Insert {
                table,
                columns,
                values,
            } => {
                assert_eq!(table, "users");
                assert!(columns.is_some());
                assert_eq!(values.len(), 3);
            }
            _ => panic!("Wrong statement type"),
        }
    }

    #[test]
    fn test_parse_select() {
        let parser = Parser::new();
        let stmt = parser
            .parse("SELECT * FROM users WHERE age > 25")
            .unwrap();

        match stmt {
            Statement::Select {
                table,
                columns,
                where_clause,
            } => {
                assert_eq!(table, "users");
                assert_eq!(columns, vec!["*"]);
                assert!(where_clause.is_some());
            }
            _ => panic!("Wrong statement type"),
        }
    }

    #[test]
    fn test_parse_update() {
        let parser = Parser::new();
        let stmt = parser
            .parse("UPDATE users SET age = 31 WHERE name = 'Alice'")
            .unwrap();

        match stmt {
            Statement::Update {
                table,
                assignments,
                where_clause,
            } => {
                assert_eq!(table, "users");
                assert_eq!(assignments.len(), 1);
                assert!(where_clause.is_some());
            }
            _ => panic!("Wrong statement type"),
        }
    }

    #[test]
    fn test_parse_delete() {
        let parser = Parser::new();
        let stmt = parser.parse("DELETE FROM users WHERE id = 2").unwrap();

        match stmt {
            Statement::Delete {
                table,
                where_clause,
            } => {
                assert_eq!(table, "users");
                assert!(where_clause.is_some());
            }
            _ => panic!("Wrong statement type"),
        }
    }
}