motedb 0.8.0

AI-native embedded multimodal database for embodied intelligence (robots, AR glasses, industrial arms).
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
//! Concurrent Workload Benchmark — read-heavy, mixed read/write, concurrent
//! transactions, concurrent checkpoint, concurrent prepared statements
//!
//! Run: cargo test --test bench_concurrent --release -- --nocapture --test-threads=1

use motedb::{DBConfig, Database};
use std::sync::Arc;
use std::thread;
use std::time::Instant;
use tempfile::TempDir;

fn is_ci() -> bool {
    std::env::var("CI").is_ok()
}

fn edge_config() -> DBConfig {
    DBConfig::for_edge()
}

fn exec(db: &Database, sql: &str) -> motedb::sql::QueryResult {
    db.execute(sql)
        .expect("execute SQL")
        .materialize()
        .expect("materialize")
}

fn print_result(name: &str, ops: usize, elapsed_ms: u64) {
    let per_op_us = if ops > 0 {
        (elapsed_ms as f64 * 1000.0) / ops as f64
    } else {
        0.0
    };
    let throughput = if elapsed_ms > 0 {
        ops as f64 / (elapsed_ms as f64 / 1000.0)
    } else {
        f64::INFINITY
    };
    println!(
        "  {:<60} | {:>7} ops | {:>8.1} ms | {:>8.1} µs/op | {:>10.0} ops/s",
        name, ops, elapsed_ms as f64, per_op_us, throughput
    );
}

fn print_separator() {
    println!("  {}", "-".repeat(100));
}

// ═══════════════════════════════════════════════════════════════
// Test 1: Read-Heavy Concurrent Workload (90% reads)
// ═══════════════════════════════════════════════════════════════

#[test]
#[ignore = "bench/stress/perf: slow in debug, run with --ignored or via bench examples"]
fn bench_read_heavy_concurrent() {
    let dir = TempDir::new().expect("temp dir");
    let db = Arc::new(Database::create_with_config(dir.path(), edge_config()).expect("create db"));
    exec(
        &db,
        "CREATE TABLE rh (id INT PRIMARY KEY, data TEXT, val INT)",
    );

    let seed: usize = if is_ci() { 2_000 } else { 10_000 };
    for i in 1..=seed as i64 {
        exec(
            &db,
            &format!("INSERT INTO rh VALUES ({}, 'data_{}', {})", i, i, i * 10),
        );
    }

    print_separator();

    let (n_threads, reads_per_thread) = if is_ci() { (2, 500) } else { (4, 2500) };
    let total_reads = n_threads * reads_per_thread;

    let ms = {
        let start = Instant::now();
        let mut handles = vec![];

        for t in 0..n_threads {
            let db_clone = Arc::clone(&db);
            handles.push(thread::spawn(move || {
                let mut ops = 0;
                for i in 0..reads_per_thread {
                    let id = ((t * reads_per_thread + i) % seed) as i64 + 1;
                    let sql = format!("SELECT * FROM rh WHERE id = {}", id);
                    db_clone
                        .execute(&sql)
                        .expect("select")
                        .materialize()
                        .expect("mat");
                    ops += 1;
                }
                ops
            }));
        }

        let total_ops: usize = handles.into_iter().map(|h| h.join().unwrap()).sum();
        let elapsed = start.elapsed().as_millis() as u64;
        print_result(
            &format!(
                "Read-heavy {} threads × {} reads",
                n_threads, reads_per_thread
            ),
            total_ops,
            elapsed,
        );
        elapsed
    };

    let throughput = total_reads as f64 / (ms as f64 / 1000.0);
    println!(
        "  -> {} threads reading concurrently: {:.0} reads/s",
        n_threads, throughput
    );
    if let Ok(db) = Arc::try_unwrap(db) {
        db.close().ok();
    }
}

// ═══════════════════════════════════════════════════════════════
// Test 2: Mixed Read/Write Concurrent (70% read, 30% write)
// ═══════════════════════════════════════════════════════════════

