use std::future::Future;
use super::Association;
use super::assoc::Preload;
use super::{Expr, Query, ToValue, Value};
use crate::error::Result;
use crate::model::Model;
pub trait LoadedRecords<M: Model>: Sized {
fn preload<P: Into<Preload<M>>>(
self,
association: impl FnOnce(&M::Columns) -> P,
) -> impl Future<Output = Result<Vec<M>>> + Send;
fn with_count<C>(
self,
association: impl FnOnce(&M::Columns) -> Association<M, C>,
) -> impl Future<Output = Result<Vec<M>>> + Send
where
M: 'static;
}
impl<M: Model + Send + 'static> LoadedRecords<M> for Vec<M> {
fn preload<P: Into<Preload<M>>>(
self,
association: impl FnOnce(&M::Columns) -> P,
) -> impl Future<Output = Result<Vec<M>>> + Send {
let preload: Preload<M> = association(&M::columns()).into();
let mut records = self;
async move {
let conn = super::current()?;
preload.run(&mut records, conn).await?;
Ok(records)
}
}
fn with_count<C>(
self,
association: impl FnOnce(&M::Columns) -> Association<M, C>,
) -> impl Future<Output = Result<Vec<M>>> + Send
where
M: 'static,
{
let preload = association(&M::columns()).counting();
let mut records = self;
async move {
let preload = preload.ok_or_else(|| {
crate::Error::internal(
"with_count counts a `has_many` association (not one `through` a join table)",
)
})?;
let conn = super::current()?;
preload.run(&mut records, conn).await?;
Ok(records)
}
}
}
pub trait Records<M: Model> {
fn ids(&self) -> Vec<i64>;
fn find_id(&self, id: impl ToValue) -> Option<&M>;
fn to_query(&self) -> Query<M>;
}
impl<M: Model> Records<M> for [M] {
fn ids(&self) -> Vec<i64> {
self.iter()
.filter_map(|record| match record.id_value() {
Value::Int(id) => Some(id),
_ => None,
})
.collect()
}
fn find_id(&self, id: impl ToValue) -> Option<&M> {
let id = match id.to_value() {
Value::Text(text) if M::INTEGER_KEY => Value::Int(text.trim().parse().ok()?),
value => value,
};
self.iter().find(|record| record.id_value() == id)
}
fn to_query(&self) -> Query<M> {
let values: Vec<Value> = self.iter().map(|record| record.id_value()).collect();
Query::new().filter(|_| Expr::In {
column: M::PRIMARY_KEY,
values,
})
}
}