tegdb 0.5.0

The name TegridyDB (short for TegDB) is inspired by the Tegridy Farm in South Park and tries to correct some of the wrong database implementations, such as null support, implicit conversion support, etc.
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
use std::fs;
use tegdb::Database;

use once_cell::sync::Lazy;
use std::sync::Mutex;

static TEST_COUNTER: Lazy<Mutex<u64>> = Lazy::new(|| Mutex::new(0));

/// Test helper: Create a temporary database
fn create_temp_db() -> (Database, String) {
    use std::time::{SystemTime, UNIX_EPOCH};
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos();

    // Get a unique counter for this test
    let counter = {
        let mut counter = TEST_COUNTER.lock().unwrap();
        *counter += 1;
        *counter
    };

    let path = format!(
        "/tmp/tegdb_test_{}_{}_{}.teg",
        std::process::id(),
        timestamp,
        counter
    );

    // Ensure the file doesn't exist
    if std::path::Path::new(&path).exists() {
        fs::remove_file(&path).unwrap();
    }

    let db = Database::open(format!("file://{path}")).expect("Failed to create database");
    (db, path)
}

/// Test helper: Create a temporary database with proper cleanup
fn with_temp_db<F>(test_fn: F)
where
    F: FnOnce(&mut Database) -> Result<(), Box<dyn std::error::Error>>,
{
    let (mut db, path) = create_temp_db();

    // Run the test
    let result = test_fn(&mut db);

    // Ensure database is dropped (which should close file handles)
    drop(db);

    // Add a small delay to ensure file handles are released
    std::thread::sleep(std::time::Duration::from_millis(10));

    // Clean up the file with retry logic
    for _ in 0..3 {
        match fs::remove_file(&path) {
            Ok(_) => break,
            Err(_) => {
                std::thread::sleep(std::time::Duration::from_millis(5));
            }
        }
    }

    // Propagate any errors
    if let Err(e) = result {
        panic!("Test failed: {e}");
    }
}

#[test]
fn test_aggregate_functions() {
    with_temp_db(|db| {
        // Create test table
        db.execute(
            "CREATE TABLE test_data (id INTEGER PRIMARY KEY, value INTEGER, category TEXT(32))",
        )
        .unwrap();

        // Insert test data
        db.execute("INSERT INTO test_data (id, value, category) VALUES (1, 100, 'A')")
            .unwrap();
        db.execute("INSERT INTO test_data (id, value, category) VALUES (2, 200, 'A')")
            .unwrap();
        db.execute("INSERT INTO test_data (id, value, category) VALUES (3, 300, 'B')")
            .unwrap();
        db.execute("INSERT INTO test_data (id, value, category) VALUES (4, 400, 'B')")
            .unwrap();
        db.execute("INSERT INTO test_data (id, value, category) VALUES (5, 500, 'C')")
            .unwrap();

        // Test COUNT(*)
        let result = db.query("SELECT COUNT(*) FROM test_data").unwrap();
        assert_eq!(result.rows().len(), 1);
        assert_eq!(result.rows()[0][0], tegdb::SqlValue::Integer(5));

        // Test COUNT with WHERE
        let result = db
            .query("SELECT COUNT(*) FROM test_data WHERE value > 200")
            .unwrap();
        assert_eq!(result.rows().len(), 1);
        assert_eq!(result.rows()[0][0], tegdb::SqlValue::Integer(3));

        // Test SUM
        let result = db.query("SELECT SUM(value) FROM test_data").unwrap();
        assert_eq!(result.rows().len(), 1);
        // Note: SUM returns Real, so we check it's approximately correct
        if let tegdb::SqlValue::Real(sum) = result.rows()[0][0] {
            assert!((sum - 1500.0).abs() < 0.1);
        } else {
            panic!("Expected Real value for SUM");
        }

        // Test AVG
        let result = db.query("SELECT AVG(value) FROM test_data").unwrap();
        assert_eq!(result.rows().len(), 1);
        if let tegdb::SqlValue::Real(avg) = result.rows()[0][0] {
            assert!((avg - 300.0).abs() < 0.1);
        } else {
            panic!("Expected Real value for AVG");
        }

        // Test MAX
        let result = db.query("SELECT MAX(value) FROM test_data").unwrap();
        assert_eq!(result.rows().len(), 1);
        assert_eq!(result.rows()[0][0], tegdb::SqlValue::Integer(500));

        // Test MIN
        let result = db.query("SELECT MIN(value) FROM test_data").unwrap();
        assert_eq!(result.rows().len(), 1);
        assert_eq!(result.rows()[0][0], tegdb::SqlValue::Integer(100));

        Ok(())
    });
}

