obj-db 1.1.2

Embedded document database. Stable file format, full ACID, single-file portability.
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
//! M11 #93 — `Db::attach` acceptance tests.
//!
//! Create two Dbs, populate both, attach one to the other, read
//! across both in a single `read_transaction`. Verify writes to the
//! attached collection error cleanly. Detach and confirm the
//! calling Db's own collections still work.

use obj::{Db, Document, Error};
use serde::{Deserialize, Serialize};
use tempfile::TempDir;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Order {
    customer_id: u64,
    total_cents: u64,
}

impl Document for Order {
    const COLLECTION: &'static str = "orders";
    const VERSION: u32 = 1;
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct ArchivedOrder {
    customer_id: u64,
    total_cents: u64,
    archived_at_ms: u64,
}

// Namespaced collection: lives in the attached database.
impl Document for ArchivedOrder {
    const COLLECTION: &'static str = "archive.orders";
    const VERSION: u32 = 1;
}

#[test]
fn attached_db_visible_in_read_transaction() {
    let dir = TempDir::new().expect("tmp");
    let main_path = dir.path().join("main.obj");
    let archive_path = dir.path().join("archive.obj");

    // 1) Populate the archive db. Note: its collection name as
    // stored is `"orders"`, not `"archive.orders"` — the namespace
    // prefix only matters on the CALLING side.
    {
        #[derive(Debug, Clone, Serialize, Deserialize)]
        struct ArchiveSide {
            customer_id: u64,
            total_cents: u64,
            archived_at_ms: u64,
        }
        impl Document for ArchiveSide {
            const COLLECTION: &'static str = "orders";
            const VERSION: u32 = 1;
        }
        let archive_db = Db::open(&archive_path).expect("open archive");
        archive_db
            .insert(ArchiveSide {
                customer_id: 1,
                total_cents: 999,
                archived_at_ms: 42,
            })
            .expect("insert into archive");
    }

    // 2) Open main db, populate live orders, attach archive.
    let mut main_db = Db::open(&main_path).expect("open main");
    main_db
        .insert(Order {
            customer_id: 1,
            total_cents: 100,
        })
        .expect("insert live");
    main_db.attach(&archive_path, "archive").expect("attach");

    // 3) Read across both in one read_transaction.
    main_db
        .read_transaction(|tx| {
            let live = tx.collection::<Order>()?;
            let archived = tx.collection::<ArchivedOrder>()?;
            // Live collection has a doc.
            let live_docs = live.all()?;
            assert_eq!(live_docs.len(), 1);
            // Archived collection has a doc too.
            let arch_docs = archived.all()?;
            assert_eq!(arch_docs.len(), 1);
            assert_eq!(arch_docs[0].1.archived_at_ms, 42);
            Ok(())
        })
        .expect("read across attached");
}

#[test]
fn writes_to_attached_collection_are_rejected() {
    let dir = TempDir::new().expect("tmp");
    let main_path = dir.path().join("main.obj");
    let archive_path = dir.path().join("archive.obj");

    {
        #[derive(Debug, Clone, Serialize, Deserialize)]
        struct ArchiveSide {
            customer_id: u64,
            total_cents: u64,
            archived_at_ms: u64,
        }
        impl Document for ArchiveSide {
            const COLLECTION: &'static str = "orders";
            const VERSION: u32 = 1;
        }
        let archive_db = Db::open(&archive_path).expect("open archive");
        archive_db
            .insert(ArchiveSide {
                customer_id: 1,
                total_cents: 999,
                archived_at_ms: 42,
            })
            .expect("insert");
    }
    let mut main_db = Db::open(&main_path).expect("open main");
    main_db.attach(&archive_path, "archive").expect("attach");

    let err = main_db
        .insert(ArchivedOrder {
            customer_id: 2,
            total_cents: 1,
            archived_at_ms: 0,
        })
        .expect_err("insert into attached must fail");
    assert!(
        matches!(
            err,
            Error::AttachedDatabaseIsReadOnly {
                ref namespace,
                ..
            } if namespace == "archive"
        ),
        "expected AttachedDatabaseIsReadOnly; got {err:?}",
    );
}

#[test]
fn duplicate_namespace_is_rejected() {
    let dir = TempDir::new().expect("tmp");
    let main_path = dir.path().join("main.obj");
    let archive_path = dir.path().join("archive.obj");
    {
        let _ = Db::open(&archive_path).expect("create archive");
    }
    let mut main_db = Db::open(&main_path).expect("open");
    main_db
        .attach(&archive_path, "archive")
        .expect("first attach");
    let err = main_db
        .attach(&archive_path, "archive")
        .expect_err("second attach");
    assert!(
        matches!(
            err,
            Error::AttachmentAlreadyExists { ref namespace }
            if namespace == "archive"
        ),
        "expected AttachmentAlreadyExists; got {err:?}",
    );
}

#[test]
fn detach_removes_attachment() {
    let dir = TempDir::new().expect("tmp");
    let main_path = dir.path().join("main.obj");
    let archive_path = dir.path().join("archive.obj");
    {
        let _ = Db::open(&archive_path).expect("create archive");
    }
    let mut main_db = Db::open(&main_path).expect("open");
    main_db.attach(&archive_path, "archive").expect("attach");
    main_db.detach("archive").expect("detach");
    // Reads against the (now-detached) namespace surface the
    // namespace-unknown error.
    let err = main_db
        .read_transaction(|tx| tx.collection::<ArchivedOrder>().map(|_| ()))
        .expect_err("read on detached namespace");
    assert!(
        matches!(
            err,
            Error::CollectionNamespaceUnknown { ref namespace }
            if namespace == "archive"
        ),
        "expected CollectionNamespaceUnknown; got {err:?}",
    );
    // Re-attaching the same namespace succeeds after detach.
    main_db.attach(&archive_path, "archive").expect("re-attach");
}

#[test]
fn detach_unknown_namespace_errors() {
    let dir = TempDir::new().expect("tmp");
    let main_path = dir.path().join("main.obj");
    let mut main_db = Db::open(&main_path).expect("open");
    let err = main_db.detach("ghost").expect_err("unknown namespace");
    assert!(
        matches!(
            err,
            Error::CollectionNamespaceUnknown { ref namespace }
            if namespace == "ghost"
        ),
        "expected CollectionNamespaceUnknown; got {err:?}",
    );
}

/// M11 #94 — Phase 1B: `Db::collection::<T>(name)` reads from a
/// runtime-named collection (here a namespaced attached one)
/// without requiring `T::COLLECTION` to carry the namespace.
///
/// Mirrors `design.md` § Portability:
///
/// ```text
/// db.attach("archive.obj", "archive")?;
/// let archived: Vec<Order> = db
///     .collection::<Order>("archive.orders")
///     .all()?
///     .collect();
/// ```
///
/// `Order`'s `COLLECTION` is `"orders"` — the namespace prefix lives
/// only on the calling side, supplied at the runtime accessor's call
/// site.
#[test]
fn db_collection_reads_from_attached_namespace() {
    let dir = TempDir::new().expect("tmp");
    let main_path = dir.path().join("main.obj");
    let archive_path = dir.path().join("archive.obj");

    // 1) Populate the archive database with 3 orders. Internal
    // collection name is `"orders"` — same as `Order::COLLECTION`.
    {
        let archive_db = Db::open(&archive_path).expect("open archive");
        for i in 1..=3 {
            archive_db
                .insert(Order {
                    customer_id: i,
                    total_cents: i * 100,
                })
                .expect("seed archive");
        }
    }

    // 2) Open the main db, attach archive under `"archive"`.
    let mut main_db = Db::open(&main_path).expect("open main");
    main_db.attach(&archive_path, "archive").expect("attach");

    // 3) Read the attached collection via the new runtime accessor.
    let archived: Vec<Order> = main_db
        .collection::<Order>("archive.orders")
        .all()
        .expect("all on attached")
        .into_iter()
        .map(|(_id, doc)| doc)
        .collect();
    assert_eq!(archived.len(), 3);
    let totals: Vec<u64> = archived.iter().map(|o| o.total_cents).collect();
    assert!(totals.contains(&100));
    assert!(totals.contains(&200));
    assert!(totals.contains(&300));

    // 4) Reads via the main db's OWN `Db::all::<Order>()` still
    // resolve against the calling-db-side `"orders"` collection;
    // since we never inserted into main, that collection has not
    // been registered yet — `Db::all` surfaces
    // `Error::CollectionNotFound`, the existing one-shot read
    // semantics. The attached namespace's collection (read above)
    // is unaffected.
    let err = main_db
        .all::<Order>()
        .expect_err("calling-db `orders` was never written");
    assert!(
        matches!(err, Error::CollectionNotFound { ref name } if name == "orders"),
        "expected CollectionNotFound for calling-db `orders`; got {err:?}",
    );
}

/// `Db::collection::<T>(name)` against an unknown namespace
/// surfaces the namespace-unknown error at the first method call
/// (construction is infallible).
#[test]
fn db_collection_unknown_namespace_errors_at_call_site() {
    let dir = TempDir::new().expect("tmp");
    let main_path = dir.path().join("main.obj");
    let main_db = Db::open(&main_path).expect("open main");
    // Construction is infallible — no `?` here. The error surfaces
    // when `.all()` opens its private read transaction.
    let handle = main_db.collection::<Order>("ghost.orders");
    let err = handle.all().expect_err("unknown namespace");
    assert!(
        matches!(
            err,
            Error::CollectionNamespaceUnknown { ref namespace }
            if namespace == "ghost"
        ),
        "expected CollectionNamespaceUnknown; got {err:?}",
    );
}

/// `Db::collection::<T>(name)` reads from a runtime-named
/// collection on the **calling** Db (no namespace prefix). Useful
/// when the type's declared `COLLECTION` differs from the name the
/// caller wants to consult at runtime (e.g. multi-tenant schemas).
#[test]
fn db_collection_reads_from_calling_db_runtime_name() {
    let dir = TempDir::new().expect("tmp");
    let main_path = dir.path().join("main.obj");
    let main_db = Db::open(&main_path).expect("open main");
    // Insert into `Order::COLLECTION` ("orders") via the typed
    // accessor.
    main_db
        .insert(Order {
            customer_id: 1,
            total_cents: 42,
        })
        .expect("insert");

    // Read back through the runtime accessor with the SAME name.
    let docs: Vec<Order> = main_db
        .collection::<Order>("orders")
        .all()
        .expect("all on calling db")
        .into_iter()
        .map(|(_id, doc)| doc)
        .collect();
    assert_eq!(docs.len(), 1);
    assert_eq!(docs[0].total_cents, 42);
}

/// Writes through `Db::collection::<T>(name)` are rejected: the
/// runtime accessor is read-only by design (documented on the
/// rustdoc). Verified through `.insert` failing with
/// `Error::ReadOnly`.
#[test]
fn db_collection_rejects_writes() {
    let dir = TempDir::new().expect("tmp");
    let main_path = dir.path().join("main.obj");
    let main_db = Db::open(&main_path).expect("open main");
    let handle = main_db.collection::<Order>("orders");
    let err = handle
        .insert(Order {
            customer_id: 1,
            total_cents: 7,
        })
        .expect_err("insert must be rejected");
    assert!(
        matches!(err, Error::ReadOnly { .. }),
        "expected ReadOnly; got {err:?}",
    );
}

#[test]
fn calling_db_collection_still_works_after_detach() {
    let dir = TempDir::new().expect("tmp");
    let main_path = dir.path().join("main.obj");
    let archive_path = dir.path().join("archive.obj");
    {
        let _ = Db::open(&archive_path).expect("create archive");
    }
    let mut main_db = Db::open(&main_path).expect("open");
    let id = main_db
        .insert(Order {
            customer_id: 7,
            total_cents: 77,
        })
        .expect("insert");
    main_db.attach(&archive_path, "archive").expect("attach");
    main_db.detach("archive").expect("detach");
    let got: Option<Order> = main_db.get(id).expect("get after detach");
    assert!(got.is_some(), "main-db reads must still work after detach");
}

/// #83 (b)+(c): the fused one-shot `Db::get` path (single pager lock,
/// empty-attached fast path) is observably identical to the explicit
/// `read_transaction(|tx| tx.collection()?.get())` handle path — the
/// hit, the miss, and the unknown-collection arms all match, with no
/// database attached.
#[test]
fn fused_get_matches_handle_path_with_empty_attached() {
    // A collection that is never written — the fused-get
    // unknown-collection arm probes it below.
    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct NeverWritten {
        x: u64,
    }
    impl Document for NeverWritten {
        const COLLECTION: &'static str = "never_written_collection";
        const VERSION: u32 = 1;
    }

    let dir = TempDir::new().expect("tmp");
    let main_path = dir.path().join("main.obj");
    let main_db = Db::open(&main_path).expect("open");
    let id = main_db
        .insert(Order {
            customer_id: 42,
            total_cents: 4_200,
        })
        .expect("insert");

    // Hit: fused `Db::get` equals the handle-path get for the same id.
    let fused: Option<Order> = main_db.get(id).expect("fused get");
    let via_handle: Option<Order> = main_db
        .read_transaction(|tx| tx.collection::<Order>()?.get(id))
        .expect("handle get");
    assert_eq!(fused, via_handle, "fused get must match the handle path");
    assert_eq!(
        fused,
        Some(Order {
            customer_id: 42,
            total_cents: 4_200,
        }),
        "fused get must return the inserted doc",
    );

    // Miss: an absent id is `Ok(None)` on both paths.
    let absent_id = obj::Id::try_new(id.get() + 1_000).expect("nonzero id");
    let fused_miss: Option<Order> = main_db.get(absent_id).expect("fused miss");
    assert!(fused_miss.is_none(), "absent id must read as None");

    // Unknown collection: surfaces `CollectionNotFound`, matching the
    // handle path's open-time contract.
    let probe = obj::Id::try_new(1).expect("nonzero id");
    let err = main_db
        .get::<NeverWritten>(probe)
        .expect_err("unknown collection");
    assert!(
        matches!(err, Error::CollectionNotFound { ref name } if name == "never_written_collection"),
        "fused get on an unknown collection must surface CollectionNotFound; got {err:?}",
    );
}