appdb 0.2.21

Lightweight SurrealDB helper library for Tauri embedded database apps
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
use std::path::PathBuf;
use std::sync::{LazyLock, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use appdb::connection::reinit_db;
use appdb::graph::GraphRepo;
use appdb::model::meta::ModelMeta;
use appdb::repository::Repo;
use appdb::{Id, Store};
use serde::{Deserialize, Serialize};
use surrealdb::types::{RecordId, SurrealValue};
use tokio::runtime::Runtime;

static TEST_LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
static TEST_RT: LazyLock<Runtime> =
    LazyLock::new(|| Runtime::new().expect("performance runtime should be created"));

const PERF_RELATE_ITEMS: &str = "perf_relate_items";
const PERF_BACK_RELATE_ITEMS: &str = "perf_back_relate_items";
const PERF_GRAPH_REL: &str = "perf_graph_rel";

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, SurrealValue, Store)]
struct PerfRelationLeaf {
    id: Id,
    label: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, SurrealValue, Store)]
struct PerfRelationRoot {
    id: Id,
    title: String,
    #[relate("perf_relate_items")]
    items: Vec<PerfRelationLeaf>,
    #[back_relate("perf_back_relate_items")]
    backlinks: Option<Vec<PerfRelationLeaf>>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, SurrealValue, Store)]
struct PerfGraphNode {
    id: Id,
    label: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, SurrealValue, Store)]
struct PerfPlainRow {
    id: Id,
    label: String,
    count: i64,
}

fn test_db_path() -> PathBuf {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("clock before epoch")
        .as_nanos();
    std::env::temp_dir().join(format!(
        "appdb_perf_relation_apis_{}_{}",
        std::process::id(),
        nanos
    ))
}

fn run_async<T>(fut: impl std::future::Future<Output = T>) -> T {
    TEST_RT.block_on(fut)
}

fn acquire_test_lock() -> std::sync::MutexGuard<'static, ()> {
    TEST_LOCK
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

async fn ensure_db() {
    reinit_db(test_db_path())
        .await
        .expect("database should initialize");
}

fn ms_per_call(elapsed: Duration, iterations: u32) -> f64 {
    elapsed.as_secs_f64() * 1000.0 / f64::from(iterations)
}

fn emit_perf_metric(
    metric: &str,
    scenario: &str,
    iterations: u32,
    elapsed: Duration,
    dimensions: &[(&str, usize)],
) {
    let mut line = format!(
        "APPDB_PERF {{\"metric\":\"{metric}\",\"scenario\":\"{scenario}\",\"unit\":\"ms_per_call\",\"iterations\":{iterations},\"avg_ms\":{:.6}",
        ms_per_call(elapsed, iterations)
    );
    for (key, value) in dimensions {
        line.push_str(&format!(",\"{key}\":{value}"));
    }
    line.push('}');
    println!("{line}");
}

fn perf_leaf(id: String) -> PerfRelationLeaf {
    PerfRelationLeaf {
        id: Id::from(id.clone()),
        label: format!("label-{id}"),
    }
}

fn perf_root(id: &str, item_count: usize, backlink_count: usize) -> PerfRelationRoot {
    let items = (0..item_count)
        .map(|idx| perf_leaf(format!("{id}-item-{idx}")))
        .collect();
    let backlinks = Some(
        (0..backlink_count)
            .map(|idx| perf_leaf(format!("{id}-backlink-{idx}")))
            .collect(),
    );

    PerfRelationRoot {
        id: Id::from(id),
        title: format!("root-{id}"),
        items,
        backlinks,
    }
}

fn perf_root_batch(
    root_count: usize,
    item_count: usize,
    backlink_count: usize,
) -> Vec<PerfRelationRoot> {
    (0..root_count)
        .map(|idx| perf_root(&format!("batch-root-{idx}"), item_count, backlink_count))
        .collect()
}