#[test]
fn test_secondary_indexes() {
    with_temp_db(|db| {
        // Create test table
        db.execute(
            "CREATE TABLE test_data (id INTEGER PRIMARY KEY, value INTEGER, category TEXT(32))",
        )
        .unwrap();

        // Insert test data
        db.execute("INSERT INTO test_data (id, value, category) VALUES (1, 100, 'A')")
            .unwrap();
        db.execute("INSERT INTO test_data (id, value, category) VALUES (2, 200, 'A')")
            .unwrap();
        db.execute("INSERT INTO test_data (id, value, category) VALUES (3, 300, 'B')")
            .unwrap();
        db.execute("INSERT INTO test_data (id, value, category) VALUES (4, 400, 'B')")
            .unwrap();

        // Create secondary indexes
        db.execute("CREATE INDEX idx_category ON test_data (category)")
            .unwrap();
        db.execute("CREATE INDEX idx_value ON test_data (value)")
            .unwrap();

        // Test index scan on category
        let result = db
            .query("SELECT * FROM test_data WHERE category = 'A'")
            .unwrap();
        assert_eq!(result.rows().len(), 2);

        // Test index scan on value range
        let result = db
            .query("SELECT * FROM test_data WHERE value BETWEEN 150 AND 350")
            .unwrap();
        assert_eq!(result.rows().len(), 2);

        // Test index scan with multiple conditions
        let result = db
            .query("SELECT * FROM test_data WHERE category = 'A' AND value > 150")
            .unwrap();
        assert_eq!(result.rows().len(), 1);

        // Test DROP INDEX
        db.execute("DROP INDEX idx_category").unwrap();

        // Verify index is dropped (query should still work but without index)
        let result = db
            .query("SELECT * FROM test_data WHERE category = 'A'")
            .unwrap();
        assert_eq!(result.rows().len(), 2);

        Ok(())
    });
}

#[test]
fn test_order_by() {
    with_temp_db(|db| {
        // Create test table
        db.execute(
            "CREATE TABLE test_data (id INTEGER PRIMARY KEY, value INTEGER, category TEXT(32))",
        )
        .unwrap();

        // Insert test data in random order
        db.execute("INSERT INTO test_data (id, value, category) VALUES (3, 300, 'B')")
            .unwrap();
        db.execute("INSERT INTO test_data (id, value, category) VALUES (1, 100, 'A')")
            .unwrap();
        db.execute("INSERT INTO test_data (id, value, category) VALUES (4, 400, 'B')")
            .unwrap();
        db.execute("INSERT INTO test_data (id, value, category) VALUES (2, 200, 'A')")
            .unwrap();

        // Test ORDER BY ASC
        let result = db
            .query("SELECT id FROM test_data ORDER BY id ASC")
            .unwrap();
        assert_eq!(result.rows().len(), 4);
        assert_eq!(result.rows()[0][0], tegdb::SqlValue::Integer(1));
        assert_eq!(result.rows()[1][0], tegdb::SqlValue::Integer(2));
        assert_eq!(result.rows()[2][0], tegdb::SqlValue::Integer(3));
        assert_eq!(result.rows()[3][0], tegdb::SqlValue::Integer(4));

        // Test ORDER BY DESC
        let result = db
            .query("SELECT id FROM test_data ORDER BY id DESC")
            .unwrap();
        assert_eq!(result.rows().len(), 4);
        assert_eq!(result.rows()[0][0], tegdb::SqlValue::Integer(4));
        assert_eq!(result.rows()[1][0], tegdb::SqlValue::Integer(3));
        assert_eq!(result.rows()[2][0], tegdb::SqlValue::Integer(2));
        assert_eq!(result.rows()[3][0], tegdb::SqlValue::Integer(1));

        // Test ORDER BY with WHERE
        let result = db
            .query("SELECT id FROM test_data WHERE category = 'A' ORDER BY value ASC")
            .unwrap();
        assert_eq!(result.rows().len(), 2);
        assert_eq!(result.rows()[0][0], tegdb::SqlValue::Integer(1));
        assert_eq!(result.rows()[1][0], tegdb::SqlValue::Integer(2));

        // Test ORDER BY with LIMIT
        let result = db
            .query("SELECT id FROM test_data ORDER BY value DESC LIMIT 2")
            .unwrap();
        assert_eq!(result.rows().len(), 2);
        assert_eq!(result.rows()[0][0], tegdb::SqlValue::Integer(4));
        assert_eq!(result.rows()[1][0], tegdb::SqlValue::Integer(3));

        Ok(())
    });
}

