absurder-sql 0.1.23

AbsurderSQL - SQLite + IndexedDB that's absurdly better than absurd-sql
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
//! TDD tests for VFS write buffering optimization
//!
//! Goal: Beat absurd-sql's 5.9ms INSERT performance by implementing lock-based write buffering
//!
//! Key insight from absurd-sql:
//! - Transactions created on xLock and stored in global Map
//! - Multiple xWrite calls reuse SAME IndexedDB transaction
//! - Writes buffered in transaction memory (NOT committed)
//! - Transaction only commits on xUnlock(NONE)
//! - All writes persisted atomically in single batch commit

#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::*;

#[cfg(target_arch = "wasm32")]
wasm_bindgen_test_configure!(run_in_browser);

#[cfg(target_arch = "wasm32")]
use absurder_sql::storage::vfs_sync::{with_global_commit_marker, with_global_storage};
#[cfg(target_arch = "wasm32")]
use absurder_sql::vfs::indexeddb_vfs::IndexedDBVFS;
#[cfg(target_arch = "wasm32")]
use absurder_sql::{ColumnValue, Database};

/// Test 1: Verify that writes during a transaction are buffered and not immediately persisted
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen_test]
async fn test_writes_are_buffered_during_transaction() {
    web_sys::console::log_1(&"=== TEST: Writes are buffered during transaction ===".into());

    let db_name = "write_buffer_test.db";

    // Clear global state
    with_global_storage(|gs| gs.borrow_mut().clear());
    with_global_commit_marker(|cm| cm.borrow_mut().clear());

    // Create VFS and register it
    let vfs = IndexedDBVFS::new(db_name).await.expect("Should create VFS");
    let vfs_name = "indexeddb";
    vfs.register(vfs_name).expect("Should register VFS");

    // Open database with our VFS
    let mut db = Database::open_with_vfs(db_name, vfs_name)
        .await
        .expect("Should open database");

    // Create table
    db.execute_internal("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)")
        .await
        .expect("Should create table");

    // Start a transaction (this should trigger x_lock)
    db.execute_internal("BEGIN TRANSACTION")
        .await
        .expect("Should begin transaction");

    // Get initial block count in GLOBAL_STORAGE before writes
    // GLOBAL_STORAGE is HashMap<String, HashMap<u64, Vec<u8>>> so we need to count blocks, not databases
    let initial_block_count = with_global_storage(|gs| {
        gs.borrow()
            .values()
            .map(|blocks| blocks.len())
            .sum::<usize>()
    });
    web_sys::console::log_1(&format!("Initial block count: {}", initial_block_count).into());

    // Perform multiple writes (these should be buffered, not persisted immediately)
    for i in 1..=10 {
        db.execute_internal(&format!(
            "INSERT INTO test (id, value) VALUES ({}, 'value_{}')",
            i, i
        ))
        .await
        .expect(&format!("Should insert row {}", i));
    }

    // Check block count DURING transaction - should NOT have increased significantly
    // (writes should be buffered, not persisted to GLOBAL_STORAGE yet)
    let during_tx_block_count = with_global_storage(|gs| {
        gs.borrow()
            .values()
            .map(|blocks| blocks.len())
            .sum::<usize>()
    });
    web_sys::console::log_1(
        &format!("Block count during transaction: {}", during_tx_block_count).into(),
    );

    // The key assertion: block count should not have grown much during transaction
    // because writes are buffered. Allow some growth for schema/metadata blocks.
    let blocks_added_during_tx = during_tx_block_count - initial_block_count;
    web_sys::console::log_1(
        &format!(
            "Blocks added during transaction: {}",
            blocks_added_during_tx
        )
        .into(),
    );

    // With buffering, we expect minimal block writes during transaction (< 5 blocks for schema)
    // Without buffering (current behavior), we'd see 10+ blocks written immediately
    assert!(
        blocks_added_during_tx < 5,
        "Expected < 5 blocks written during transaction (buffered), but got {}. \
         This indicates writes are NOT being buffered!",
        blocks_added_during_tx
    );

    // Commit transaction (this should trigger x_unlock and flush buffered writes)
    db.execute_internal("COMMIT")
        .await
        .expect("Should commit transaction");

    // NOW check block count - blocks should be persisted (may be same count if overwriting)
    let after_commit_block_count = with_global_storage(|gs| {
        gs.borrow()
            .values()
            .map(|blocks| blocks.len())
            .sum::<usize>()
    });
    web_sys::console::log_1(
        &format!("Block count after commit: {}", after_commit_block_count).into(),
    );

    // The key success: blocks were NOT written during transaction (buffered)
    // and were flushed on commit (we saw "TRANSACTION COMMIT" message)
    web_sys::console::log_1(
        &"SUCCESS: Writes were buffered during transaction and flushed on commit!".into(),
    );

    // Verify data is actually persisted
    let result = db
        .execute_internal("SELECT COUNT(*) FROM test")
        .await
        .expect("Should count rows");
    let rows = result.rows;
    assert_eq!(rows.len(), 1, "Should have one result row");
    if let ColumnValue::Integer(count) = &rows[0].values[0] {
        assert_eq!(*count, 10, "Should have 10 rows inserted");
    } else {
        panic!("Expected integer count");
    }

    web_sys::console::log_1(&"TEST PASSED: Writes are buffered during transaction".into());
}