fn perf_graph_node(id: String) -> PerfGraphNode {
    PerfGraphNode {
        id: Id::from(id.clone()),
        label: format!("node-{id}"),
    }
}

fn perf_plain_batch(prefix: &str, row_count: usize) -> Vec<PerfPlainRow> {
    (0..row_count)
        .map(|idx| PerfPlainRow {
            id: Id::from(format!("{prefix}-{idx}")),
            label: format!("plain-{prefix}-{idx}"),
            count: idx as i64,
        })
        .collect()
}

fn perf_graph_record(id: &str) -> RecordId {
    RecordId::new(PerfGraphNode::table_name(), id)
}

fn perf_root_record(id: &str) -> RecordId {
    RecordId::new(PerfRelationRoot::table_name(), id)
}

#[test]
#[ignore = "manual performance smoke test"]
fn perf_relation_field_save_smoke() {
    let _guard = acquire_test_lock();
    run_async(async {
        ensure_db().await;

        Repo::<PerfRelationRoot>::delete_all()
            .await
            .expect("root cleanup should succeed");
        Repo::<PerfRelationLeaf>::delete_all()
            .await
            .expect("leaf cleanup should succeed");

        let item_count = 64usize;
        let backlink_count = 64usize;
        let iterations = 8u32;
        let root = perf_root("single-root", item_count, backlink_count);

        let saved = PerfRelationRoot::save(root.clone())
            .await
            .expect("baseline save should succeed");
        assert_eq!(saved.items.len(), item_count);
        assert_eq!(saved.backlinks.as_ref().map(Vec::len), Some(backlink_count));

        let root_record = perf_root_record("single-root");
        assert_eq!(
            GraphRepo::outgoing_ids(root_record.clone(), PERF_RELATE_ITEMS)
                .await
                .expect("outgoing edge lookup should succeed")
                .len(),
            item_count
        );
        assert_eq!(
            GraphRepo::incoming_ids(root_record.clone(), PERF_BACK_RELATE_ITEMS)
                .await
                .expect("incoming edge lookup should succeed")
                .len(),
            backlink_count
        );

        let start = Instant::now();
        for _ in 0..iterations {
            let saved = PerfRelationRoot::save(root.clone())
                .await
                .expect("repeated save should succeed");
            assert_eq!(saved.items.len(), item_count);
            assert_eq!(saved.backlinks.as_ref().map(Vec::len), Some(backlink_count));
        }
        let elapsed = start.elapsed();

        println!(
            "perf_relation_field_save_smoke: items={item_count}, backlinks={backlink_count}, avg_ms_per_save={:.3}",
            ms_per_call(elapsed, iterations)
        );
        emit_perf_metric(
            "relation_field_save",
            "single_root_replace_edges",
            iterations,
            elapsed,
            &[
                ("roots", 1),
                ("items_per_root", item_count),
                ("backlinks_per_root", backlink_count),
                ("edges_per_root", item_count + backlink_count),
            ],
        );
    });
}