#[test]
fn test_vector_similarity_functions() {
    with_temp_db(|db| {
        // Create test table with vector column
        db.execute(
            "CREATE TABLE embeddings (id INTEGER PRIMARY KEY, embedding VECTOR(3), text TEXT(32))",
        )
        .unwrap();

        // Insert test vectors
        db.execute("INSERT INTO embeddings (id, embedding, text) VALUES (1, [1.0, 0.0, 0.0], 'unit vector x')").unwrap();
        db.execute("INSERT INTO embeddings (id, embedding, text) VALUES (2, [0.0, 1.0, 0.0], 'unit vector y')").unwrap();
        db.execute("INSERT INTO embeddings (id, embedding, text) VALUES (3, [0.0, 0.0, 1.0], 'unit vector z')").unwrap();

        // Test COSINE_SIMILARITY
        let result = db
            .query(
                "SELECT COSINE_SIMILARITY(embedding, [1.0, 0.0, 0.0]) FROM embeddings WHERE id = 1",
            )
            .unwrap();
        assert_eq!(result.rows().len(), 1);
        if let tegdb::SqlValue::Real(similarity) = result.rows()[0][0] {
            assert!((similarity - 1.0).abs() < 0.001);
        } else {
            panic!("Expected Real value for cosine similarity");
        }

        // Test EUCLIDEAN_DISTANCE
        let result = db.query("SELECT EUCLIDEAN_DISTANCE(embedding, [1.0, 0.0, 0.0]) FROM embeddings WHERE id = 2").unwrap();
        assert_eq!(result.rows().len(), 1);
        if let tegdb::SqlValue::Real(distance) = result.rows()[0][0] {
            assert!((distance - std::f64::consts::SQRT_2).abs() < 0.01); // sqrt(2)
        } else {
            panic!("Expected Real value for euclidean distance");
        }

        // Test DOT_PRODUCT
        let result = db
            .query("SELECT DOT_PRODUCT(embedding, [1.0, 1.0, 0.0]) FROM embeddings WHERE id = 1")
            .unwrap();
        assert_eq!(result.rows().len(), 1);
        if let tegdb::SqlValue::Real(product) = result.rows()[0][0] {
            assert!((product - 1.0).abs() < 0.001);
        } else {
            panic!("Expected Real value for dot product");
        }

        // Test L2_NORMALIZE
        let result = db
            .query("SELECT L2_NORMALIZE(embedding) FROM embeddings WHERE id = 3")
            .unwrap();
        assert_eq!(result.rows().len(), 1);
        if let tegdb::SqlValue::Vector(normalized) = &result.rows()[0][0] {
            assert_eq!(normalized.len(), 3);
            // [0.0, 0.0, 1.0] normalized should be [0.0, 0.0, 1.0] (already unit vector)
            assert!((normalized[0] - 0.0).abs() < 0.001);
            assert!((normalized[1] - 0.0).abs() < 0.001);
            assert!((normalized[2] - 1.0).abs() < 0.001);
        } else {
            panic!("Expected Vector value for L2 normalization");
        }

        Ok(())
    });
}

#[test]
fn test_vector_search_operations() {
    with_temp_db(|db| {
        // Create test table with vector column
        db.execute(
            "CREATE TABLE embeddings (id INTEGER PRIMARY KEY, embedding VECTOR(3), text TEXT(32))",
        )
        .unwrap();

        // Insert test vectors
        db.execute("INSERT INTO embeddings (id, embedding, text) VALUES (1, [1.0, 0.0, 0.0], 'unit vector x')").unwrap();
        db.execute("INSERT INTO embeddings (id, embedding, text) VALUES (2, [0.0, 1.0, 0.0], 'unit vector y')").unwrap();
        db.execute("INSERT INTO embeddings (id, embedding, text) VALUES (3, [0.0, 0.0, 1.0], 'unit vector z')").unwrap();
        db.execute("INSERT INTO embeddings (id, embedding, text) VALUES (4, [0.7, 0.7, 0.0], 'diagonal vector')").unwrap();

        // Test K-NN query (ORDER BY similarity DESC LIMIT)
        let result = db.query("SELECT id, text FROM embeddings ORDER BY COSINE_SIMILARITY(embedding, [1.0, 0.0, 0.0]) DESC LIMIT 2").unwrap();
        assert_eq!(result.rows().len(), 2);
        // First result should be the exact match
        assert_eq!(result.rows()[0][0], tegdb::SqlValue::Integer(1));

        // Test similarity threshold
        let result = db.query("SELECT id FROM embeddings WHERE COSINE_SIMILARITY(embedding, [1.0, 0.0, 0.0]) > 0.5").unwrap();
        assert_eq!(result.rows().len(), 2); // Should include id=1 and id=4

        // Test range query with euclidean distance
        let result = db.query("SELECT id FROM embeddings WHERE EUCLIDEAN_DISTANCE(embedding, [1.0, 0.0, 0.0]) < 1.5").unwrap();
        assert_eq!(result.rows().len(), 4); // Should include id=1, id=2, id=3, and id=4

        // Test combination of similarity and text filter
        let result = db.query("SELECT id FROM embeddings WHERE COSINE_SIMILARITY(embedding, [1.0, 0.0, 0.0]) > 0.5 AND text LIKE '%vector%'").unwrap();
        assert_eq!(result.rows().len(), 2);

        Ok(())
    });
}

