Skip to main content

navree_orm/attributes/
model_ref.rs

1//! Records in queued jobs: [`ModelRef`] and [`ModelRefs`] carry a record's
2//! identity (its model, key, loaded relation names and connection) instead
3//! of its values, and load it again when the job runs, so the job sees the
4//! record as it is then.
5//!
6//! ```no_run
7//! # use navree_orm::__doc_models::*;
8//! use navree_orm::attributes::ModelRef;
9//! use serde::{Deserialize, Serialize};
10//!
11//! /// Emails a deal's owner (serialized into the queue).
12//! #[derive(Serialize, Deserialize)]
13//! struct NotifyOwner {
14//!     deal: ModelRef<Deal>,
15//! }
16//!
17//! # async fn demo(uow: Uow, deal: Record<Deal>) -> Result<()> {
18//! let job = NotifyOwner { deal: deal.to_ref()? };
19//! // ... later, when the job runs:
20//! let deal = job.deal.restore(&uow).await?; // 404-shaped ModelNotFound if it is gone
21//! # Ok(()) }
22//! ```
23
24use std::fmt;
25use std::marker::PhantomData;
26
27use serde::{Deserialize, Serialize};
28
29use crate::collection::Collection;
30use crate::error::{OrmError, Result};
31use crate::exec::{Access, Executor};
32use crate::model::{Model, PrimaryKey};
33use crate::query::Builder;
34use crate::record::Record;
35use crate::value::{Field, to_json};
36
37/// One record's identity, for a queued job. Serializes as `{"model":
38/// "Deal", "key": ..., "relations": [..], "connection": ..}`.
39#[derive(Serialize, Deserialize)]
40#[serde(bound = "")]
41pub struct ModelRef<M> {
42    model: String,
43    key: serde_json::Value,
44    #[serde(default, skip_serializing_if = "Vec::is_empty")]
45    relations: Vec<String>,
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    connection: Option<String>,
48    #[serde(skip)]
49    _model: PhantomData<fn() -> M>,
50}
51
52/// Several records' identities, for a queued job; restored in the same
53/// order.
54#[derive(Serialize, Deserialize)]
55#[serde(bound = "")]
56pub struct ModelRefs<M> {
57    model: String,
58    keys: Vec<serde_json::Value>,
59    #[serde(default, skip_serializing_if = "Vec::is_empty")]
60    relations: Vec<String>,
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    connection: Option<String>,
63    #[serde(skip)]
64    _model: PhantomData<fn() -> M>,
65}
66
67fn check_model<M: Model>(model: &str) -> Result<()> {
68    if model == M::meta().name() {
69        Ok(())
70    } else {
71        Err(OrmError::InvalidQuery(format!(
72            "this reference names model {model}, not {}",
73            M::meta().name()
74        )))
75    }
76}
77
78fn key_from<M: Model>(json: &serde_json::Value) -> Result<M::Key> {
79    M::Key::from_json(json.clone()).map_err(|error| OrmError::Decode {
80        model: M::meta().name().into(),
81        column: M::meta().key_column().to_owned(),
82        expected: M::Key::type_name(),
83        message: format!("the reference's key {json}: {error}"),
84    })
85}
86
87impl<M: Model> ModelRef<M> {
88    /// The identity of `record`, which must be stored.
89    pub fn of(record: &Record<M>) -> Result<Self> {
90        if !record.exists() {
91            return Err(Record::<M>::not_persisted("refer to"));
92        }
93        Ok(ModelRef {
94            model: M::meta().name().to_owned(),
95            key: to_json(&record.key().to_value()),
96            relations: record.relations().names().map(str::to_owned).collect(),
97            connection: M::meta().connection_name().map(str::to_owned),
98            _model: PhantomData,
99        })
100    }
101
102    /// The model's name the reference was made for.
103    pub fn model_name(&self) -> &str {
104        &self.model
105    }
106
107    /// The record's key.
108    pub fn key(&self) -> Result<M::Key> {
109        check_model::<M>(&self.model)?;
110        key_from::<M>(&self.key)
111    }
112
113    /// The names of the relations the record had loaded, to load again
114    /// with the restored record.
115    pub fn relations(&self) -> &[String] {
116        &self.relations
117    }
118
119    /// The model's connection when the reference was made.
120    pub fn connection(&self) -> Option<&str> {
121        self.connection.as_deref()
122    }
123
124    /// The record as it is now, read through the writer and without global
125    /// scopes (a soft-deleted record restores too);
126    /// [`OrmError::ModelNotFound`] when it is gone, which fails the job
127    /// with a clear message.
128    pub async fn restore<E: Executor + ?Sized>(&self, exec: &E) -> Result<Record<M>> {
129        let key = self.key()?;
130        self.restore_or_skip(exec)
131            .await?
132            .ok_or_else(|| OrmError::not_found(M::meta().name(), vec![key.to_key_string()]))
133    }
134
135    /// Like [`restore`](ModelRef::restore), with `None` when the record is
136    /// gone: for jobs that skip records deleted since they were queued.
137    pub async fn restore_or_skip<E: Executor + ?Sized>(
138        &self,
139        exec: &E,
140    ) -> Result<Option<Record<M>>> {
141        let key = self.key()?;
142        let target = exec.target(Access::Write).await?;
143        Ok(Builder::<M>::new()
144            .without_global_scopes()
145            .where_key(key)
146            .limit(1)
147            .fetch(&target)
148            .await?
149            .into_vec()
150            .into_iter()
151            .next())
152    }
153}
154
155impl<M: Model> ModelRefs<M> {
156    /// The identities of `records`, which must all be stored.
157    pub fn of(records: &Collection<M>) -> Result<Self> {
158        let mut keys = Vec::with_capacity(records.len());
159        let mut relations: Vec<String> = Vec::new();
160        for record in records.iter() {
161            if !record.exists() {
162                return Err(Record::<M>::not_persisted("refer to"));
163            }
164            keys.push(to_json(&record.key().to_value()));
165            for name in record.relations().names() {
166                if !relations.iter().any(|known| known == name) {
167                    relations.push(name.to_owned());
168                }
169            }
170        }
171        Ok(ModelRefs {
172            model: M::meta().name().to_owned(),
173            keys,
174            relations,
175            connection: M::meta().connection_name().map(str::to_owned),
176            _model: PhantomData,
177        })
178    }
179
180    /// The model's name the references were made for.
181    pub fn model_name(&self) -> &str {
182        &self.model
183    }
184
185    /// The records' keys, in order.
186    pub fn keys(&self) -> Result<Vec<M::Key>> {
187        check_model::<M>(&self.model)?;
188        self.keys.iter().map(key_from::<M>).collect()
189    }
190
191    /// How many records.
192    pub fn len(&self) -> usize {
193        self.keys.len()
194    }
195
196    /// Whether there are none.
197    pub fn is_empty(&self) -> bool {
198        self.keys.is_empty()
199    }
200
201    /// The names of the relations the records had loaded.
202    pub fn relations(&self) -> &[String] {
203        &self.relations
204    }
205
206    /// The models' connection when the references were made.
207    pub fn connection(&self) -> Option<&str> {
208        self.connection.as_deref()
209    }
210
211    /// The records as they are now, in the references' order, read through
212    /// the writer and without global scopes; records gone since are left
213    /// out.
214    pub async fn restore<E: Executor + ?Sized>(&self, exec: &E) -> Result<Collection<M>> {
215        let keys = self.keys()?;
216        if keys.is_empty() {
217            return Ok(Collection::new());
218        }
219        let target = exec.target(Access::Write).await?;
220        let mut found = Builder::<M>::new()
221            .without_global_scopes()
222            .where_key_in(keys.clone())
223            .fetch(&target)
224            .await?
225            .into_vec();
226        let mut ordered = Vec::with_capacity(found.len());
227        for key in keys {
228            if let Some(index) = found.iter().position(|record| record.key() == key) {
229                ordered.push(found.swap_remove(index));
230            }
231        }
232        Ok(ordered.into())
233    }
234}
235
236impl<M: Model> Record<M> {
237    /// The record's identity, for a queued job ([`ModelRef`]).
238    pub fn to_ref(&self) -> Result<ModelRef<M>> {
239        ModelRef::of(self)
240    }
241}
242
243impl<M: Model> Collection<M> {
244    /// The records' identities, for a queued job ([`ModelRefs`]).
245    pub fn to_refs(&self) -> Result<ModelRefs<M>> {
246        ModelRefs::of(self)
247    }
248}
249
250impl<M> Clone for ModelRef<M> {
251    fn clone(&self) -> Self {
252        ModelRef {
253            model: self.model.clone(),
254            key: self.key.clone(),
255            relations: self.relations.clone(),
256            connection: self.connection.clone(),
257            _model: PhantomData,
258        }
259    }
260}
261
262impl<M> Clone for ModelRefs<M> {
263    fn clone(&self) -> Self {
264        ModelRefs {
265            model: self.model.clone(),
266            keys: self.keys.clone(),
267            relations: self.relations.clone(),
268            connection: self.connection.clone(),
269            _model: PhantomData,
270        }
271    }
272}
273
274impl<M> PartialEq for ModelRef<M> {
275    fn eq(&self, other: &Self) -> bool {
276        self.model == other.model
277            && self.key == other.key
278            && self.relations == other.relations
279            && self.connection == other.connection
280    }
281}
282
283impl<M> PartialEq for ModelRefs<M> {
284    fn eq(&self, other: &Self) -> bool {
285        self.model == other.model
286            && self.keys == other.keys
287            && self.relations == other.relations
288            && self.connection == other.connection
289    }
290}
291
292impl<M> fmt::Debug for ModelRef<M> {
293    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
294        f.debug_struct("ModelRef")
295            .field("model", &self.model)
296            .field("key", &self.key)
297            .field("relations", &self.relations)
298            .field("connection", &self.connection)
299            .finish()
300    }
301}
302
303impl<M> fmt::Debug for ModelRefs<M> {
304    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305        f.debug_struct("ModelRefs")
306            .field("model", &self.model)
307            .field("keys", &self.keys)
308            .field("relations", &self.relations)
309            .field("connection", &self.connection)
310            .finish()
311    }
312}