appdb 0.2.14

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
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,
}

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 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_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)
        );
    });
}

#[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)
        );
    });
}

#[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);
        }
        println!(
            "perf_store_graph_accessors_smoke: outgoing_ids avg_ms={:.3}",
            ms_per_call(start.elapsed(), iterations)
        );

        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);
        }
        println!(
            "perf_store_graph_accessors_smoke: outgoing_rows avg_ms={:.3}",
            ms_per_call(start.elapsed(), iterations)
        );

        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);
        }
        println!(
            "perf_store_graph_accessors_smoke: outgoing_count avg_ms={:.3}",
            ms_per_call(start.elapsed(), iterations)
        );

        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);
        }
        println!(
            "perf_store_graph_accessors_smoke: outgoing_count_as avg_ms={:.3}",
            ms_per_call(start.elapsed(), iterations)
        );

        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);
        }
        println!(
            "perf_store_graph_accessors_smoke: incoming_ids avg_ms={:.3}",
            ms_per_call(start.elapsed(), iterations)
        );

        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);
        }
        println!(
            "perf_store_graph_accessors_smoke: incoming_rows avg_ms={:.3}",
            ms_per_call(start.elapsed(), iterations)
        );

        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);
        }
        println!(
            "perf_store_graph_accessors_smoke: incoming_count avg_ms={:.3}",
            ms_per_call(start.elapsed(), iterations)
        );

        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);
        }
        println!(
            "perf_store_graph_accessors_smoke: incoming_count_as avg_ms={:.3}",
            ms_per_call(start.elapsed(), iterations)
        );
    });
}