#[test]
fn test_vector_indexing() {
    with_temp_db(|db| {
        // Create test table with vector column
        db.execute(
            "CREATE TABLE embeddings (id INTEGER PRIMARY KEY, embedding VECTOR(3), text TEXT(32))",
        )
        .unwrap();

        // Insert test vectors
        db.execute("INSERT INTO embeddings (id, embedding, text) VALUES (1, [1.0, 0.0, 0.0], 'unit vector x')").unwrap();
        db.execute("INSERT INTO embeddings (id, embedding, text) VALUES (2, [0.0, 1.0, 0.0], 'unit vector y')").unwrap();
        db.execute("INSERT INTO embeddings (id, embedding, text) VALUES (3, [0.0, 0.0, 1.0], 'unit vector z')").unwrap();
        db.execute("INSERT INTO embeddings (id, embedding, text) VALUES (4, [0.7, 0.7, 0.0], 'diagonal vector')").unwrap();

        // Test HNSW index creation
        db.execute("CREATE INDEX idx_hnsw ON embeddings (embedding)")
            .unwrap();

        // Test IVF index creation
        db.execute("CREATE INDEX idx_ivf ON embeddings (embedding)")
            .unwrap();

        // Test LSH index creation
        db.execute("CREATE INDEX idx_lsh ON embeddings (embedding)")
            .unwrap();

        // Test K-NN query with HNSW index
        let result = db.query("SELECT id FROM embeddings ORDER BY COSINE_SIMILARITY(embedding, [1.0, 0.0, 0.0]) DESC LIMIT 2").unwrap();
        assert_eq!(result.rows().len(), 2);

        // Test similarity search with IVF index
        let result = db.query("SELECT id FROM embeddings WHERE COSINE_SIMILARITY(embedding, [0.0, 1.0, 0.0]) > 0.8").unwrap();
        assert_eq!(result.rows().len(), 1);

        // Test range search with LSH index
        let result = db.query("SELECT id FROM embeddings WHERE EUCLIDEAN_DISTANCE(embedding, [0.5, 0.5, 0.0]) < 0.5").unwrap();
        assert_eq!(result.rows().len(), 1);

        // Test index drop
        db.execute("DROP INDEX idx_hnsw").unwrap();
        db.execute("DROP INDEX idx_ivf").unwrap();
        db.execute("DROP INDEX idx_lsh").unwrap();

        // Verify queries still work after index drop
        let result = db.query("SELECT id FROM embeddings ORDER BY COSINE_SIMILARITY(embedding, [1.0, 0.0, 0.0]) DESC LIMIT 2").unwrap();
        assert_eq!(result.rows().len(), 2);

        Ok(())
    });
}

