oximod_core 0.2.4

The core logic and error handling for OxiMod, a MongoDB ODM for Rust.
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 crate::error::oximod_error::OxiModError;
use crate::feature::conn::client::OxiClient;
use async_trait;
use mongodb::Client;
use mongodb::{
    Collection,
    bson::{Document, doc, oid::ObjectId},
    results::{DeleteResult, UpdateResult},
};
use serde::de::DeserializeOwned;

/// Core async model interface for OxiMod-backed MongoDB documents.
///
/// This trait is typically implemented automatically via `#[derive(Model)]`.
/// Provides a minimal typed API for:
///
/// - accessing a model's MongoDB collection,
/// - saving a model instance,
/// - clearing all documents from a model's collection,
/// - querying documents by `_id`,
/// - deleting and updating documents by `_id`,
/// - checking document existence,
/// - counting documents,
/// - working either with an explicit [`mongodb::Client`] or the globally
///   initialized [`OxiClient`].
///
/// # Design
///
/// `Model` is intentionally lightweight. OxiMod provides schema-awareness,
/// builder-style ergonomics, and validation, while still exposing the underlying
/// MongoDB driver patterns when needed.
///
/// In practice:
///
/// - use [`Model::save`] and [`Model::clear`] for common persistence operations,
/// - use helpers like [`Model::find_by_id`], [`Model::delete_by_id`],
///   [`Model::update_by_id`], [`Model::exists`], and [`Model::count`] for
///   common convenience workflows,
/// - use [`Model::get_collection`] when you want direct access to
///   `mongodb::Collection<Self>`,
/// - use [`Model::get_document_collection`] when you want a raw
///   `mongodb::Collection<Document>` for untyped operations.
///
/// # Global vs explicit client usage
///
/// The trait supports two access patterns:
///
/// ## 1. Global client
///
/// Methods like [`Model::save`], [`Model::clear`], [`Model::get_collection`],
/// [`Model::find_by_id`], and [`Model::count`] use the globally initialized
/// [`OxiClient`].
///
/// ## 2. Explicit client
///
/// Methods ending in `_from`, such as [`Model::save_from`] and
/// [`Model::find_by_id_from`], operate on a caller-provided [`mongodb::Client`].
///
/// This is useful for:
///
/// - tests,
/// - scoped client lifetimes,
/// - multi-client or multi-database setups,
/// - avoiding reliance on global state.
///
/// # Typed vs raw collections
///
/// [`Model::get_collection`] and [`Model::get_collection_from`] return
/// `Collection<Self>`, which is the preferred typed API.
///
/// [`Model::get_document_collection`] and
/// [`Model::get_document_collection_from`] return `Collection<Document>`,
/// which is useful when you need to work with raw BSON documents.
///
/// # Implementors
///
/// This trait is generally not implemented manually. Instead, derive it:
///
/// ```ignore
/// use mongodb::bson::oid::ObjectId;
/// use oximod::Model;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Debug, Serialize, Deserialize, Model)]
/// #[db("app_db")]
/// #[collection("users")]
/// struct User {
///     #[serde(skip_serializing_if = "Option::is_none")]
///     _id: Option<ObjectId>,
///     name: String,
///     age: i32,
/// }
/// ```
///
/// # Thread-safety
///
/// Implementors must be:
///
/// - [`Send`]
/// - [`Sync`]
/// - [`Sized`]
///
/// so model operations can safely participate in async workflows.
#[async_trait::async_trait]
pub trait Model
where
    Self: DeserializeOwned + Send + Sync + Sized,
{
    /// Returns the typed MongoDB collection for this model using an explicit client.
    ///
    /// This is the fundamental collection accessor that implementors are expected
    /// to provide. It resolves the model's configured database and collection name
    /// and returns a typed `Collection<Self>`.
    ///
    /// Most users will prefer [`Model::get_collection`] unless they specifically
    /// need to work with an explicit client.
    ///
    /// # Parameters
    ///
    /// - `client`: A MongoDB client to use for resolving the collection.
    ///
    /// # Returns
    ///
    /// A typed [`mongodb::Collection`] whose document type is `Self`.
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if the collection cannot be resolved.
    fn get_collection_from(client: &mongodb::Client) -> Result<Collection<Self>, OxiModError>;

    /// Returns the raw BSON document collection for this model using an explicit client.
    ///
    /// This is a convenience wrapper around [`Model::get_collection_from`] that
    /// converts the typed collection into `Collection<Document>`.
    ///
    /// This is useful when you want to work directly with raw BSON documents
    /// instead of strongly typed model instances.
    ///
    /// # Parameters
    ///
    /// - `client`: A MongoDB client to use for resolving the collection.
    ///
    /// # Returns
    ///
    /// A raw [`mongodb::Collection`] of [`mongodb::bson::Document`].
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if the underlying typed collection cannot be resolved.
    fn get_document_collection_from(
        client: &mongodb::Client,
    ) -> Result<Collection<Document>, OxiModError> {
        Ok(Self::get_collection_from(client)?.clone_with_type::<Document>())
    }

    /// Persists this model instance using an explicit MongoDB client.
    ///
    /// Implementations are expected to serialize and insert `self` into the model's
    /// configured collection, returning the inserted document's [`ObjectId`].
    ///
    /// This method is the explicit-client counterpart to [`Model::save`].
    ///
    /// # Parameters
    ///
    /// - `client`: The MongoDB client to use for the save operation.
    ///
    /// # Returns
    ///
    /// The inserted document's [`ObjectId`].
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if validation, serialization, collection access,
    /// or insertion fails.
    async fn save_from(&self, client: &mongodb::Client) -> Result<ObjectId, OxiModError>;

    /// Persists this model instance using an explicit MongoDB client with mutable access.
    ///
    /// Implementations are expected to serialize and insert `self` into the model's
    /// configured collection, returning the inserted document's [`ObjectId`].
    ///
    /// This method is the explicit-client counterpart to [`Model::save_mut`].
    ///
    /// Unlike [`Model::save_from`], this method allows mutable access to the model
    /// before persistence. This enables lifecycle hooks such as
    /// [`crate::feature::hooks::Hooks::pre_save_mut`] and [`crate::feature::hooks::Hooks::post_save_mut`] to modify or observe
    /// the model during the save workflow.
    ///
    /// This is useful when the save operation needs to perform normalization
    /// or other in-place changes before validation and insertion.
    ///
    /// # Parameters
    ///
    /// - `client`: The MongoDB client to use for the save operation.
    ///
    /// # Returns
    ///
    /// The inserted document's [`ObjectId`].
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if validation, serialization, collection access,
    /// hook execution, or insertion fails.
    async fn save_from_mut(&mut self, client: &mongodb::Client) -> Result<ObjectId, OxiModError>;

    /// Deletes all documents in this model's collection using an explicit client.
    ///
    /// This method removes every document in the collection associated with the model.
    /// It is primarily useful for tests, examples, and resetting known datasets.
    ///
    /// This is the explicit-client counterpart to [`Model::clear`].
    ///
    /// # Parameters
    ///
    /// - `client`: The MongoDB client to use for the delete operation.
    ///
    /// # Returns
    ///
    /// A [`DeleteResult`] describing how many documents were removed.
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if collection access or deletion fails.
    ///
    /// # Warning
    ///
    /// This removes **all documents** from the model's collection.
    async fn clear_from(client: &mongodb::Client) -> Result<DeleteResult, OxiModError>;

    /// Finds a document by its `_id` using an explicit client.
    ///
    /// This is a convenience method for a very common query pattern:
    /// resolving a single typed document by its MongoDB `_id`.
    ///
    /// Internally, this is equivalent in behavior to:
    ///
    /// ```ignore
    /// let collection = User::get_collection_from(client)?;
    /// let found = collection.find_one(doc! { "_id": id }).await?;
    /// ```
    ///
    /// # Parameters
    ///
    /// - `id`: The `_id` of the document to find.
    /// - `client`: The MongoDB client to use for the query.
    ///
    /// # Returns
    ///
    /// `Ok(Some(Self))` if a matching document is found, otherwise `Ok(None)`.
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if collection resolution or the query fails.
    async fn find_by_id_from(
        id: ObjectId,
        client: &mongodb::Client,
    ) -> Result<Option<Self>, OxiModError>;

    /// Deletes a document by its `_id` using an explicit client.
    ///
    /// This method removes at most one document whose `_id` matches `id`.
    ///
    /// Internally, this is equivalent in behavior to:
    ///
    /// ```ignore
    /// let collection = User::get_collection_from(client)?;
    /// let result = collection.delete_one(doc! { "_id": id }).await?;
    /// ```
    ///
    /// # Parameters
    ///
    /// - `id`: The `_id` of the document to delete.
    /// - `client`: The MongoDB client to use for the delete operation.
    ///
    /// # Returns
    ///
    /// A [`DeleteResult`] indicating whether a document was deleted.
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if collection resolution or deletion fails.
    async fn delete_by_id_from(
        id: ObjectId,
        client: &mongodb::Client,
    ) -> Result<DeleteResult, OxiModError>;

    /// Updates a document by its `_id` using an explicit client.
    ///
    /// This method updates at most one document whose `_id` matches `id`.
    ///
    /// The `update` document must follow MongoDB update syntax, such as:
    ///
    /// ```ignore
    /// doc! { "$set": { "active": false } }
    /// ```
    ///
    /// Internally, this is equivalent in behavior to:
    ///
    /// ```ignore
    /// let collection = User::get_collection_from(client)?;
    /// let result = collection.update_one(doc! { "_id": id }, update).await?;
    /// ```
    ///
    /// # Parameters
    ///
    /// - `id`: The `_id` of the document to update.
    /// - `update`: A MongoDB update document.
    /// - `client`: The MongoDB client to use for the update operation.
    ///
    /// # Returns
    ///
    /// An [`UpdateResult`] indicating how many documents matched and were modified.
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if collection resolution or update execution fails.
    async fn update_by_id_from(
        id: ObjectId,
        update: Document,
        client: &mongodb::Client,
    ) -> Result<UpdateResult, OxiModError>;

    /// Checks whether any document matching `filter` exists using an explicit client.
    ///
    /// This method is implemented using `find_one(filter).await?.is_some()`,
    /// which is typically more efficient for existence checks than counting
    /// all matching documents.
    ///
    /// # Parameters
    ///
    /// - `filter`: A MongoDB filter document.
    /// - `client`: The MongoDB client to use for the query.
    ///
    /// # Returns
    ///
    /// `true` if at least one matching document exists, otherwise `false`.
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if collection resolution or the query fails.
    async fn exists_from(filter: Document, client: &mongodb::Client) -> Result<bool, OxiModError> {
        let collection = Self::get_collection_from(client)?;
        let found = collection
            .find_one(filter)
            .await
            .map_err(|e| OxiModError::database("Failed to check document existence", e))?;
        Ok(found.is_some())
    }

    /// Counts documents matching `filter` using an explicit client.
    ///
    /// This is a convenience wrapper around MongoDB's `count_documents`.
    ///
    /// # Parameters
    ///
    /// - `filter`: A MongoDB filter document.
    /// - `client`: The MongoDB client to use for the count operation.
    ///
    /// # Returns
    ///
    /// The number of matching documents.
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if collection resolution or the count operation fails.
    async fn count_from(filter: Document, client: &mongodb::Client) -> Result<u64, OxiModError> {
        let collection = Self::get_collection_from(client)?;
        collection
            .count_documents(filter)
            .await
            .map_err(|e| OxiModError::database("Failed to count matching documents", e))
    }

    /// Returns the typed MongoDB collection for this model using the global [`OxiClient`].
    ///
    /// This method retrieves the globally initialized client via [`OxiClient::global`]
    /// and delegates to [`Model::get_collection_from`].
    ///
    /// # Returns
    ///
    /// A typed [`mongodb::Collection`] whose document type is `Self`.
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if:
    ///
    /// - the global client has not been initialized,
    /// - or the collection cannot be resolved.
    fn get_collection() -> Result<Collection<Self>, OxiModError> {
        let client_arc = OxiClient::global()?;
        let client: &Client = client_arc.as_ref();
        Self::get_collection_from(client)
    }

    /// Returns the raw BSON document collection for this model using the global [`OxiClient`].
    ///
    /// This is a convenience wrapper around [`Model::get_collection`] that converts
    /// the typed collection into `Collection<Document>`.
    ///
    /// # Returns
    ///
    /// A raw [`mongodb::Collection`] of [`mongodb::bson::Document`].
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if:
    ///
    /// - the global client has not been initialized,
    /// - or the collection cannot be resolved.
    fn get_document_collection() -> Result<Collection<Document>, OxiModError> {
        Ok(Self::get_collection()?.clone_with_type::<Document>())
    }

    /// Persists this model instance using the global [`OxiClient`].
    ///
    /// This method retrieves the global client via [`OxiClient::global`] and
    /// delegates to [`Model::save_from`].
    ///
    /// # Returns
    ///
    /// The inserted document's [`ObjectId`].
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if:
    ///
    /// - the global client has not been initialized,
    /// - validation fails,
    /// - serialization fails,
    /// - collection resolution fails,
    /// - or insertion fails.
    async fn save(&self) -> Result<ObjectId, OxiModError> {
        let client_arc = OxiClient::global()?;
        let client: &Client = client_arc.as_ref();
        self.save_from(client).await
    }

    /// Persists this model instance using the global [`OxiClient`] with mutable access.
    ///
    /// This method retrieves the global client via [`OxiClient::global`] and
    /// delegates to [`Model::save_from_mut`].
    ///
    /// Unlike [`Model::save`], this method allows mutable access to the model
    /// before persistence. This enables lifecycle hooks such as
    /// [`crate::feature::hooks::Hooks::pre_save_mut`] and [`crate::feature::hooks::Hooks::post_save_mut`] to modify or observe
    /// the model during the save workflow.
    ///
    /// This is useful when the save operation needs to perform normalization
    /// or other in-place changes before validation and insertion.
    ///
    /// # Returns
    ///
    /// The inserted document's [`ObjectId`].
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if:
    ///
    /// - the global client has not been initialized,
    /// - hook execution fails,
    /// - validation fails,
    /// - serialization fails,
    /// - collection resolution fails,
    /// - or insertion fails.
    async fn save_mut(&mut self) -> Result<ObjectId, OxiModError> {
        let client_arc = OxiClient::global()?;
        let client: &Client = client_arc.as_ref();
        self.save_from_mut(client).await
    }

    /// Deletes all documents in this model's collection using the global [`OxiClient`].
    ///
    /// This method retrieves the global client via [`OxiClient::global`] and
    /// delegates to [`Model::clear_from`].
    ///
    /// # Returns
    ///
    /// A [`DeleteResult`] describing how many documents were removed.
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if:
    ///
    /// - the global client has not been initialized,
    /// - collection resolution fails,
    /// - or deletion fails.
    ///
    /// # Warning
    ///
    /// This removes **all documents** from the model's collection.
    async fn clear() -> Result<DeleteResult, OxiModError> {
        let client_arc = OxiClient::global()?;
        let client: &Client = client_arc.as_ref();
        Self::clear_from(client).await
    }

    /// Finds a document by its `_id` using the global [`OxiClient`].
    ///
    /// This method retrieves the global client via [`OxiClient::global`] and
    /// delegates to [`Model::find_by_id_from`].
    ///
    /// # Parameters
    ///
    /// - `id`: The `_id` of the document to find.
    ///
    /// # Returns
    ///
    /// `Ok(Some(Self))` if a matching document is found, otherwise `Ok(None)`.
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if:
    ///
    /// - the global client has not been initialized,
    /// - collection resolution fails,
    /// - or the query fails.
    async fn find_by_id(id: ObjectId) -> Result<Option<Self>, OxiModError> {
        let client_arc = OxiClient::global()?;
        let client: &Client = client_arc.as_ref();
        Self::find_by_id_from(id, client).await
    }

    /// Deletes a document by its `_id` using the global [`OxiClient`].
    ///
    /// This method retrieves the global client via [`OxiClient::global`] and
    /// delegates to [`Model::delete_by_id_from`].
    ///
    /// # Parameters
    ///
    /// - `id`: The `_id` of the document to delete.
    ///
    /// # Returns
    ///
    /// A [`DeleteResult`] indicating whether a document was deleted.
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if:
    ///
    /// - the global client has not been initialized,
    /// - collection resolution fails,
    /// - or deletion fails.
    async fn delete_by_id(id: ObjectId) -> Result<DeleteResult, OxiModError> {
        let client_arc = OxiClient::global()?;
        let client: &Client = client_arc.as_ref();
        Self::delete_by_id_from(id, client).await
    }

    /// Updates a document by its `_id` using the global [`OxiClient`].
    ///
    /// This method retrieves the global client via [`OxiClient::global`] and
    /// delegates to [`Model::update_by_id_from`].
    ///
    /// # Parameters
    ///
    /// - `id`: The `_id` of the document to update.
    /// - `update`: A MongoDB update document.
    ///
    /// # Returns
    ///
    /// An [`UpdateResult`] indicating how many documents matched and were modified.
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if:
    ///
    /// - the global client has not been initialized,
    /// - collection resolution fails,
    /// - or update execution fails.
    async fn update_by_id(id: ObjectId, update: Document) -> Result<UpdateResult, OxiModError> {
        let client_arc = OxiClient::global()?;
        let client: &Client = client_arc.as_ref();
        Self::update_by_id_from(id, update, client).await
    }

    /// Checks whether any document matching `filter` exists using the global [`OxiClient`].
    ///
    /// This method retrieves the global client via [`OxiClient::global`] and
    /// delegates to [`Model::exists_from`].
    ///
    /// # Parameters
    ///
    /// - `filter`: A MongoDB filter document.
    ///
    /// # Returns
    ///
    /// `true` if at least one matching document exists, otherwise `false`.
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if:
    ///
    /// - the global client has not been initialized,
    /// - collection resolution fails,
    /// - or the query fails.
    async fn exists(filter: Document) -> Result<bool, OxiModError> {
        let client_arc = OxiClient::global()?;
        let client: &Client = client_arc.as_ref();
        Self::exists_from(filter, client).await
    }

    /// Counts documents matching `filter` using the global [`OxiClient`].
    ///
    /// This method retrieves the global client via [`OxiClient::global`] and
    /// delegates to [`Model::count_from`].
    ///
    /// # Parameters
    ///
    /// - `filter`: A MongoDB filter document.
    ///
    /// # Returns
    ///
    /// The number of matching documents.
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if:
    ///
    /// - the global client has not been initialized,
    /// - collection resolution fails,
    /// - or the count operation fails.
    async fn count(filter: Document) -> Result<u64, OxiModError> {
        let client_arc = OxiClient::global()?;
        let client: &Client = client_arc.as_ref();
        Self::count_from(filter, client).await
    }

    /// Performs validation on a model instance using inline checks and user-defined validators.
    ///
    /// # Returns
    ///
    /// The unit value () if all validations pass.
    ///
    /// # Errors
    ///
    /// Returns [`OxiModError`] if:
    ///
    /// - inlines checks fail
    /// - user-defined validators fail
    fn validate(&self) -> Result<(), OxiModError>;
}