#[test]
#[ignore = "manual performance smoke test"]
fn perf_relation_field_save_many_smoke() {
    let _guard = acquire_test_lock();
    run_async(async {
        ensure_db().await;

        Repo::<PerfRelationRoot>::delete_all()
            .await
            .expect("root cleanup should succeed");
        Repo::<PerfRelationLeaf>::delete_all()
            .await
            .expect("leaf cleanup should succeed");

        let root_count = 12usize;
        let item_count = 24usize;
        let backlink_count = 24usize;
        let iterations = 4u32;
        let batch = perf_root_batch(root_count, item_count, backlink_count);

        let saved = PerfRelationRoot::save_many(batch.clone())
            .await
            .expect("baseline save_many should succeed");
        assert_eq!(saved.len(), root_count);

        let sample_record = perf_root_record("batch-root-0");
        assert_eq!(
            GraphRepo::outgoing_ids(sample_record.clone(), PERF_RELATE_ITEMS)
                .await
                .expect("sample outgoing edge lookup should succeed")
                .len(),
            item_count
        );
        assert_eq!(
            GraphRepo::incoming_ids(sample_record.clone(), PERF_BACK_RELATE_ITEMS)
                .await
                .expect("sample incoming edge lookup should succeed")
                .len(),
            backlink_count
        );

        let start = Instant::now();
        for _ in 0..iterations {
            let saved = PerfRelationRoot::save_many(batch.clone())
                .await
                .expect("repeated save_many should succeed");
            assert_eq!(saved.len(), root_count);
        }
        let elapsed = start.elapsed();

        println!(
            "perf_relation_field_save_many_smoke: roots={root_count}, items_per_root={item_count}, backlinks_per_root={backlink_count}, avg_ms_per_batch={:.3}",
            ms_per_call(elapsed, iterations)
        );
        emit_perf_metric(
            "relation_field_save_many",
            "batch_roots_replace_edges",
            iterations,
            elapsed,
            &[
                ("roots", root_count),
                ("items_per_root", item_count),
                ("backlinks_per_root", backlink_count),
                ("edges_per_root", item_count + backlink_count),
            ],
        );
    });
}

#[test]
#[ignore = "manual performance smoke test"]
fn perf_plain_store_write_paths_smoke() {
    let _guard = acquire_test_lock();
    run_async(async {
        ensure_db().await;

        Repo::<PerfPlainRow>::delete_all()
            .await
            .expect("plain row cleanup should succeed");

        let row_count = 512usize;
        let iterations = 4u32;

        let insert_batches: Vec<Vec<PerfPlainRow>> = (0..iterations)
            .map(|idx| perf_plain_batch(&format!("insert-{idx}"), row_count))
            .collect();
        let start = Instant::now();
        for batch in insert_batches {
            let inserted = Repo::<PerfPlainRow>::insert(batch)
                .await
                .expect("plain insert should succeed");
            assert_eq!(inserted.len(), row_count);
        }
        let elapsed = start.elapsed();
        println!(
            "perf_plain_store_write_paths_smoke: insert rows={row_count}, avg_ms_per_batch={:.3}",
            ms_per_call(elapsed, iterations)
        );
        emit_perf_metric(
            "plain_store_write",
            "raw_insert_new_rows",
            iterations,
            elapsed,
            &[("rows", row_count)],
        );

        let ignore_seed = perf_plain_batch("insert-ignore-conflict", row_count);
        Repo::<PerfPlainRow>::insert(ignore_seed.clone())
            .await
            .expect("plain insert_ignore seed should succeed");
        let start = Instant::now();
        for _ in 0..iterations {
            let inserted = Repo::<PerfPlainRow>::insert_ignore(ignore_seed.clone())
                .await
                .expect("plain insert_ignore should succeed");
            assert!(inserted.is_empty());
        }
        let elapsed = start.elapsed();
        println!(
            "perf_plain_store_write_paths_smoke: insert_ignore all_conflicts rows={row_count}, avg_ms_per_batch={:.3}",
            ms_per_call(elapsed, iterations)
        );
        emit_perf_metric(
            "plain_store_write",
            "raw_insert_ignore_all_conflicts",
            iterations,
            elapsed,
            &[("rows", row_count)],
        );

        let replace_seed = perf_plain_batch("insert-or-replace-existing", row_count);
        Repo::<PerfPlainRow>::insert(replace_seed.clone())
            .await
            .expect("plain insert_or_replace seed should succeed");
        let start = Instant::now();
        for _ in 0..iterations {
            let replaced = Repo::<PerfPlainRow>::insert_or_replace(replace_seed.clone())
                .await
                .expect("plain insert_or_replace should succeed");
            assert_eq!(replaced.len(), row_count);
        }
        let elapsed = start.elapsed();
        println!(
            "perf_plain_store_write_paths_smoke: insert_or_replace existing rows={row_count}, avg_ms_per_batch={:.3}",
            ms_per_call(elapsed, iterations)
        );
        emit_perf_metric(
            "plain_store_write",
            "raw_insert_or_replace_existing_rows",
            iterations,
            elapsed,
            &[("rows", row_count)],
        );

        let save_many_batch = perf_plain_batch("save-many-existing", row_count);
        PerfPlainRow::save_many(save_many_batch.clone())
            .await
            .expect("plain save_many seed should succeed");
        let start = Instant::now();
        for _ in 0..iterations {
            let saved = PerfPlainRow::save_many(save_many_batch.clone())
                .await
                .expect("plain save_many should succeed");
            assert_eq!(saved.len(), row_count);
        }
        let elapsed = start.elapsed();
        println!(
            "perf_plain_store_write_paths_smoke: save_many existing rows={row_count}, avg_ms_per_batch={:.3}",
            ms_per_call(elapsed, iterations)
        );
        emit_perf_metric(
            "plain_store_write",
            "save_many_existing_rows",
            iterations,
            elapsed,
            &[("rows", row_count)],
        );
    });
}

