oximod 0.2.5

MongoDB ODM for Rust inspired by Mongoose
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
use futures_util::TryStreamExt;
use mongodb::{
    IndexModel,
    bson::{Bson, DateTime, doc, oid::ObjectId},
    options::{CollationStrength, IndexVersion, Sphere2DIndexVersion, TextIndexVersion},
};
use oximod::Model;
use serde::{Deserialize, Serialize};
use std::{thread::sleep, time::Duration};
use testresult::TestResult;

mod common;
use common::init;

async fn reset_collection<T>() -> Result<(), Box<dyn std::error::Error>>
where
    T: Model,
{
    let collection = T::get_collection()?;
    let _ = collection.drop().await;
    Ok(())
}

async fn find_index_by_name<T>(name: &str) -> Result<Option<IndexModel>, Box<dyn std::error::Error>>
where
    T: Model,
{
    let mut cursor = T::get_collection()?.list_indexes().await?;

    while let Some(index) = cursor.try_next().await? {
        if index.options.as_ref().and_then(|opts| opts.name.as_deref()) == Some(name) {
            return Ok(Some(index));
        }
    }

    Ok(None)
}

fn assert_key_is(index: &IndexModel, field: &str, expected: Bson) {
    let actual = index.keys.get(field);
    assert_eq!(
        actual,
        Some(&expected),
        "expected index key `{}` to be {:?}, got {:?}",
        field,
        expected,
        actual
    );
}

fn assert_option_name(index: &IndexModel, expected_name: &str) {
    let actual = index.options.as_ref().and_then(|opts| opts.name.as_deref());
    assert_eq!(actual, Some(expected_name), "unexpected index name");
}

fn assert_text_index_shape(index: &IndexModel) {
    assert_eq!(
        index.keys.get("_fts"),
        Some(&Bson::String("text".to_string())),
        "expected MongoDB text index marker `_fts: \"text\"`"
    );
    assert_eq!(
        index.keys.get("_ftsx"),
        Some(&Bson::Int32(1)),
        "expected MongoDB text index marker `_ftsx: 1`"
    );
}

// Run test: cargo nextest run creates_indexes_correctly
#[tokio::test]
async fn creates_indexes_correctly() -> TestResult {
    init().await?;

    #[derive(Model, Serialize, Deserialize)]
    #[db("test")]
    #[collection("index_test_creates_indexes_correctly")]
    pub struct User {
        #[serde(skip_serializing_if = "Option::is_none")]
        _id: Option<ObjectId>,

        #[index(unique, name = "name_idx")]
        name: String,

        #[index(sparse, order = "-1", name = "age_desc_sparse_idx")]
        age: Option<i32>,

        #[index(expire_after_secs = 3600, name = "created_at_ttl_idx")]
        created_at: Option<DateTime>,

        active: bool,
    }

    reset_collection::<User>().await?;

    let user = User::default()
        .name("IndexUser")
        .age(25)
        .created_at(DateTime::now())
        .active(true);

    let result = user.save().await?;
    assert_ne!(result, ObjectId::default());

    let name_index = find_index_by_name::<User>("name_idx")
        .await?
        .expect("Expected index `name_idx` to exist");
    assert_option_name(&name_index, "name_idx");
    assert_key_is(&name_index, "name", Bson::Int32(1));
    assert_eq!(
        name_index.options.as_ref().and_then(|opts| opts.unique),
        Some(true),
        "Expected `name_idx` to be unique"
    );

    let age_index = find_index_by_name::<User>("age_desc_sparse_idx")
        .await?
        .expect("Expected index `age_desc_sparse_idx` to exist");
    assert_option_name(&age_index, "age_desc_sparse_idx");
    assert_key_is(&age_index, "age", Bson::Int32(-1));
    assert_eq!(
        age_index.options.as_ref().and_then(|opts| opts.sparse),
        Some(true),
        "Expected `age_desc_sparse_idx` to be sparse"
    );

    let ttl_index = find_index_by_name::<User>("created_at_ttl_idx")
        .await?
        .expect("Expected index `created_at_ttl_idx` to exist");
    assert_option_name(&ttl_index, "created_at_ttl_idx");
    assert_key_is(&ttl_index, "created_at", Bson::Int32(1));
    assert_eq!(
        ttl_index
            .options
            .as_ref()
            .and_then(|opts| opts.expire_after)
            .map(|d| d.as_secs()),
        Some(3600),
        "Expected TTL to be 3600 seconds"
    );

    Ok(())
}