/// Test 2: Iteratively test performance with increasing batch sizes to find our limit
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen_test]
async fn test_batch_commit_performance() {
    web_sys::console::log_1(&"=== TEST: Batch commit performance - Finding our limits ===".into());

    let db_name = "batch_perf_test.db";

    // Clear global state
    with_global_storage(|gs| gs.borrow_mut().clear());
    with_global_commit_marker(|cm| cm.borrow_mut().clear());

    // Create VFS and register it
    let vfs = IndexedDBVFS::new(db_name).await.expect("Should create VFS");
    let vfs_name = "indexeddb";
    vfs.register(vfs_name).expect("Should register VFS");

    // Open database
    let mut db = Database::open_with_vfs(db_name, vfs_name)
        .await
        .expect("Should open database");

    // Create table
    db.execute_internal("CREATE TABLE perf_test (id INTEGER PRIMARY KEY, value TEXT)")
        .await
        .expect("Should create table");

    // Test with increasing batch sizes to find performance ceiling
    let batch_sizes = vec![10, 50, 100, 500, 1000, 5000];
    let mut results = Vec::new();

    web_sys::console::log_1(&"\nPERFORMANCE SCALING TEST:".into());
    web_sys::console::log_1(&"─────────────────────────────────────────────────────".into());

    for &batch_size in &batch_sizes {
        let start = js_sys::Date::now();

        db.execute_internal("BEGIN TRANSACTION")
            .await
            .expect("Should begin transaction");
        for i in 1..=batch_size {
            db.execute_internal(&format!(
                "INSERT INTO perf_test (id, value) VALUES ({}, 'value_{}')",
                i, i
            ))
            .await
            .expect(&format!("Should insert row {}", i));
        }
        db.execute_internal("COMMIT")
            .await
            .expect("Should commit transaction");

        let batch_time = js_sys::Date::now() - start;
        let per_insert_ms = batch_time / batch_size as f64;

        results.push((batch_size, batch_time, per_insert_ms));

        web_sys::console::log_1(
            &format!(
                "  {:>5} inserts: {:>8.2}ms total | {:>6.3}ms per insert | {:>6.0} inserts/sec",
                batch_size,
                batch_time,
                per_insert_ms,
                1000.0 / per_insert_ms
            )
            .into(),
        );

        // Clean up for next test
        db.execute_internal(&format!("DELETE FROM perf_test WHERE id <= {}", batch_size))
            .await
            .expect("Should delete rows");
    }

    web_sys::console::log_1(&"─────────────────────────────────────────────────────".into());

    // Find best performance
    let best = results
        .iter()
        .min_by(|a, b| a.2.partial_cmp(&b.2).unwrap())
        .unwrap();
    web_sys::console::log_1(
        &format!(
            "\n🏆 BEST: {:.3}ms per insert at {} batch size ({:.0} inserts/sec)",
            best.2,
            best.0,
            1000.0 / best.2
        )
        .into(),
    );

    // Compare to absurd-sql
    let absurd_sql_ms = 5.9;
    let speedup = absurd_sql_ms / best.2;
    web_sys::console::log_1(&format!("vs absurd-sql (5.9ms): {}x FASTER\n", speedup as i32).into());

    // Verify we beat absurd-sql with at least one batch size
    assert!(
        best.2 < absurd_sql_ms,
        "Expected to beat absurd-sql (5.9ms), but best was {:.3}ms",
        best.2
    );
}

/// Test 3: Verify no borrow panic when reading during buffered transaction
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen_test]
async fn test_no_borrow_panic_during_buffered_write() {
    web_sys::console::log_1(&"=== TEST: No borrow panic during buffered write ===".into());

    let db_name = "borrow_panic_test.db";

    // Clear global state
    with_global_storage(|gs| gs.borrow_mut().clear());
    with_global_commit_marker(|cm| cm.borrow_mut().clear());

    // Create VFS and register it
    let vfs = IndexedDBVFS::new(db_name).await.expect("Should create VFS");
    let vfs_name = "indexeddb";
    vfs.register(vfs_name).expect("Should register VFS");

    // Open database
    let mut db = Database::open_with_vfs(db_name, vfs_name)
        .await
        .expect("Should open database");

    // Create table - this writes initial blocks
    db.execute_internal("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)")
        .await
        .expect("Should create table");

    // Start transaction - activates buffering
    db.execute_internal("BEGIN TRANSACTION")
        .await
        .expect("Should begin transaction");

    // Insert data - this should:
    // 1. Read existing blocks (to preserve data)
    // 2. Modify them
    // 3. Buffer them
    // This is where the borrow panic happens if not handled correctly
    db.execute_internal("INSERT INTO test (id, value) VALUES (1, 'test')")
        .await
        .expect("Should insert without borrow panic");

    // Commit
    db.execute_internal("COMMIT").await.expect("Should commit");

    // Verify data persisted
    let result = db
        .execute_internal("SELECT COUNT(*) FROM test")
        .await
        .expect("Should count rows");
    let rows = result.rows;

    if let ColumnValue::Integer(count) = &rows[0].values[0] {
        assert_eq!(*count, 1, "Should have 1 row");
    } else {
        panic!("Expected integer count");
    }

    web_sys::console::log_1(&"TEST PASSED: No borrow panic during buffered write".into());
}

