obj-db 1.0.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
435
436
437
438
439
//! `#[derive(obj::Document)]` integration tests.
//!
//! These tests verify the proc-macro emits a working
//! `obj_core::Document` implementation. We exercise the macro against
//! a live `Db` (insert + get) to catch any wiring mismatches between
//! the generated impl and the catalog reconciliation path.
//!
//! Coverage grows across M9 commits:
//!
//! - **#75 (this commit)** — bare derive: no `#[obj(...)]` attributes
//!   anywhere; the collection name defaults to the type name and the
//!   schema version defaults to `1`.
//! - #76 — struct-level `version` / `collection` overrides.
//! - #77 — field-level `index` attributes.
//! - #78 — struct-level `index_composite` attribute.

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

/// Bare derive — no `#[obj(...)]` anywhere. Confirms the default
/// COLLECTION (type name) and VERSION (1) match what M5's
/// hand-written impls supplied.
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, obj::Document)]
struct BareDoc {
    a: u32,
    b: String,
}

#[test]
fn bare_derive_constants_match_type_name() {
    assert_eq!(<BareDoc as Document>::COLLECTION, "BareDoc");
    assert_eq!(<BareDoc as Document>::VERSION, 1);
}

#[test]
fn bare_derive_round_trips_through_db() {
    let dir = TempDir::new().expect("tmp");
    let path = dir.path().join("bare.obj");
    let db = Db::open(&path).expect("open");

    let id = db
        .insert(BareDoc {
            a: 42,
            b: "hello".to_owned(),
        })
        .expect("insert");

    let back: BareDoc = db.get::<BareDoc>(id).expect("get").expect("present");
    assert_eq!(
        back,
        BareDoc {
            a: 42,
            b: "hello".to_owned(),
        }
    );
}

#[test]
fn bare_derive_default_indexes_is_empty() {
    // The trait default `Vec::new()` survives the derive — the bare
    // derive does not emit an `indexes()` override.
    let specs = <BareDoc as Document>::indexes();
    assert!(specs.is_empty(), "no #[obj(index)] → empty indexes()");
}

// ----- #76: struct-level `#[obj(version = N)]` + `collection`. -----

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, obj::Document)]
#[obj(version = 3)]
struct CustomerV3 {
    name: String,
}

#[test]
fn version_override_sets_const() {
    assert_eq!(<CustomerV3 as Document>::VERSION, 3);
    // Collection still defaults to the type name when only `version`
    // is overridden.
    assert_eq!(<CustomerV3 as Document>::COLLECTION, "CustomerV3");
}

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, obj::Document)]
#[obj(collection = "people")]
struct Customer {
    name: String,
}

#[test]
fn collection_override_sets_const() {
    assert_eq!(<Customer as Document>::COLLECTION, "people");
    assert_eq!(<Customer as Document>::VERSION, 1);
}

#[test]
fn collection_override_round_trips_through_db() {
    let dir = TempDir::new().expect("tmp");
    let path = dir.path().join("people.obj");
    let db = Db::open(&path).expect("open");

    let id = db
        .insert(Customer {
            name: "Ada".to_owned(),
        })
        .expect("insert");

    let back: Customer = db.get::<Customer>(id).expect("get").expect("present");
    assert_eq!(back.name, "Ada");
}

// Multiple `#[obj(...)]` attributes compose — the parser merges the
// two into one `StructAttrs`.
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, obj::Document)]
#[obj(version = 2)]
#[obj(collection = "two_attrs")]
struct TwoAttrs {
    x: u32,
}

#[test]
fn two_obj_attributes_compose() {
    assert_eq!(<TwoAttrs as Document>::VERSION, 2);
    assert_eq!(<TwoAttrs as Document>::COLLECTION, "two_attrs");
}

// Combined inside a single `#[obj(...)]` — same result.
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, obj::Document)]
#[obj(version = 7, collection = "combo")]
struct Combo {
    x: u32,
}

#[test]
fn combined_obj_attribute_compose() {
    assert_eq!(<Combo as Document>::VERSION, 7);
    assert_eq!(<Combo as Document>::COLLECTION, "combo");
}

// ----- #77: field-level `#[obj(index ...)]` attrs. -----

// Pedantic clippy complains that `order_no` / `total_cents` share the
// `Order` prefix; this is a test struct whose shape mirrors the
// design.md sample exactly, so naming is fixed by spec.
#[allow(clippy::struct_field_names)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, obj::Document)]
struct Order {
    #[obj(index)]
    customer_id: u64,

    #[obj(index = unique)]
    order_no: String,

    #[obj(index = each)]
    tags: Vec<String>,

    total_cents: u64,
}