#[test]
#[ignore = "manual performance smoke test"]
fn perf_store_graph_accessors_smoke() {
    let _guard = acquire_test_lock();
    run_async(async {
        ensure_db().await;

        Repo::<PerfGraphNode>::delete_all()
            .await
            .expect("node cleanup should succeed");

        let edge_count = 96usize;
        let iterations = 20u32;

        let mut nodes = Vec::with_capacity(1 + edge_count * 2);
        nodes.push(perf_graph_node("hub".to_owned()));
        for idx in 0..edge_count {
            nodes.push(perf_graph_node(format!("out-{idx}")));
            nodes.push(perf_graph_node(format!("in-{idx}")));
        }
        PerfGraphNode::save_many(nodes)
            .await
            .expect("node setup should succeed");

        let hub_record = perf_graph_record("hub");
        for idx in 0..edge_count {
            GraphRepo::relate_at(
                hub_record.clone(),
                perf_graph_record(&format!("out-{idx}")),
                PERF_GRAPH_REL,
            )
            .await
            .expect("hub outgoing relate should succeed");
            GraphRepo::relate_at(
                perf_graph_record(&format!("in-{idx}")),
                hub_record.clone(),
                PERF_GRAPH_REL,
            )
            .await
            .expect("hub incoming relate should succeed");
        }

        let hub = PerfGraphNode {
            id: Id::from("hub"),
            label: "node-hub".to_owned(),
        };

        assert_eq!(
            hub.outgoing_ids(PERF_GRAPH_REL)
                .await
                .expect("warmup outgoing_ids should succeed")
                .len(),
            edge_count
        );
        assert_eq!(
            hub.incoming_ids(PERF_GRAPH_REL)
                .await
                .expect("warmup incoming_ids should succeed")
                .len(),
            edge_count
        );

        let start = Instant::now();
        for _ in 0..iterations {
            let ids = hub
                .outgoing_ids(PERF_GRAPH_REL)
                .await
                .expect("outgoing_ids should succeed");
            assert_eq!(ids.len(), edge_count);
        }
        let elapsed = start.elapsed();
        println!(
            "perf_store_graph_accessors_smoke: outgoing_ids avg_ms={:.3}",
            ms_per_call(elapsed, iterations)
        );
        emit_perf_metric(
            "graph_accessor",
            "outgoing_ids",
            iterations,
            elapsed,
            &[("edges", edge_count)],
        );

        let start = Instant::now();
        for _ in 0..iterations {
            let rows = hub
                .outgoing::<PerfGraphNode>(PERF_GRAPH_REL)
                .await
                .expect("outgoing rows should succeed");
            assert_eq!(rows.len(), edge_count);
        }
        let elapsed = start.elapsed();
        println!(
            "perf_store_graph_accessors_smoke: outgoing_rows avg_ms={:.3}",
            ms_per_call(elapsed, iterations)
        );
        emit_perf_metric(
            "graph_accessor",
            "outgoing_rows",
            iterations,
            elapsed,
            &[("edges", edge_count)],
        );

        let start = Instant::now();
        for _ in 0..iterations {
            let count = hub
                .outgoing_count(PERF_GRAPH_REL)
                .await
                .expect("outgoing_count should succeed");
            assert_eq!(count, edge_count as i64);
        }
        let elapsed = start.elapsed();
        println!(
            "perf_store_graph_accessors_smoke: outgoing_count avg_ms={:.3}",
            ms_per_call(elapsed, iterations)
        );
        emit_perf_metric(
            "graph_accessor",
            "outgoing_count",
            iterations,
            elapsed,
            &[("edges", edge_count)],
        );

        let start = Instant::now();
        for _ in 0..iterations {
            let count = hub
                .outgoing_count_as::<PerfGraphNode>(PERF_GRAPH_REL)
                .await
                .expect("typed outgoing_count should succeed");
            assert_eq!(count, edge_count as i64);
        }
        let elapsed = start.elapsed();
        println!(
            "perf_store_graph_accessors_smoke: outgoing_count_as avg_ms={:.3}",
            ms_per_call(elapsed, iterations)
        );
        emit_perf_metric(
            "graph_accessor",
            "outgoing_count_as",
            iterations,
            elapsed,
            &[("edges", edge_count)],
        );

        let start = Instant::now();
        for _ in 0..iterations {
            let ids = hub
                .incoming_ids(PERF_GRAPH_REL)
                .await
                .expect("incoming_ids should succeed");
            assert_eq!(ids.len(), edge_count);
        }
        let elapsed = start.elapsed();
        println!(
            "perf_store_graph_accessors_smoke: incoming_ids avg_ms={:.3}",
            ms_per_call(elapsed, iterations)
        );
        emit_perf_metric(
            "graph_accessor",
            "incoming_ids",
            iterations,
            elapsed,
            &[("edges", edge_count)],
        );

        let start = Instant::now();
        for _ in 0..iterations {
            let rows = hub
                .incoming::<PerfGraphNode>(PERF_GRAPH_REL)
                .await
                .expect("incoming rows should succeed");
            assert_eq!(rows.len(), edge_count);
        }
        let elapsed = start.elapsed();
        println!(
            "perf_store_graph_accessors_smoke: incoming_rows avg_ms={:.3}",
            ms_per_call(elapsed, iterations)
        );
        emit_perf_metric(
            "graph_accessor",
            "incoming_rows",
            iterations,
            elapsed,
            &[("edges", edge_count)],
        );

        let start = Instant::now();
        for _ in 0..iterations {
            let count = hub
                .incoming_count(PERF_GRAPH_REL)
                .await
                .expect("incoming_count should succeed");
            assert_eq!(count, edge_count as i64);
        }
        let elapsed = start.elapsed();
        println!(
            "perf_store_graph_accessors_smoke: incoming_count avg_ms={:.3}",
            ms_per_call(elapsed, iterations)
        );
        emit_perf_metric(
            "graph_accessor",
            "incoming_count",
            iterations,
            elapsed,
            &[("edges", edge_count)],
        );

        let start = Instant::now();
        for _ in 0..iterations {
            let count = hub
                .incoming_count_as::<PerfGraphNode>(PERF_GRAPH_REL)
                .await
                .expect("typed incoming_count should succeed");
            assert_eq!(count, edge_count as i64);
        }
        let elapsed = start.elapsed();
        println!(
            "perf_store_graph_accessors_smoke: incoming_count_as avg_ms={:.3}",
            ms_per_call(elapsed, iterations)
        );
        emit_perf_metric(
            "graph_accessor",
            "incoming_count_as",
            iterations,
            elapsed,
            &[("edges", edge_count)],
        );
    });
}