Skip to main content

navree_orm/
lifecycle.rs

1//! [`ModelLifecycle`]: the lifecycle's model-level methods, for every
2//! model.
3
4use std::borrow::Cow;
5use std::future::Future;
6use std::sync::Arc;
7
8use crate::column::Assignment;
9use crate::error::Result;
10use crate::events::without_events;
11use crate::exec::Executor;
12use crate::model::Model;
13use crate::record::Record;
14use crate::scope::GlobalScope;
15use crate::soft_deletes::SoftDeleting;
16
17/// The lifecycle's methods on models themselves (`Deal::create_quietly`,
18/// `Note::force_destroy`, ...), implemented for every [`Model`]. Bring it
19/// into scope with `use navree_orm::prelude::*;`.
20pub trait ModelLifecycle: Model {
21    /// Inserts `model` and returns its record without model events
22    /// ([`Model::create`] inside [`without_events`]).
23    ///
24    /// ```no_run
25    /// # use navree_orm::__doc_models::*;
26    /// # async fn demo(uow: Uow) -> Result<()> {
27    /// // An import: nobody is notified of each row.
28    /// let tag = Tag::create_quietly(&uow, Tag { name: "vip".into(), ..Default::default() }).await?;
29    /// # Ok(()) }
30    /// ```
31    fn create_quietly<E: Executor + ?Sized>(
32        exec: &E,
33        model: Self,
34    ) -> impl Future<Output = Result<Record<Self>>> + Send {
35        without_events(Self::create(exec, model))
36    }
37
38    /// Removes the records with these keys for good, soft-deleted ones
39    /// included, loading each so its force-delete events fire; returns how
40    /// many were removed. On a model without soft deletes it is
41    /// [`destroy`](Model::destroy).
42    ///
43    /// ```no_run
44    /// # use navree_orm::__doc_models::*;
45    /// # async fn demo(uow: Uow) -> Result<()> {
46    /// let removed = Note::force_destroy(&uow, [3_i64, 4, 5]).await?;
47    /// # Ok(()) }
48    /// ```
49    fn force_destroy<E: Executor + ?Sized>(
50        exec: &E,
51        keys: impl IntoIterator<Item = impl Into<Self::Key>>,
52    ) -> impl Future<Output = Result<u64>> + Send {
53        let keys: Vec<Self::Key> = keys.into_iter().map(Into::into).collect();
54        async move {
55            if keys.is_empty() {
56                return Ok(0);
57            }
58            let records = Self::query()
59                .with_trashed()
60                .where_key_in(keys)
61                .get(exec)
62                .await?;
63            let mut removed = 0;
64            for mut record in records {
65                if record.force_delete(exec).await? {
66                    removed += 1;
67                }
68            }
69            Ok(removed)
70        }
71    }
72
73    /// The record matching `attributes`, soft-deleted or not, restored when
74    /// it was trashed; or a new one with them (and whatever `fill` sets)
75    /// inserted. See [`Builder::restore_or_create`](crate::Builder::restore_or_create).
76    fn restore_or_create<E: Executor + ?Sized>(
77        exec: &E,
78        attributes: impl IntoIterator<Item = Assignment>,
79        fill: impl FnOnce(&mut Self) + Send,
80    ) -> impl Future<Output = Result<Record<Self>>> + Send
81    where
82        Self: SoftDeleting + Default,
83    {
84        let attributes: Vec<Assignment> = attributes.into_iter().collect();
85        Self::query().restore_or_create(exec, attributes, fill)
86    }
87
88    /// Inserts a record with `attributes` (and whatever `fill` sets), or on
89    /// a unique violation returns the record holding them, restored when it
90    /// was trashed. See
91    /// [`Builder::create_or_restore`](crate::Builder::create_or_restore).
92    fn create_or_restore<E: Executor + ?Sized>(
93        exec: &E,
94        attributes: impl IntoIterator<Item = Assignment>,
95        fill: impl FnOnce(&mut Self) + Send,
96    ) -> impl Future<Output = Result<Record<Self>>> + Send
97    where
98        Self: SoftDeleting + Default,
99    {
100        let attributes: Vec<Assignment> = attributes.into_iter().collect();
101        Self::query().create_or_restore(exec, attributes, fill)
102    }
103
104    /// Whether the model has a global scope named `name` (declared,
105    /// registered at boot, or `SoftDeletes`).
106    ///
107    /// ```
108    /// # use navree_orm::__doc_models::*;
109    /// assert!(Note::has_global_scope("SoftDeletes"));
110    /// assert!(!Deal::has_global_scope("SoftDeletes"));
111    /// ```
112    fn has_global_scope(name: &str) -> bool {
113        crate::global_scopes::find::<Self>(name).is_some()
114    }
115
116    /// The global scope named `name`, if the model has one.
117    fn global_scope(name: &str) -> Option<Arc<dyn GlobalScope<Self>>> {
118        crate::global_scopes::find::<Self>(name)
119    }
120
121    /// The names of every global scope the model's queries apply, in
122    /// order.
123    fn global_scope_names() -> Vec<Cow<'static, str>> {
124        crate::global_scopes::scopes_of::<Self>()
125            .iter()
126            .map(|scope| scope.name())
127            .collect()
128    }
129}
130
131impl<M: Model> ModelLifecycle for M {}