#[test]
fn field_index_attrs_emit_specs_in_declaration_order() {
    let specs = <Order as Document>::indexes();
    assert_eq!(specs.len(), 3, "three indexed fields");

    assert_eq!(specs[0].name, "customer_id");
    assert_eq!(specs[0].kind, IndexKind::Standard);
    assert_eq!(specs[0].key_paths, vec!["customer_id".to_owned()]);

    assert_eq!(specs[1].name, "order_no");
    assert_eq!(specs[1].kind, IndexKind::Unique);
    assert_eq!(specs[1].key_paths, vec!["order_no".to_owned()]);

    assert_eq!(specs[2].name, "tags");
    assert_eq!(specs[2].kind, IndexKind::Each);
    assert_eq!(specs[2].key_paths, vec!["tags".to_owned()]);
}

#[test]
fn field_index_attrs_drive_catalog_reconciliation() {
    let dir = TempDir::new().expect("tmp");
    let path = dir.path().join("orders.obj");
    let db = Db::open(&path).expect("open");

    let id_a = db
        .insert(Order {
            customer_id: 7,
            order_no: "ORD-A".to_owned(),
            tags: vec!["red".to_owned(), "blue".to_owned()],
            total_cents: 100,
        })
        .expect("insert a");
    let _id_b = db
        .insert(Order {
            customer_id: 7,
            order_no: "ORD-B".to_owned(),
            tags: vec!["green".to_owned()],
            total_cents: 250,
        })
        .expect("insert b");

    // Unique-index lookup uses the derive-declared index.
    let by_unique: Option<Order> = db
        .find_unique::<Order>("order_no", "ORD-A".to_owned())
        .expect("find_unique");
    assert_eq!(by_unique.expect("found A").customer_id, 7);

    // The standard index is exercised by the round-trip — confirm
    // get-by-id still works (insert succeeded ⇒ reconciliation
    // declared the standard index inside the same WAL txn).
    let back: Option<Order> = db.get::<Order>(id_a).expect("get a");
    assert_eq!(back.expect("present").total_cents, 100);
}

// `#[obj(index, name = "...")]` overrides the default index name.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, obj::Document)]
#[obj(collection = "named_idx")]
struct NamedIdx {
    #[obj(index, name = "by_status")]
    status: u32,
}

#[test]
fn field_index_custom_name_overrides_default() {
    let specs = <NamedIdx as Document>::indexes();
    assert_eq!(specs.len(), 1);
    assert_eq!(specs[0].name, "by_status");
    assert_eq!(specs[0].key_paths, vec!["status".to_owned()]);
    assert_eq!(specs[0].kind, IndexKind::Standard);
}

// ----- #78: struct-level `#[obj(index_composite(...))]`. -----

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, obj::Document)]
#[obj(index_composite(fields = ("customer_id", "placed_at")))]
struct OrderHistory {
    customer_id: u64,
    placed_at: u64,
    payload: String,
}

#[test]
fn composite_attr_emits_default_name() {
    let specs = <OrderHistory as Document>::indexes();
    assert_eq!(specs.len(), 1, "one composite, no field indexes");
    assert_eq!(specs[0].kind, IndexKind::Composite);
    assert_eq!(
        specs[0].key_paths,
        vec!["customer_id".to_owned(), "placed_at".to_owned()]
    );
    // Default name = fields joined by `__`.
    assert_eq!(specs[0].name, "customer_id__placed_at");
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, obj::Document)]
#[obj(index_composite(fields = ("a", "b"), name = "by_a_b"))]
struct CompositeNamed {
    a: u32,
    b: u32,
}

#[test]
fn composite_attr_emits_custom_name() {
    let specs = <CompositeNamed as Document>::indexes();
    assert_eq!(specs.len(), 1);
    assert_eq!(specs[0].name, "by_a_b");
    assert_eq!(specs[0].kind, IndexKind::Composite);
    assert_eq!(specs[0].key_paths, vec!["a".to_owned(), "b".to_owned()]);
}

// Two `#[obj(index_composite(...))]` attributes compose into two
// separate composite indexes on the same struct.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, obj::Document)]
#[obj(index_composite(fields = ("a", "b")))]
#[obj(index_composite(fields = ("b", "c"), name = "by_b_c"))]
struct TwoComposites {
    a: u32,
    b: u32,
    c: u32,
}

#[test]
fn two_composite_attrs_compose() {
    let specs = <TwoComposites as Document>::indexes();
    assert_eq!(specs.len(), 2, "two composites");
    assert_eq!(specs[0].name, "a__b");
    assert_eq!(specs[1].name, "by_b_c");
}

// Mix: per-field standard index + struct-level composite.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, obj::Document)]
#[obj(index_composite(fields = ("customer_id", "placed_at")))]
struct OrderMix {
    #[obj(index)]
    customer_id: u64,

    placed_at: u64,
    line_items: Vec<String>,
}