// Run test: cargo nextest run ttl_index_removes_expired_documents
#[tokio::test]
async fn ttl_index_removes_expired_documents() -> TestResult {
    init().await?;

    #[derive(Model, Serialize, Deserialize)]
    #[db("test")]
    #[collection("ttl_test_removes_expired_documents")]
    pub struct Session {
        #[serde(skip_serializing_if = "Option::is_none")]
        _id: Option<ObjectId>,

        #[index(expire_after_secs = 2, name = "session_ttl_idx")]
        created_at: Option<DateTime>,
    }

    reset_collection::<Session>().await?;

    let expired_session = Session::default().created_at(DateTime::from_millis(
        DateTime::now().timestamp_millis() - 10_000,
    ));

    expired_session.save().await?;

    let ttl_index = find_index_by_name::<Session>("session_ttl_idx")
        .await?
        .expect("Expected TTL index `session_ttl_idx` to exist");
    assert_option_name(&ttl_index, "session_ttl_idx");
    assert_key_is(&ttl_index, "created_at", Bson::Int32(1));
    assert_eq!(
        ttl_index
            .options
            .as_ref()
            .and_then(|opts| opts.expire_after)
            .map(|d| d.as_secs()),
        Some(2),
        "Expected TTL to be 2 seconds"
    );

    sleep(Duration::from_secs(65));

    let collection = Session::get_collection()?;
    let remaining = collection.count_documents(doc! {}).await?;
    assert_eq!(remaining, 0, "Expected document to be expired and deleted");

    Ok(())
}

// Run test: cargo nextest run index_version_is_applied_correctly
#[tokio::test]
async fn index_version_is_applied_correctly() -> TestResult {
    init().await?;

    #[derive(Model, Serialize, Deserialize)]
    #[db("test")]
    #[collection("index_version_is_applied_correctly")]
    pub struct VersionedIndex {
        #[serde(skip_serializing_if = "Option::is_none")]
        _id: Option<ObjectId>,

        #[index(version = 2, name = "v2_idx")]
        data: String,
    }

    reset_collection::<VersionedIndex>().await?;

    let item = VersionedIndex::default().data("hello");
    item.save().await?;

    let index = find_index_by_name::<VersionedIndex>("v2_idx")
        .await?
        .expect("Expected index with name `v2_idx`");
    assert_option_name(&index, "v2_idx");
    assert_key_is(&index, "data", Bson::Int32(1));

    let version = index.options.as_ref().and_then(|opts| opts.version.clone());
    assert!(
        matches!(version, Some(IndexVersion::V2)),
        "Expected `v2_idx` to use IndexVersion::V2, got {:?}",
        version
    );

    Ok(())
}

// Run test: cargo nextest run text_index_version_is_applied_correctly
#[tokio::test]
async fn text_index_version_is_applied_correctly() -> TestResult {
    init().await?;

    #[derive(Model, Serialize, Deserialize)]
    #[db("test")]
    #[collection("text_index_version_is_applied_correctly")]
    pub struct TestModel {
        #[serde(skip_serializing_if = "Option::is_none")]
        _id: Option<ObjectId>,

        #[index(text_index_version = 2, name = "text_v2_idx")]
        data: String,
    }

    reset_collection::<TestModel>().await?;

    let item = TestModel::default().data("hello");
    item.save().await?;

    let index = find_index_by_name::<TestModel>("text_v2_idx")
        .await?
        .expect("Expected index with name `text_v2_idx`");
    assert_option_name(&index, "text_v2_idx");
    assert_text_index_shape(&index);

    let text_options = index
        .options
        .as_ref()
        .expect("Expected `text_v2_idx` to have options");

    let text_index_version = text_options.text_index_version.clone();
    assert!(
        matches!(text_index_version, Some(TextIndexVersion::V2)),
        "Expected `text_v2_idx` to use TextIndexVersion::V2, got {:?}",
        text_index_version
    );

    let weights = text_options
        .weights
        .as_ref()
        .expect("Expected `text_v2_idx` to have weights");
    assert_eq!(
        weights.get("data"),
        Some(&Bson::Int32(1)),
        "Expected MongoDB to register `data` in text index weights"
    );

    Ok(())
}

// Run test: cargo nextest run hidden_index_is_applied_correctly
#[tokio::test]
async fn hidden_index_is_applied_correctly() -> TestResult {
    init().await?;

    #[derive(Model, Serialize, Deserialize)]
    #[db("test")]
    #[collection("hidden_index_is_applied_correctly")]
    struct HiddenTest {
        #[index(hidden, name = "hidden_idx")]
        secret: String,
    }

    reset_collection::<HiddenTest>().await?;

    let doc = HiddenTest::default().secret("classified");
    doc.save().await?;

    let index = find_index_by_name::<HiddenTest>("hidden_idx")
        .await?
        .expect("Expected index `hidden_idx` not found");
    assert_option_name(&index, "hidden_idx");
    assert_key_is(&index, "secret", Bson::Int32(1));
    assert_eq!(
        index.options.as_ref().and_then(|opts| opts.hidden),
        Some(true),
        "Expected `hidden_idx` to be hidden"
    );

    Ok(())
}