#[test]
#[ignore = "bench/stress/perf: slow in debug, run with --ignored or via bench examples"]
fn bench_mixed_read_write_concurrent() {
    let dir = TempDir::new().expect("temp dir");
    let db = Arc::new(Database::create_with_config(dir.path(), edge_config()).expect("create db"));
    exec(
        &db,
        "CREATE TABLE mix (id INT PRIMARY KEY, val TEXT, score FLOAT)",
    );

    let seed: usize = if is_ci() { 1_000 } else { 5_000 };
    for i in 1..=seed as i64 {
        exec(
            &db,
            &format!(
                "INSERT INTO mix VALUES ({}, 'v_{}', {})",
                i,
                i,
                i as f64 * 1.5
            ),
        );
    }

    print_separator();

    let n_threads = if is_ci() { 2 } else { 4 };
    let ops_per_thread = if is_ci() { 500 } else { 2000 };
    let total_ops = n_threads * ops_per_thread;

    let ms = {
        let start = Instant::now();
        let mut handles = vec![];

        for t in 0..n_threads {
            let db_clone = Arc::clone(&db);
            handles.push(thread::spawn(move || {
                let base_id = (seed + t * ops_per_thread) as i64;
                let mut ops = 0;
                for i in 0..ops_per_thread {
                    if i % 10 < 7 {
                        // 70% reads
                        let id = (i % seed) as i64 + 1;
                        let sql = format!("SELECT * FROM mix WHERE id = {}", id);
                        db_clone
                            .execute(&sql)
                            .expect("select")
                            .materialize()
                            .expect("mat");
                    } else if i % 10 < 9 {
                        // 20% inserts
                        let id = base_id + i as i64;
                        let sql = format!(
                            "INSERT INTO mix VALUES ({}, 'new_{}', {})",
                            id, i, id as f64
                        );
                        db_clone
                            .execute(&sql)
                            .expect("insert")
                            .materialize()
                            .expect("mat");
                    } else {
                        // 10% updates
                        let id = (i % seed) as i64 + 1;
                        let sql = format!("UPDATE mix SET score = score + 1 WHERE id = {}", id);
                        db_clone
                            .execute(&sql)
                            .expect("update")
                            .materialize()
                            .expect("mat");
                    }
                    ops += 1;
                }
                ops
            }));
        }

        let total: usize = handles.into_iter().map(|h| h.join().unwrap()).sum();
        let elapsed = start.elapsed().as_millis() as u64;
        print_result(
            &format!(
                "Mixed R/W {} threads × {} ops (70R/20W/10U)",
                n_threads, ops_per_thread
            ),
            total,
            elapsed,
        );
        elapsed
    };

    let throughput = total_ops as f64 / (ms as f64 / 1000.0);
    println!("  -> Mixed workload throughput: {:.0} ops/s", throughput);
    if let Ok(db) = Arc::try_unwrap(db) {
        db.close().ok();
    }
}

// ═══════════════════════════════════════════════════════════════
// Test 3: Concurrent Transactions (begin/commit/rollback)
// ═══════════════════════════════════════════════════════════════