#[test]
fn field_and_composite_indexes_compose_field_first() {
    let specs = <OrderMix as Document>::indexes();
    assert_eq!(specs.len(), 2);
    // Field indexes come first (in declaration order), then
    // composites (in declaration order).
    assert_eq!(specs[0].kind, IndexKind::Standard);
    assert_eq!(specs[0].name, "customer_id");
    assert_eq!(specs[1].kind, IndexKind::Composite);
    assert_eq!(specs[1].name, "customer_id__placed_at");
}

// ----- Phase 1A: short composite-index syntax. -----
//
// `#[obj(index = ("a", "b"))]` is the surface declared by
// `design.md` § Indexes. It produces the same `IndexKind::Composite`
// shape as the longer `#[obj(index_composite(fields = ("a", "b")))]`,
// with the default name = fields joined by `__`. Both forms coexist.

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, obj::Document)]
#[obj(index = ("customer_id", "placed_at"))]
struct OrderShortComposite {
    customer_id: u64,
    placed_at: u64,
    payload: String,
}

#[test]
fn short_composite_attr_emits_default_name() {
    let specs = <OrderShortComposite as Document>::indexes();
    assert_eq!(specs.len(), 1, "one composite, no field indexes");
    assert_eq!(specs[0].kind, IndexKind::Composite);
    assert_eq!(
        specs[0].key_paths,
        vec!["customer_id".to_owned(), "placed_at".to_owned()]
    );
    // Default name matches the long form: fields joined by `__`.
    assert_eq!(specs[0].name, "customer_id__placed_at");
}

#[test]
fn short_composite_attr_round_trips_through_db() {
    // End-to-end: a struct using the short composite syntax inserts
    // and range-scans through the same catalog path as the long form.
    let dir = TempDir::new().expect("tmp");
    let path = dir.path().join("short_composite.obj");
    let db = Db::open(&path).expect("open");

    for i in 0..3u64 {
        let _ = db
            .insert(OrderShortComposite {
                customer_id: 7,
                placed_at: i,
                payload: format!("p{i}"),
            })
            .expect("insert");
    }

    let pairs: Vec<(Vec<u8>, OrderShortComposite)> = db
        .read_transaction(|tx| {
            tx.collection::<OrderShortComposite>()?
                .index_range("customer_id__placed_at", ..)?
                .collect()
        })
        .expect("range");
    assert_eq!(pairs.len(), 3);
    for window in pairs.windows(2) {
        assert!(window[0].0 <= window[1].0);
    }
}

// Two short-form composites compose into two separate Composite specs,
// in declaration order — same composition behaviour as the long form.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, obj::Document)]
#[obj(index = ("a", "b"))]
#[obj(index = ("b", "c"))]
struct TwoShortComposites {
    a: u32,
    b: u32,
    c: u32,
}

#[test]
fn two_short_composite_attrs_compose() {
    let specs = <TwoShortComposites as Document>::indexes();
    assert_eq!(specs.len(), 2, "two composites");
    assert_eq!(specs[0].name, "a__b");
    assert_eq!(specs[0].key_paths, vec!["a".to_owned(), "b".to_owned()]);
    assert_eq!(specs[1].name, "b__c");
    assert_eq!(specs[1].key_paths, vec!["b".to_owned(), "c".to_owned()]);
}

// The long and short forms can be mixed on the same struct.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, obj::Document)]
#[obj(index = ("a", "b"))]
#[obj(index_composite(fields = ("b", "c"), name = "by_b_c"))]
struct MixedCompositeForms {
    a: u32,
    b: u32,
    c: u32,
}

#[test]
fn mixed_composite_forms_compose() {
    let specs = <MixedCompositeForms as Document>::indexes();
    assert_eq!(specs.len(), 2);
    assert_eq!(specs[0].name, "a__b");
    assert_eq!(specs[1].name, "by_b_c");
}

#[test]
fn composite_attr_drives_catalog_reconciliation_with_range_scan() {
    // End-to-end: a struct with a derive-declared composite index can
    // be range-scanned via `index_range` over the composite's name.
    let dir = TempDir::new().expect("tmp");
    let path = dir.path().join("history.obj");
    let db = Db::open(&path).expect("open");

    for i in 0..3u64 {
        let _ = db
            .insert(OrderHistory {
                customer_id: 7,
                placed_at: i,
                payload: format!("p{i}"),
            })
            .expect("insert");
    }

    let pairs: Vec<(Vec<u8>, OrderHistory)> = db
        .read_transaction(|tx| {
            tx.collection::<OrderHistory>()?
                .index_range("customer_id__placed_at", ..)?
                .collect()
        })
        .expect("range");
    assert_eq!(pairs.len(), 3);
    // B+tree invariant: keys are lexicographically non-decreasing.
    for window in pairs.windows(2) {
        assert!(window[0].0 <= window[1].0);
    }
}