1use 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
18pub struct Collection<M: Model> {
34 records: Vec<Record<M>>,
35}
36
37impl<M: Model> Collection<M> {
38 pub fn new() -> Self {
40 Collection {
41 records: Vec::new(),
42 }
43 }
44
45 pub fn into_vec(self) -> Vec<Record<M>> {
47 self.records
48 }
49
50 pub fn into_models(self) -> Vec<M> {
52 self.records.into_iter().map(Record::into_inner).collect()
53 }
54
55 pub fn push(&mut self, record: Record<M>) {
57 self.records.push(record);
58 }
59
60 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 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 pub fn contains(&self, key: impl Into<M::Key>) -> bool {
74 self.find(key).is_some()
75 }
76
77 pub fn model_keys(&self) -> Vec<M::Key> {
79 self.records.iter().map(Record::key).collect()
80 }
81
82 pub fn map<U>(&self, f: impl FnMut(&Record<M>) -> U) -> Vec<U> {
84 self.records.iter().map(f).collect()
85 }
86
87 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 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 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 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 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 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 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 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 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 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 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 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 pub fn reverse(mut self) -> Self {
220 self.records.reverse();
221 self
222 }
223
224 pub fn to_query(&self) -> Builder<M> {
234 Builder::new().where_key_in(self.model_keys())
235 }
236
237 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 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
363impl<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}