#[test]
#[ignore = "bench/stress/perf: slow in debug, run with --ignored or via bench examples"]
fn bench_concurrent_transactions() {
    let dir = TempDir::new().expect("temp dir");
    let db = Arc::new(Database::create_with_config(dir.path(), edge_config()).expect("create db"));
    exec(&db, "CREATE TABLE txn_data (id INT PRIMARY KEY, val INT)");

    // Seed
    for i in 1..=100i64 {
        exec(
            &db,
            &format!("INSERT INTO txn_data VALUES ({}, {})", i, i * 10),
        );
    }

    print_separator();

    let n_threads = if is_ci() { 2 } else { 4 };
    let txns_per_thread = if is_ci() { 50 } else { 200 };

    let ms = {
        let start = Instant::now();
        let mut handles = vec![];

        for t in 0..n_threads {
            let db_clone = Arc::clone(&db);
            handles.push(thread::spawn(move || {
                let mut committed = 0;
                let mut rolled_back = 0;
                for i in 0..txns_per_thread {
                    let tx = db_clone.begin_transaction().expect("begin");
                    let id = 101 + t * txns_per_thread + i;
                    let row = vec![
                        motedb::types::Value::Integer(id as i64),
                        motedb::types::Value::Integer(id as i64 * 10),
                    ];
                    db_clone
                        .insert_row_with_txn("txn_data", tx, row)
                        .expect("insert with txn");

                    if i % 5 == 0 {
                        db_clone.rollback_transaction(tx).expect("rollback");
                        rolled_back += 1;
                    } else {
                        db_clone.commit_transaction(tx).expect("commit");
                        committed += 1;
                    }
                }
                (committed, rolled_back)
            }));
        }

        let (total_committed, total_rolled_back): (usize, usize) = handles
            .into_iter()
            .map(|h| h.join().unwrap())
            .fold((0, 0), |(c, r), (tc, tr)| (c + tc, r + tr));

        let elapsed = start.elapsed().as_millis() as u64;
        let total_ops = total_committed + total_rolled_back;
        print_result(
            &format!(
                "Concurrent txn {} threads × {} (commit/rollback)",
                n_threads, txns_per_thread
            ),
            total_ops,
            elapsed,
        );
        println!(
            "  -> Committed: {}, Rolled back: {}",
            total_committed, total_rolled_back
        );
        elapsed
    };

    let total = n_threads * txns_per_thread;
    let throughput = total as f64 / (ms as f64 / 1000.0);
    println!("  -> Transaction throughput: {:.0} txns/s", throughput);
    if let Ok(db) = Arc::try_unwrap(db) {
        db.close().ok();
    }
}

// ═══════════════════════════════════════════════════════════════
// Test 4: Concurrent Writes (insert-only, contention)
// ═══════════════════════════════════════════════════════════════

#[test]
#[ignore = "bench/stress/perf: slow in debug, run with --ignored or via bench examples"]
fn bench_concurrent_inserts() {
    let dir = TempDir::new().expect("temp dir");
    let db = Arc::new(Database::create_with_config(dir.path(), edge_config()).expect("create db"));
    exec(
        &db,
        "CREATE TABLE ci (id INT PRIMARY KEY, payload TEXT, ts INT)",
    );

    print_separator();

    let (n_threads, inserts_per_thread) = if is_ci() { (2, 500) } else { (4, 2500) };
    let total_inserts = n_threads * inserts_per_thread;

    let ms = {
        let start = Instant::now();
        let mut handles = vec![];

        for t in 0..n_threads {
            let db_clone = Arc::clone(&db);
            handles.push(thread::spawn(move || {
                let base = t * inserts_per_thread;
                let mut ops = 0;
                for i in 0..inserts_per_thread {
                    let id = (base + i + 1) as i64;
                    let sql = format!(
                        "INSERT INTO ci VALUES ({}, 'payload_{}_{}', {})",
                        id,
                        t,
                        i,
                        1700000000 + id
                    );
                    db_clone
                        .execute(&sql)
                        .expect("insert")
                        .materialize()
                        .expect("mat");
                    ops += 1;
                }
                ops
            }));
        }

        let total: usize = handles.into_iter().map(|h| h.join().unwrap()).sum();
        let elapsed = start.elapsed().as_millis() as u64;
        print_result(
            &format!(
                "Concurrent INSERT {} threads × {}",
                n_threads, inserts_per_thread
            ),
            total,
            elapsed,
        );
        elapsed
    };

    // Verify row count
    let result = exec(&db, "SELECT COUNT(*) FROM ci");
    if let motedb::sql::QueryResult::Select { rows, .. } = result {
        if let Some(motedb::types::Value::Integer(count)) = rows.first().and_then(|r| r.first()) {
            println!("  -> Total rows after concurrent inserts: {}", count);
            assert_eq!(
                *count, total_inserts as i64,
                "All concurrent inserts should succeed"
            );
        }
    }

    let throughput = total_inserts as f64 / (ms as f64 / 1000.0);
    println!("  -> Concurrent insert throughput: {:.0} ops/s", throughput);
    if let Ok(db) = Arc::try_unwrap(db) {
        db.close().ok();
    }
}