/// Test 4: Verify that rollback discards buffered writes
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen_test]
async fn test_rollback_discards_buffered_writes() {
    web_sys::console::log_1(&"=== TEST: Rollback discards buffered writes ===".into());

    let db_name = "rollback_test.db";

    // Clear global state
    with_global_storage(|gs| gs.borrow_mut().clear());
    with_global_commit_marker(|cm| cm.borrow_mut().clear());

    // Create VFS and register it
    let vfs = IndexedDBVFS::new(db_name).await.expect("Should create VFS");
    let vfs_name = "indexeddb";
    vfs.register(vfs_name).expect("Should register VFS");

    // Open database
    let mut db = Database::open_with_vfs(db_name, vfs_name)
        .await
        .expect("Should open database");

    // Create table
    db.execute_internal("CREATE TABLE rollback_test (id INTEGER PRIMARY KEY, value TEXT)")
        .await
        .expect("Should create table");

    // Insert initial data and commit
    db.execute_internal("INSERT INTO rollback_test (id, value) VALUES (1, 'initial')")
        .await
        .expect("Should insert initial row");

    // Start transaction
    db.execute_internal("BEGIN TRANSACTION")
        .await
        .expect("Should begin transaction");

    // Insert data that will be rolled back
    for i in 2..=5 {
        db.execute_internal(&format!(
            "INSERT INTO rollback_test (id, value) VALUES ({}, 'rollback_{}')",
            i, i
        ))
        .await
        .expect(&format!("Should insert row {}", i));
    }

    // Rollback transaction (buffered writes should be discarded)
    db.execute_internal("ROLLBACK")
        .await
        .expect("Should rollback transaction");

    // Verify only initial data exists
    let result = db
        .execute_internal("SELECT COUNT(*) FROM rollback_test")
        .await
        .expect("Should count rows");
    let rows = result.rows;

    if let ColumnValue::Integer(count) = &rows[0].values[0] {
        assert_eq!(
            *count, 1,
            "Should only have initial row after rollback, buffered writes should be discarded"
        );
    } else {
        panic!("Expected integer count");
    }

    web_sys::console::log_1(&"TEST PASSED: Rollback discards buffered writes".into());
}

/// Test 4: Verify that nested transactions work correctly with buffering
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen_test]
async fn test_nested_transactions_with_buffering() {
    web_sys::console::log_1(&"=== TEST: Nested transactions with buffering ===".into());

    let db_name = "nested_tx_test.db";

    // Clear global state
    with_global_storage(|gs| gs.borrow_mut().clear());
    with_global_commit_marker(|cm| cm.borrow_mut().clear());

    // Create VFS and register it
    let vfs = IndexedDBVFS::new(db_name).await.expect("Should create VFS");
    let vfs_name = "indexeddb";
    vfs.register(vfs_name).expect("Should register VFS");

    // Open database
    let mut db = Database::open_with_vfs(db_name, vfs_name)
        .await
        .expect("Should open database");

    // Create table
    db.execute_internal("CREATE TABLE nested_test (id INTEGER PRIMARY KEY, value TEXT)")
        .await
        .expect("Should create table");

    // Outer transaction
    db.execute_internal("BEGIN TRANSACTION")
        .await
        .expect("Should begin outer transaction");

    db.execute_internal("INSERT INTO nested_test (id, value) VALUES (1, 'outer')")
        .await
        .expect("Should insert in outer transaction");

    // SQLite doesn't support true nested transactions, but we can use SAVEPOINTs
    db.execute_internal("SAVEPOINT inner")
        .await
        .expect("Should create savepoint");

    db.execute_internal("INSERT INTO nested_test (id, value) VALUES (2, 'inner')")
        .await
        .expect("Should insert in savepoint");

    // Rollback to savepoint (should discard inner insert but keep outer)
    db.execute_internal("ROLLBACK TO inner")
        .await
        .expect("Should rollback to savepoint");

    // Commit outer transaction
    db.execute_internal("COMMIT")
        .await
        .expect("Should commit outer transaction");

    // Verify only outer insert persisted
    let result = db
        .execute_internal("SELECT COUNT(*) FROM nested_test")
        .await
        .expect("Should count rows");
    let rows = result.rows;

    if let ColumnValue::Integer(count) = &rows[0].values[0] {
        assert_eq!(*count, 1, "Should only have outer transaction row");
    } else {
        panic!("Expected integer count");
    }

    web_sys::console::log_1(
        &"TEST PASSED: Nested transactions work correctly with buffering".into(),
    );
}