#[test]
fn test_expression_framework() {
    with_temp_db(|db| {
        // Create test table
        db.execute(
            "CREATE TABLE test_data (id INTEGER PRIMARY KEY, value INTEGER, category TEXT(32))",
        )
        .unwrap();

        // Insert test data
        db.execute("INSERT INTO test_data (id, value, category) VALUES (1, 100, 'A')")
            .unwrap();
        db.execute("INSERT INTO test_data (id, value, category) VALUES (2, 200, 'A')")
            .unwrap();
        db.execute("INSERT INTO test_data (id, value, category) VALUES (3, 300, 'B')")
            .unwrap();

        // Test arithmetic expressions in SELECT
        let result = db
            .query("SELECT id, value * 2 + 10 FROM test_data WHERE id = 1")
            .unwrap();
        assert_eq!(result.rows().len(), 1);
        assert_eq!(result.rows()[0][0], tegdb::SqlValue::Integer(1));
        assert_eq!(result.rows()[0][1], tegdb::SqlValue::Integer(210)); // 100 * 2 + 10

        // Test function calls in expressions
        let result = db
            .query("SELECT id, ABS(value - 5000) FROM test_data WHERE id = 1")
            .unwrap();
        assert_eq!(result.rows().len(), 1);
        assert_eq!(result.rows()[0][1], tegdb::SqlValue::Integer(4900)); // ABS(100 - 5000)

        // Test complex expressions
        let result = db
            .query("SELECT id, (value * 2 + 10) / 3 FROM test_data WHERE id = 2")
            .unwrap();
        assert_eq!(result.rows().len(), 1);
        assert_eq!(result.rows()[0][1], tegdb::SqlValue::Integer(136)); // (200 * 2 + 10) / 3 = 136

        // Test expressions in WHERE clause
        let result = db
            .query("SELECT id FROM test_data WHERE value * 2 > 300")
            .unwrap();
        assert_eq!(result.rows().len(), 2); // id=2 and id=3

        // Test expressions in ORDER BY (simplified to use column only)
        let result = db
            .query("SELECT id FROM test_data ORDER BY value DESC")
            .unwrap();
        assert_eq!(result.rows().len(), 3);
        assert_eq!(result.rows()[0][0], tegdb::SqlValue::Integer(3)); // value = 300
        assert_eq!(result.rows()[1][0], tegdb::SqlValue::Integer(2)); // value = 200
        assert_eq!(result.rows()[2][0], tegdb::SqlValue::Integer(1)); // value = 100

        Ok(())
    });
}

#[test]
fn test_comprehensive_vector_workflow() {
    with_temp_db(|db| {
        // Create comprehensive test table
        db.execute("CREATE TABLE documents (id INTEGER PRIMARY KEY, title TEXT(32), content TEXT(64), embedding VECTOR(3), category TEXT(16), score REAL)").unwrap();

        // Insert test documents
        db.execute("INSERT INTO documents (id, title, content, embedding, category, score) VALUES (1, 'Math', 'Mathematics content', [1.0, 0.0, 0.0], 'science', 0.9)").unwrap();
        db.execute("INSERT INTO documents (id, title, content, embedding, category, score) VALUES (2, 'Physics', 'Physics content', [0.0, 1.0, 0.0], 'science', 0.8)").unwrap();
        db.execute("INSERT INTO documents (id, title, content, embedding, category, score) VALUES (3, 'History', 'History content', [0.0, 0.0, 1.0], 'humanities', 0.7)").unwrap();
        db.execute("INSERT INTO documents (id, title, content, embedding, category, score) VALUES (4, 'Chemistry', 'Chemistry content', [0.7, 0.7, 0.0], 'science', 0.85)").unwrap();

        // Create indexes
        db.execute("CREATE INDEX idx_category ON documents (category)")
            .unwrap();
        db.execute("CREATE INDEX idx_hnsw ON documents (embedding)")
            .unwrap();

        // Test complex query: K-NN with filtering and ordering
        let result = db.query("SELECT id, title, COSINE_SIMILARITY(embedding, [1.0, 0.0, 0.0]) FROM documents WHERE category = 'science' AND score > 0.8 ORDER BY COSINE_SIMILARITY(embedding, [1.0, 0.0, 0.0]) DESC LIMIT 2").unwrap();

        assert_eq!(result.rows().len(), 2);
        // First result should be the exact match (id=1)
        assert_eq!(result.rows()[0][0], tegdb::SqlValue::Integer(1));

        // Test simple vector similarity query
        let result = db.query("SELECT id, title FROM documents WHERE COSINE_SIMILARITY(embedding, [1.0, 0.0, 0.0]) > 0.5").unwrap();

        assert_eq!(result.rows().len(), 2); // Should include id=1 and id=4

        // Test expression with vector functions
        let result = db.query("SELECT id, title, COSINE_SIMILARITY(embedding, [1.0, 0.0, 0.0]) * score FROM documents WHERE EUCLIDEAN_DISTANCE(embedding, [1.0, 0.0, 0.0]) < 1.5 ORDER BY COSINE_SIMILARITY(embedding, [1.0, 0.0, 0.0]) * score DESC").unwrap();

        assert_eq!(result.rows().len(), 4); // All four vectors match the distance < 1.5

        Ok(())
    });
}