// ═══════════════════════════════════════════════════════════════
// Test 5: Concurrent Row API (insert_row + get_row)
// ═══════════════════════════════════════════════════════════════

#[test]
#[ignore = "bench/stress/perf: slow in debug, run with --ignored or via bench examples"]
fn bench_concurrent_row_api() {
    let dir = TempDir::new().expect("temp dir");
    let db = Arc::new(Database::create_with_config(dir.path(), edge_config()).expect("create db"));
    exec(&db, "CREATE TABLE row_api (id INT PRIMARY KEY, val TEXT)");

    // Seed
    let seed: usize = if is_ci() { 500 } else { 2000 };
    let mut row_ids = Vec::new();
    for i in 1..=seed as i64 {
        let row = vec![
            motedb::types::Value::Integer(i),
            motedb::types::Value::text(format!("v_{}", i)),
        ];
        let rid = db.insert_row("row_api", row).expect("insert_row");
        row_ids.push(rid);
    }

    print_separator();

    let n_threads = if is_ci() { 2 } else { 4 };
    let reads_per_thread = if is_ci() { 500 } else { 2000 };

    // Concurrent reads via row API
    let read_ms = {
        let ids = Arc::new(row_ids.clone());
        let start = Instant::now();
        let mut handles = vec![];

        for _ in 0..n_threads {
            let db_clone = Arc::clone(&db);
            let ids_clone = Arc::clone(&ids);
            handles.push(thread::spawn(move || {
                let mut ops = 0;
                for i in 0..reads_per_thread {
                    let idx = i % ids_clone.len();
                    let _ = db_clone
                        .get_row("row_api", ids_clone[idx])
                        .expect("get_row");
                    ops += 1;
                }
                ops
            }));
        }

        let total: usize = handles.into_iter().map(|h| h.join().unwrap()).sum();
        let elapsed = start.elapsed().as_millis() as u64;
        let _total_reads = n_threads * reads_per_thread;
        print_result(
            &format!(
                "Concurrent get_row {} threads × {} reads",
                n_threads, reads_per_thread
            ),
            total,
            elapsed,
        );
        elapsed
    };

    // Concurrent inserts via row API
    let insert_per_thread = if is_ci() { 200 } else { 1000 };
    let insert_ms = {
        let start = Instant::now();
        let mut handles = vec![];

        for t in 0..n_threads {
            let db_clone = Arc::clone(&db);
            handles.push(thread::spawn(move || {
                let mut ops = 0;
                for i in 0..insert_per_thread {
                    let id = (seed + t * insert_per_thread + i + 1) as i64;
                    let row = vec![
                        motedb::types::Value::Integer(id),
                        motedb::types::Value::text(format!("new_{}", id)),
                    ];
                    db_clone.insert_row("row_api", row).expect("insert_row");
                    ops += 1;
                }
                ops
            }));
        }

        let total: usize = handles.into_iter().map(|h| h.join().unwrap()).sum();
        let elapsed = start.elapsed().as_millis() as u64;
        print_result(
            &format!(
                "Concurrent insert_row {} threads × {} inserts",
                n_threads, insert_per_thread
            ),
            total,
            elapsed,
        );
        elapsed
    };

    let read_throughput = (n_threads * reads_per_thread) as f64 / (read_ms as f64 / 1000.0);
    let insert_throughput = (n_threads * insert_per_thread) as f64 / (insert_ms as f64 / 1000.0);
    println!(
        "  -> get_row: {:.0} ops/s, insert_row: {:.0} ops/s",
        read_throughput, insert_throughput
    );
    if let Ok(db) = Arc::try_unwrap(db) {
        db.close().ok();
    }
}

