Skip to main content

navree_orm/
collection.rs

1//! [`Collection`]: the records a query returns.
2
3use std::fmt;
4use std::hash::Hash;
5use std::ops::{Deref, DerefMut};
6
7use indexmap::IndexMap;
8use serde::{Serialize, Serializer};
9
10use crate::column::Column;
11use crate::error::{OrmError, Result};
12use crate::exec::{Access, Executor};
13use crate::model::Model;
14use crate::query::Builder;
15use crate::record::Record;
16use crate::row::Row;
17
18/// The records of a query, in order.
19///
20/// A collection dereferences to a slice of [`Record`]s (`len`, indexing,
21/// `iter`, `first`, `last`, ...), iterates by value or by reference, and
22/// serializes as an array. Its own methods work with keys and columns:
23///
24/// ```no_run
25/// # use navree_orm::__doc_models::*;
26/// # async fn demo(db: Db) -> Result<()> {
27/// let deals = Deal::query().where_(Deal::STAGE.eq(Stage::Open)).get(&db).await?;
28/// let by_owner = deals.clone().group_by(|deal| deal.owner_id);
29/// let titles = deals.pluck(Deal::TITLE)?;
30/// let big = deals.filter(|deal| deal.amount_cents > 100_000);
31/// # Ok(()) }
32/// ```
33pub struct Collection<M: Model> {
34    records: Vec<Record<M>>,
35}
36
37impl<M: Model> Collection<M> {
38    /// An empty collection.
39    pub fn new() -> Self {
40        Collection {
41            records: Vec::new(),
42        }
43    }
44
45    /// The records, by value.
46    pub fn into_vec(self) -> Vec<Record<M>> {
47        self.records
48    }
49
50    /// The models, without the records' bookkeeping.
51    pub fn into_models(self) -> Vec<M> {
52        self.records.into_iter().map(Record::into_inner).collect()
53    }
54
55    /// Appends a record.
56    pub fn push(&mut self, record: Record<M>) {
57        self.records.push(record);
58    }
59
60    /// The record with key `key`.
61    pub fn find(&self, key: impl Into<M::Key>) -> Option<&Record<M>> {
62        let key = key.into();
63        self.records.iter().find(|record| record.key() == key)
64    }
65
66    /// The record with key `key`, for changes.
67    pub fn find_mut(&mut self, key: impl Into<M::Key>) -> Option<&mut Record<M>> {
68        let key = key.into();
69        self.records.iter_mut().find(|record| record.key() == key)
70    }
71
72    /// Whether a record has key `key`.
73    pub fn contains(&self, key: impl Into<M::Key>) -> bool {
74        self.find(key).is_some()
75    }
76
77    /// The records' keys, in order.
78    pub fn model_keys(&self) -> Vec<M::Key> {
79        self.records.iter().map(Record::key).collect()
80    }
81
82    /// `f` of every record, in order.
83    pub fn map<U>(&self, f: impl FnMut(&Record<M>) -> U) -> Vec<U> {
84        self.records.iter().map(f).collect()
85    }
86
87    /// The records for which `keep` holds.
88    pub fn filter(self, mut keep: impl FnMut(&Record<M>) -> bool) -> Self {
89        Collection {
90            records: self
91                .records
92                .into_iter()
93                .filter(|record| keep(record))
94                .collect(),
95        }
96    }
97
98    /// The records for which `test` holds, and the others.
99    pub fn partition(self, test: impl FnMut(&Record<M>) -> bool) -> (Self, Self) {
100        let (yes, no): (Vec<_>, Vec<_>) = self.records.into_iter().partition(test);
101        (Collection { records: yes }, Collection { records: no })
102    }
103
104    /// The values of `column`, in order (decoded as the field is, casts
105    /// included).
106    ///
107    /// ```
108    /// # use navree_orm::__doc_models::*;
109    /// # fn main() -> Result<()> {
110    /// let deals = Collection::from(vec![
111    ///     Record::new(Deal { title: "Renewal".into(), ..Deal::default() }),
112    ///     Record::new(Deal { title: "Upsell".into(), ..Deal::default() }),
113    /// ]);
114    /// let titles: Vec<String> = deals.pluck(Deal::TITLE)?;
115    /// assert_eq!(titles, ["Renewal", "Upsell"]);
116    /// # Ok(()) }
117    /// ```
118    pub fn pluck<T>(&self, column: Column<M, T>) -> Result<Vec<T>> {
119        let name = column.column_ref().name.into_owned();
120        self.records
121            .iter()
122            .map(|record| {
123                let value = record
124                    .model
125                    .value(&name)?
126                    .ok_or_else(|| crate::model::derive_support::unknown_column::<M>(&name))?;
127                let row = Row::from_values(vec![(name.clone(), value)]);
128                column.decode(&row).map_err(|error| {
129                    crate::row::decode_error(
130                        M::meta().name(),
131                        &name,
132                        "the column's type".into(),
133                        &error,
134                    )
135                })
136            })
137            .collect()
138    }
139
140    /// The records by `key` (a later record with the same key replaces an
141    /// earlier one, keeping its position).
142    pub fn key_by<K: Hash + Eq>(
143        self,
144        mut key: impl FnMut(&Record<M>) -> K,
145    ) -> IndexMap<K, Record<M>> {
146        let mut map = IndexMap::with_capacity(self.records.len());
147        for record in self.records {
148            map.insert(key(&record), record);
149        }
150        map
151    }
152
153    /// The records grouped by `key`, groups in order of first appearance.
154    pub fn group_by<K: Hash + Eq>(
155        self,
156        mut key: impl FnMut(&Record<M>) -> K,
157    ) -> IndexMap<K, Collection<M>> {
158        let mut groups: IndexMap<K, Collection<M>> = IndexMap::new();
159        for record in self.records {
160            groups.entry(key(&record)).or_default().push(record);
161        }
162        groups
163    }
164
165    /// The records whose key is not in `other`.
166    pub fn diff(self, other: &Collection<M>) -> Self {
167        let keys = other.model_keys();
168        self.filter(|record| !keys.contains(&record.key()))
169    }
170
171    /// The records whose key is also in `other`.
172    pub fn intersect(self, other: &Collection<M>) -> Self {
173        let keys = other.model_keys();
174        self.filter(|record| keys.contains(&record.key()))
175    }
176
177    /// The first record of each key.
178    pub fn unique(self) -> Self {
179        let mut seen: Vec<M::Key> = Vec::with_capacity(self.records.len());
180        self.filter(|record| {
181            let key = record.key();
182            if seen.contains(&key) {
183                false
184            } else {
185                seen.push(key);
186                true
187            }
188        })
189    }
190
191    /// The records with these keys.
192    pub fn only(self, keys: impl IntoIterator<Item = impl Into<M::Key>>) -> Self {
193        let keys: Vec<M::Key> = keys.into_iter().map(Into::into).collect();
194        self.filter(|record| keys.contains(&record.key()))
195    }
196
197    /// The records without these keys.
198    pub fn except(self, keys: impl IntoIterator<Item = impl Into<M::Key>>) -> Self {
199        let keys: Vec<M::Key> = keys.into_iter().map(Into::into).collect();
200        self.filter(|record| !keys.contains(&record.key()))
201    }
202
203    /// The records sorted by `compare` (stable).
204    pub fn sort_by(
205        mut self,
206        compare: impl FnMut(&Record<M>, &Record<M>) -> std::cmp::Ordering,
207    ) -> Self {
208        self.records.sort_by(compare);
209        self
210    }
211
212    /// The records sorted by `key` (stable).
213    pub fn sort_by_key<K: Ord>(mut self, key: impl FnMut(&Record<M>) -> K) -> Self {
214        self.records.sort_by_key(key);
215        self
216    }
217
218    /// The records in reverse order.
219    pub fn reverse(mut self) -> Self {
220        self.records.reverse();
221        self
222    }
223
224    /// A query of exactly these records (by key), e.g. for a mass update.
225    ///
226    /// ```no_run
227    /// # use navree_orm::__doc_models::*;
228    /// # async fn demo(db: Db, uow: Uow) -> Result<()> {
229    /// let stale = Deal::query().where_(Deal::CREATED_AT.lt(Utc::now() - Duration::days(90))).get(&db).await?;
230    /// stale.to_query().update(&uow, [Deal::STAGE.set(Stage::Lost)]).await?;
231    /// # Ok(()) }
232    /// ```
233    pub fn to_query(&self) -> Builder<M> {
234        Builder::new().where_key_in(self.model_keys())
235    }
236
237    /// The records as they are now in the database (ignoring global
238    /// scopes), in this collection's order; records that are gone or were
239    /// never stored are left out.
240    pub async fn fresh<E: Executor + ?Sized>(&self, exec: &E) -> Result<Collection<M>> {
241        let keys: Vec<M::Key> = self
242            .records
243            .iter()
244            .filter(|record| record.exists())
245            .map(Record::key)
246            .collect();
247        if keys.is_empty() {
248            return Ok(Collection::new());
249        }
250        let target = exec
251            .target_routed(Access::Read, crate::query::model_route::<M>())
252            .await?;
253        let mut fresh = Builder::<M>::new()
254            .without_global_scopes()
255            .where_key_in(keys.clone())
256            .fetch(&target)
257            .await?
258            .into_vec();
259        let mut ordered = Vec::with_capacity(fresh.len());
260        for key in keys {
261            if let Some(index) = fresh.iter().position(|record| record.key() == key) {
262                ordered.push(fresh.swap_remove(index));
263            }
264        }
265        Ok(Collection { records: ordered })
266    }
267
268    /// The single record, or an error naming how many there are.
269    pub fn sole(self) -> Result<Record<M>> {
270        let count = self.records.len();
271        let mut records = self.records.into_iter();
272        match (records.next(), count) {
273            (Some(record), 1) => Ok(record),
274            (None, _) => Err(OrmError::not_found(M::meta().name(), Vec::new())),
275            (Some(_), _) => Err(OrmError::MultipleRecordsFound {
276                model: M::meta().name().into(),
277            }),
278        }
279    }
280}
281
282impl<M: Model> Default for Collection<M> {
283    fn default() -> Self {
284        Collection::new()
285    }
286}
287
288impl<M: Model> Clone for Collection<M> {
289    fn clone(&self) -> Self {
290        Collection {
291            records: self.records.clone(),
292        }
293    }
294}
295
296impl<M: Model + fmt::Debug> fmt::Debug for Collection<M> {
297    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298        f.debug_list().entries(&self.records).finish()
299    }
300}
301
302impl<M: Model> Deref for Collection<M> {
303    type Target = [Record<M>];
304
305    fn deref(&self) -> &[Record<M>] {
306        &self.records
307    }
308}
309
310impl<M: Model> DerefMut for Collection<M> {
311    fn deref_mut(&mut self) -> &mut [Record<M>] {
312        &mut self.records
313    }
314}
315
316impl<M: Model> From<Vec<Record<M>>> for Collection<M> {
317    fn from(records: Vec<Record<M>>) -> Self {
318        Collection { records }
319    }
320}
321
322impl<M: Model> FromIterator<Record<M>> for Collection<M> {
323    fn from_iter<I: IntoIterator<Item = Record<M>>>(iter: I) -> Self {
324        Collection {
325            records: iter.into_iter().collect(),
326        }
327    }
328}
329
330impl<M: Model> Extend<Record<M>> for Collection<M> {
331    fn extend<I: IntoIterator<Item = Record<M>>>(&mut self, iter: I) {
332        self.records.extend(iter);
333    }
334}
335
336impl<M: Model> IntoIterator for Collection<M> {
337    type Item = Record<M>;
338    type IntoIter = std::vec::IntoIter<Record<M>>;
339
340    fn into_iter(self) -> Self::IntoIter {
341        self.records.into_iter()
342    }
343}
344
345impl<'a, M: Model> IntoIterator for &'a Collection<M> {
346    type Item = &'a Record<M>;
347    type IntoIter = std::slice::Iter<'a, Record<M>>;
348
349    fn into_iter(self) -> Self::IntoIter {
350        self.records.iter()
351    }
352}
353
354impl<'a, M: Model> IntoIterator for &'a mut Collection<M> {
355    type Item = &'a mut Record<M>;
356    type IntoIter = std::slice::IterMut<'a, Record<M>>;
357
358    fn into_iter(self) -> Self::IntoIter {
359        self.records.iter_mut()
360    }
361}
362
363/// An array of the records.
364impl<M: Model> Serialize for Collection<M> {
365    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
366        self.records.serialize(serializer)
367    }
368}