// Run test: cargo nextest run creates_indexes_correctly_fails_on_duplicate
#[tokio::test]
async fn creates_indexes_correctly_fails_on_duplicate() -> TestResult {
    init().await?;

    #[derive(Model, Serialize, Deserialize)]
    #[db("test")]
    #[collection("index_test_duplicate_fails")]
    pub struct User {
        #[serde(skip_serializing_if = "Option::is_none")]
        _id: Option<ObjectId>,

        #[index(unique, name = "name_idx")]
        name: String,
    }

    reset_collection::<User>().await?;

    let user1 = User::default().name("IndexUser");
    user1.save().await?;

    let index = find_index_by_name::<User>("name_idx")
        .await?
        .expect("Expected index `name_idx` to exist");
    assert_option_name(&index, "name_idx");
    assert_key_is(&index, "name", Bson::Int32(1));
    assert_eq!(
        index.options.as_ref().and_then(|opts| opts.unique),
        Some(true),
        "Expected `name_idx` to be unique"
    );

    let user2 = User::default().name("IndexUser");
    let dup_result = user2.save().await;
    assert!(
        dup_result.is_err(),
        "Expected duplicate unique index to fail"
    );

    Ok(())
}

// Run test: cargo nextest run index_init_respects_overridden_retry_and_timeout
#[tokio::test]
async fn index_init_respects_overridden_retry_and_timeout() -> TestResult {
    init().await?;

    #[derive(Model, Serialize, Deserialize)]
    #[db("test")]
    #[collection("index_init_overrides")]
    #[index_max_retries(7)]
    #[index_max_init_seconds(45)]
    pub struct UserOverride {
        #[serde(skip_serializing_if = "Option::is_none")]
        _id: Option<ObjectId>,

        #[index(name = "overrides_name_idx")]
        name: String,
    }

    reset_collection::<UserOverride>().await?;

    let doc = UserOverride::default().name("User1");
    let result = doc.save().await?;
    assert_ne!(result, ObjectId::default());

    let index = find_index_by_name::<UserOverride>("overrides_name_idx")
        .await?
        .expect("Expected index `overrides_name_idx` to exist");
    assert_option_name(&index, "overrides_name_idx");
    assert_key_is(&index, "name", Bson::Int32(1));

    Ok(())
}

// Run test: cargo nextest run advanced_index_features_are_applied_correctly
#[tokio::test]
async fn advanced_index_features_are_applied_correctly() -> TestResult {
    init().await?;

    #[derive(Model, Serialize, Deserialize)]
    #[db("test")]
    #[collection("advanced_index_features")]
    struct Advanced {
        #[serde(skip_serializing_if = "Option::is_none")]
        _id: Option<ObjectId>,

        #[index(text, weight = 5, default_language = "english", name = "text_idx")]
        title: String,

        #[index(hashed, name = "hashed_idx")]
        user_id: String,

        #[index(case_insensitive, name = "ci_idx")]
        email: String,

        #[index(geo_2dsphere, geo_2dsphere_index_version = 3, name = "geo_idx")]
        location: Vec<f64>,
    }

    reset_collection::<Advanced>().await?;

    let doc = Advanced::default()
        .title("hello world")
        .user_id("user123")
        .email("TEST@EMAIL.COM")
        .location(vec![0.0, 0.0]);

    doc.save().await?;

    let text_index = find_index_by_name::<Advanced>("text_idx")
        .await?
        .expect("Expected index `text_idx` to exist");
    assert_option_name(&text_index, "text_idx");
    assert_text_index_shape(&text_index);

    let text_options = text_index
        .options
        .as_ref()
        .expect("Expected `text_idx` to have options");
    assert_eq!(
        text_options.default_language.as_deref(),
        Some("english"),
        "Expected `text_idx` default language to be `english`"
    );
    let weights = text_options
        .weights
        .as_ref()
        .expect("Expected `text_idx` to have weights");
    assert_eq!(
        weights.get("title"),
        Some(&Bson::Int32(5)),
        "Expected `title` weight to be 5"
    );

    let hashed_index = find_index_by_name::<Advanced>("hashed_idx")
        .await?
        .expect("Expected index `hashed_idx` to exist");
    assert_option_name(&hashed_index, "hashed_idx");
    assert_key_is(&hashed_index, "user_id", Bson::String("hashed".to_string()));

    let ci_index = find_index_by_name::<Advanced>("ci_idx")
        .await?
        .expect("Expected index `ci_idx` to exist");
    assert_option_name(&ci_index, "ci_idx");
    assert_key_is(&ci_index, "email", Bson::Int32(1));

    let collation = ci_index
        .options
        .as_ref()
        .and_then(|opts| opts.collation.as_ref())
        .expect("Expected `ci_idx` to have collation");
    assert_eq!(
        collation.locale, "en",
        "Expected `ci_idx` collation locale to be `en`"
    );
    assert!(
        matches!(
            collation.strength.as_ref(),
            Some(CollationStrength::Secondary)
        ),
        "Expected `ci_idx` collation strength to be Secondary"
    );

    let geo_index = find_index_by_name::<Advanced>("geo_idx")
        .await?
        .expect("Expected index `geo_idx` to exist");
    assert_option_name(&geo_index, "geo_idx");
    assert_key_is(&geo_index, "location", Bson::String("2dsphere".to_string()));

    let sphere_version = geo_index
        .options
        .as_ref()
        .and_then(|opts| opts.sphere_2d_index_version.clone());
    assert!(
        matches!(sphere_version, Some(Sphere2DIndexVersion::V3)),
        "Expected `geo_idx` to use Sphere2DIndexVersion::V3, got {:?}",
        sphere_version
    );

    Ok(())
}