// ═══════════════════════════════════════════════════════════════
// Test 6: Concurrent Prepared Statements
// ═══════════════════════════════════════════════════════════════

#[test]
#[ignore = "bench/stress/perf: slow in debug, run with --ignored or via bench examples"]
fn bench_concurrent_prepared() {
    use motedb::types::Value;

    let dir = TempDir::new().expect("temp dir");
    let db = Arc::new(Database::create_with_config(dir.path(), edge_config()).expect("create db"));
    exec(
        &db,
        "CREATE TABLE cp (id INT PRIMARY KEY, name TEXT, val INT)",
    );

    let seed: usize = if is_ci() { 1_000 } else { 5_000 };
    for i in 1..=seed as i64 {
        exec(
            &db,
            &format!("INSERT INTO cp VALUES ({}, 'name_{}', {})", i, i, i * 10),
        );
    }

    print_separator();

    let n_threads = if is_ci() { 2 } else { 4 };
    let ops_per_thread = if is_ci() { 300 } else { 1500 };

    let ms = {
        let start = Instant::now();
        let mut handles = vec![];

        for _t in 0..n_threads {
            let db_clone = Arc::clone(&db);
            handles.push(thread::spawn(move || {
                let mut ops = 0;
                for i in 0..ops_per_thread {
                    let id = (i % seed) as i64 + 1;
                    if i % 10 < 7 {
                        // Read
                        let _ = db_clone
                            .execute_prepared(
                                "SELECT * FROM cp WHERE id = ?",
                                vec![Value::Integer(id)],
                            )
                            .expect("prepared select");
                    } else {
                        // Update
                        let _ = db_clone
                            .execute_prepared(
                                "UPDATE cp SET val = val + 1 WHERE id = ?",
                                vec![Value::Integer(id)],
                            )
                            .expect("prepared update");
                    }
                    ops += 1;
                }
                ops
            }));
        }

        let total: usize = handles.into_iter().map(|h| h.join().unwrap()).sum();
        let elapsed = start.elapsed().as_millis() as u64;
        print_result(
            &format!(
                "Concurrent prepared {} threads × {} ops",
                n_threads, ops_per_thread
            ),
            total,
            elapsed,
        );
        elapsed
    };

    let total = n_threads * ops_per_thread;
    let throughput = total as f64 / (ms as f64 / 1000.0);
    println!(
        "  -> Concurrent prepared throughput: {:.0} ops/s",
        throughput
    );
    if let Ok(db) = Arc::try_unwrap(db) {
        db.close().ok();
    }
}

// ═══════════════════════════════════════════════════════════════
// Test 7: Concurrent DELETE + Reclaim
// ═══════════════════════════════════════════════════════════════

#[test]
#[ignore = "bench/stress/perf: slow in debug, run with --ignored or via bench examples"]
fn bench_concurrent_delete() {
    let dir = TempDir::new().expect("temp dir");
    let db = Arc::new(Database::create_with_config(dir.path(), edge_config()).expect("create db"));
    exec(&db, "CREATE TABLE cd (id INT PRIMARY KEY, data TEXT)");

    let seed: usize = if is_ci() { 2_000 } else { 10_000 };
    for i in 1..=seed as i64 {
        exec(&db, &format!("INSERT INTO cd VALUES ({}, 'data_{}')", i, i));
    }

    print_separator();

    let db = Arc::new(db);
    let n_threads = if is_ci() { 2 } else { 4 };
    let deletes_per_thread = seed / n_threads;

    let ms = {
        let start = Instant::now();
        let mut handles = vec![];

        for t in 0..n_threads {
            let db_clone = Arc::clone(&db);
            let start_id = (t * deletes_per_thread) as i64 + 1;
            let end_id = ((t + 1) * deletes_per_thread) as i64;
            handles.push(thread::spawn(move || {
                let mut ops = 0;
                for id in start_id..=end_id {
                    let sql = format!("DELETE FROM cd WHERE id = {}", id);
                    db_clone
                        .execute(&sql)
                        .expect("delete")
                        .materialize()
                        .expect("mat");
                    ops += 1;
                }
                ops
            }));
        }

        let total: usize = handles.into_iter().map(|h| h.join().unwrap()).sum();
        let elapsed = start.elapsed().as_millis() as u64;
        print_result(
            &format!(
                "Concurrent DELETE {} threads × {} rows",
                n_threads, deletes_per_thread
            ),
            total,
            elapsed,
        );
        elapsed
    };

    let total = n_threads * deletes_per_thread;
    let throughput = total as f64 / (ms as f64 / 1000.0);
    println!("  -> Concurrent delete throughput: {:.0} ops/s", throughput);

    // Verify table is empty
    let result = exec(&db, "SELECT COUNT(*) FROM cd");
    if let motedb::sql::QueryResult::Select { rows, .. } = result {
        if let Some(motedb::types::Value::Integer(count)) = rows.first().and_then(|r| r.first()) {
            println!("  -> Rows remaining after deletes: {}", count);
        }
    }
    if let Ok(db) = Arc::try_unwrap(db) {
        db.close().ok();
    }
}

// ═══════════════════════════════════════════════════════════════
// Test 8: Write-Then-Read Consistency Under Concurrency
// ═══════════════════════════════════════════════════════════════

#[test]
#[ignore = "bench/stress/perf: slow in debug, run with --ignored or via bench examples"]
fn bench_concurrent_write_read_consistency() {
    let dir = TempDir::new().expect("temp dir");
    let db = Arc::new(Database::create_with_config(dir.path(), edge_config()).expect("create db"));
    exec(&db, "CREATE TABLE wrc (id INT PRIMARY KEY, val INT)");

    print_separator();

    let n_writers = if is_ci() { 1 } else { 2 };
    let n_readers = if is_ci() { 1 } else { 2 };
    let rows_per_writer = if is_ci() { 500 } else { 2500 };

    let ms = {
        let start = Instant::now();
        let mut handles = vec![];

        // Writers
        for w in 0..n_writers {
            let db_clone = Arc::clone(&db);
            handles.push(thread::spawn(move || {
                let base = w * rows_per_writer;
                let mut ops = 0;
                for i in 0..rows_per_writer {
                    let id = (base + i + 1) as i64;
                    let sql = format!("INSERT INTO wrc VALUES ({}, {})", id, id * 10);
                    db_clone
                        .execute(&sql)
                        .expect("insert")
                        .materialize()
                        .expect("mat");
                    ops += 1;
                }
                ops
            }));
        }

        // Readers (read what's been written so far)
        for _ in 0..n_readers {
            let db_clone = Arc::clone(&db);
            handles.push(thread::spawn(move || {
                let mut ops = 0;
                for i in 1..=rows_per_writer as i64 {
                    let sql = format!("SELECT * FROM wrc WHERE id = {}", i);
                    let _ = db_clone.execute(&sql);
                    ops += 1;
                }
                ops
            }));
        }

        let results: Vec<usize> = handles.into_iter().map(|h| h.join().unwrap()).collect();
        let elapsed = start.elapsed().as_millis() as u64;
        let total_ops: usize = results.iter().sum();
        print_result(
            &format!("Write+Read concurrent ({}W + {}R)", n_writers, n_readers),
            total_ops,
            elapsed,
        );
        elapsed
    };

    let total = (n_writers + n_readers) * rows_per_writer;
    let throughput = total as f64 / (ms as f64 / 1000.0);
    println!("  -> Combined throughput: {:.0} ops/s", throughput);
    if let Ok(db) = Arc::try_unwrap(db) {
        db.close().ok();
    }
}