use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::sync::Arc;
use serde::{Serialize, Serializer};
use super::query::Expr;
use super::value::{ToValue, Value};
use super::{Connection, Query};
use crate::error::Result;
use crate::model::Model;
pub struct BelongsTo<M>(State<Option<M>>);
pub struct HasMany<M>(State<Vec<M>>);
pub struct HasOne<M>(State<Option<Box<M>>>);
enum State<T> {
NotLoaded,
Loaded(T),
Counted(usize),
}
fn not_loaded<M>() -> ! {
panic!(
"association to `{}` was not preloaded; add `.preload(..)` to the query that \
loaded this record",
std::any::type_name::<M>()
)
}
impl<M> BelongsTo<M> {
pub fn loaded(record: Option<M>) -> Self {
Self(State::Loaded(record))
}
pub fn is_loaded(&self) -> bool {
matches!(self.0, State::Loaded(_))
}
pub fn get(&self) -> Option<&M> {
match &self.0 {
State::Loaded(record) => record.as_ref(),
State::NotLoaded | State::Counted(_) => None,
}
}
}
impl<M> Deref for BelongsTo<M> {
type Target = M;
fn deref(&self) -> &M {
match &self.0 {
State::Loaded(Some(record)) => record,
State::Loaded(None) => panic!(
"association to `{}` is empty (the foreign key is NULL or dangling); \
use `.get()` for optional associations",
std::any::type_name::<M>()
),
State::NotLoaded | State::Counted(_) => not_loaded::<M>(),
}
}
}
#[doc(hidden)]
pub trait ForeignKey: Sized {
fn is_unset(&self) -> bool;
fn from_value(value: Value) -> Option<Self>;
}
impl ForeignKey for i64 {
fn is_unset(&self) -> bool {
*self == 0
}
fn from_value(value: Value) -> Option<Self> {
match value {
Value::Int(key) => Some(key),
_ => None,
}
}
}
impl ForeignKey for i32 {
fn is_unset(&self) -> bool {
*self == 0
}
fn from_value(value: Value) -> Option<Self> {
match value {
Value::Int(key) => key.try_into().ok(),
_ => None,
}
}
}
impl ForeignKey for String {
fn is_unset(&self) -> bool {
self.is_empty()
}
fn from_value(value: Value) -> Option<Self> {
match value {
Value::Text(key) => Some(key),
_ => None,
}
}
}
impl ForeignKey for uuid::Uuid {
fn is_unset(&self) -> bool {
self.is_nil()
}
fn from_value(value: Value) -> Option<Self> {
match value {
Value::Uuid(key) => Some(key),
_ => None,
}
}
}
impl<T: ForeignKey> ForeignKey for Option<T> {
fn is_unset(&self) -> bool {
self.is_none()
}
fn from_value(value: Value) -> Option<Self> {
T::from_value(value).map(Some)
}
}
#[doc(hidden)]
pub trait ParentKey {
fn parent_key(self) -> Value;
}
impl<M: crate::Model> ParentKey for M {
fn parent_key(self) -> Value {
self.id_value()
}
}
impl<T: ParentKey> ParentKey for Option<T> {
fn parent_key(self) -> Value {
self.map_or(Value::Null, ParentKey::parent_key)
}
}
macro_rules! key_parent {
($($ty:ty),*) => {$(
impl ParentKey for $ty {
fn parent_key(self) -> Value {
self.to_value()
}
}
)*};
}
key_parent!(i64, i32, String, &str, uuid::Uuid);
impl<M> HasOne<M> {
pub fn loaded(record: Option<M>) -> Self {
Self(State::Loaded(record.map(Box::new)))
}
pub fn is_loaded(&self) -> bool {
matches!(self.0, State::Loaded(_))
}
pub fn get(&self) -> Option<&M> {
match &self.0 {
State::Loaded(record) => record.as_deref(),
State::NotLoaded | State::Counted(_) => None,
}
}
}
impl<M> Deref for HasOne<M> {
type Target = M;
fn deref(&self) -> &M {
match &self.0 {
State::Loaded(Some(record)) => record,
State::Loaded(None) => panic!(
"there's no `{}` for this record; use `.get()` when there may be none",
std::any::type_name::<M>()
),
State::NotLoaded | State::Counted(_) => not_loaded::<M>(),
}
}
}
impl<M> HasMany<M> {
pub fn loaded(records: Vec<M>) -> Self {
Self(State::Loaded(records))
}
pub fn is_loaded(&self) -> bool {
matches!(self.0, State::Loaded(_))
}
pub fn get(&self) -> Option<&[M]> {
match &self.0 {
State::Loaded(records) => Some(records),
State::NotLoaded | State::Counted(_) => None,
}
}
pub fn counted(count: usize) -> Self {
Self(State::Counted(count))
}
pub fn count(&self) -> usize {
match &self.0 {
State::Loaded(records) => records.len(),
State::Counted(count) => *count,
State::NotLoaded => panic!(
"association to `{}` was neither counted nor preloaded; add \
`.with_count(..)` or `.preload(..)` to the query that loaded this record",
std::any::type_name::<M>()
),
}
}
}
impl<M> Deref for HasMany<M> {
type Target = [M];
fn deref(&self) -> &[M] {
self.get().unwrap_or_else(|| not_loaded::<M>())
}
}
impl<M> DerefMut for HasMany<M> {
fn deref_mut(&mut self) -> &mut [M] {
match &mut self.0 {
State::Loaded(records) => records,
State::NotLoaded | State::Counted(_) => not_loaded::<M>(),
}
}
}
impl<'a, M> IntoIterator for &'a HasMany<M> {
type Item = &'a M;
type IntoIter = std::slice::Iter<'a, M>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
macro_rules! assoc_impls {
($($ty:ident),*) => {$(
impl<M> Default for $ty<M> {
fn default() -> Self {
Self(State::NotLoaded)
}
}
impl<M: Clone> Clone for $ty<M> {
fn clone(&self) -> Self {
Self(match &self.0 {
State::NotLoaded => State::NotLoaded,
State::Loaded(v) => State::Loaded(v.clone()),
State::Counted(n) => State::Counted(*n),
})
}
}
impl<M: fmt::Debug> fmt::Debug for $ty<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 {
State::NotLoaded => f.write_str("NotLoaded"),
State::Loaded(v) => v.fmt(f),
State::Counted(n) => write!(f, "Counted({n})"),
}
}
}
impl<M: Serialize> Serialize for $ty<M> {
fn serialize<S: Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
match &self.0 {
State::NotLoaded | State::Counted(_) => s.serialize_none(),
State::Loaded(v) => v.serialize(s),
}
}
}
)*};
}
assoc_impls!(BelongsTo, HasMany, HasOne);
type PreloadFuture<'a> = Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
type LoadAll<M> = dyn for<'a> Fn(&'a mut [M], Connection) -> PreloadFuture<'a> + Send + Sync;
type LoadFn<M, C> = for<'a> fn(&'a mut [M], Connection, Loading<C>) -> PreloadFuture<'a>;
type CountFn<M> = for<'a> fn(&'a mut [M], Connection) -> PreloadFuture<'a>;
pub struct Preload<M> {
load: Arc<LoadAll<M>>,
}
impl<M> Clone for Preload<M> {
fn clone(&self) -> Self {
Self {
load: Arc::clone(&self.load),
}
}
}
impl<M> Preload<M> {
pub(crate) fn run<'a>(&self, records: &'a mut [M], conn: Connection) -> PreloadFuture<'a> {
(self.load)(records, conn)
}
}
pub struct Association<M, C> {
load: LoadFn<M, C>,
count: Option<CountFn<M>>,
pub(crate) through: Option<(&'static str, &'static str, &'static str)>,
pub(crate) join: Option<(&'static str, &'static str)>,
pub(crate) kind: Option<(&'static str, &'static str)>,
}
impl<M, C> Clone for Association<M, C> {
fn clone(&self) -> Self {
*self
}
}
impl<M, C> Copy for Association<M, C> {}
impl<M, C> Association<M, C> {
#[doc(hidden)]
pub const fn new(load: LoadFn<M, C>) -> Self {
Self {
load,
count: None,
through: None,
join: None,
kind: None,
}
}
#[doc(hidden)]
pub const fn of_kind(mut self, column: &'static str, name: &'static str) -> Self {
self.kind = Some((column, name));
self
}
#[doc(hidden)]
pub const fn through_table(
mut self,
table: &'static str,
owner_key: &'static str,
target_key: &'static str,
) -> Self {
self.through = Some((table, owner_key, target_key));
self
}
#[doc(hidden)]
pub const fn counted_by(mut self, count: CountFn<M>) -> Self {
self.count = Some(count);
self
}
pub(crate) fn counting(self) -> Option<Preload<M>>
where
M: 'static,
{
let count = self.count?;
Some(Preload {
load: Arc::new(move |records, conn| count(records, conn)),
})
}
#[doc(hidden)]
pub const fn joined_on(mut self, own: &'static str, other: &'static str) -> Self {
self.join = Some((own, other));
self
}
pub fn with<P: Into<Preload<C>>>(
self,
association: impl FnOnce(&C::Columns) -> P,
) -> Nested<M, C>
where
C: Model,
{
Nested {
load: self.load,
loading: Loading::default(),
}
.with(association)
}
pub fn only(self, query: Query<C>) -> Nested<M, C> {
Nested {
load: self.load,
loading: Loading::default(),
}
.only(query)
}
}
#[doc(hidden)]
pub struct Loading<C> {
nested: Vec<Preload<C>>,
query: Option<Query<C>>,
}
impl<C> Default for Loading<C> {
fn default() -> Self {
Self {
nested: Vec::new(),
query: None,
}
}
}
impl<C> Clone for Loading<C> {
fn clone(&self) -> Self {
Self {
nested: self.nested.clone(),
query: self.query.clone(),
}
}
}
impl<C: Model> Loading<C> {
fn query(&self) -> Result<Query<C>> {
match &self.query {
Some(query) => query.clone().for_association(),
None => Ok(Query::new().via_association()),
}
}
fn is_ordered(&self) -> bool {
self.query.as_ref().is_some_and(Query::is_ordered)
}
}
pub struct Nested<M, C> {
load: LoadFn<M, C>,
loading: Loading<C>,
}
impl<M, C> Nested<M, C> {
pub fn only(mut self, query: Query<C>) -> Self {
self.loading.query = Some(query);
self
}
pub fn with<P: Into<Preload<C>>>(mut self, association: impl FnOnce(&C::Columns) -> P) -> Self
where
C: Model,
{
self.loading.nested.push(association(&C::columns()).into());
self
}
}
impl<M: 'static, C: 'static> From<Association<M, C>> for Preload<M> {
fn from(association: Association<M, C>) -> Self {
Nested {
load: association.load,
loading: Loading::default(),
}
.into()
}
}
impl<M: 'static, C: 'static> From<Nested<M, C>> for Preload<M> {
fn from(nested: Nested<M, C>) -> Self {
let Nested { load, loading } = nested;
let loading = Arc::new(loading);
Preload {
load: Arc::new(move |records, conn| load(records, conn, (*loading).clone())),
}
}
}
async fn run_nested<C>(records: &mut [C], conn: &Connection, nested: &[Preload<C>]) -> Result<()> {
for preload in nested {
preload.run(records, conn.clone()).await?;
}
Ok(())
}
fn key(value: &Value) -> Option<String> {
match value {
Value::Null => None,
other => Some(format!("{other:?}")),
}
}
pub type LoadedTargets<T> =
std::pin::Pin<Box<dyn std::future::Future<Output = Result<Vec<(String, T)>>> + Send>>;
pub trait PolymorphicTarget: Sized + Clone + Send + 'static {
fn load(type_name: String, ids: Vec<Value>, conn: Connection) -> LoadedTargets<Self>;
}
#[doc(hidden)]
pub async fn load_polymorphic<P, C>(
parents: &mut [P],
conn: Connection,
target: impl Fn(&P) -> (Value, Value),
assign: impl Fn(&mut P, Option<C>),
) -> Result<()>
where
P: Model,
C: PolymorphicTarget,
{
let mut wanted: Vec<(String, Vec<Value>)> = Vec::new();
for parent in parents.iter() {
let (kind, id) = target(parent);
let (Some(kind), Some(_)) = (type_name(&kind), key(&id)) else {
continue;
};
match wanted.iter_mut().find(|(k, _)| *k == kind) {
Some((_, ids)) if !ids.contains(&id) => ids.push(id),
Some(_) => {}
None => wanted.push((kind, vec![id])),
}
}
let mut found: HashMap<(String, String), C> = HashMap::new();
for (kind, ids) in wanted {
for (id, record) in C::load(kind.clone(), ids, conn.clone()).await? {
found.insert((kind.clone(), id), record);
}
}
for parent in parents.iter_mut() {
let (kind, id) = target(parent);
let record = type_name(&kind)
.zip(key(&id))
.and_then(|k| found.get(&k).cloned());
assign(parent, record);
}
Ok(())
}
fn type_name(value: &Value) -> Option<String> {
match value {
Value::Text(name) if !name.is_empty() => Some(name.clone()),
_ => None,
}
}
#[doc(hidden)]
pub async fn load_by_ids<C: Model>(ids: Vec<Value>, conn: Connection) -> Result<Vec<(String, C)>> {
let records = Query::<C>::new()
.via_association()
.filter(|_| Expr::In {
column: C::PRIMARY_KEY,
values: ids,
})
.on(conn)
.all()
.await?;
Ok(records
.into_iter()
.filter_map(|record| Some((key(&record.id_value())?, record)))
.collect())
}
#[doc(hidden)]
pub async fn load_belongs_to<P, C>(
parents: &mut [P],
conn: Connection,
loading: Loading<C>,
foreign_key: impl Fn(&P) -> Value,
assign: impl Fn(&mut P, Option<C>),
) -> Result<()>
where
P: Model,
C: Model + Clone,
{
let mut ids: Vec<Value> = Vec::new();
for parent in parents.iter() {
let id = foreign_key(parent);
if key(&id).is_some() && !ids.contains(&id) {
ids.push(id);
}
}
let found: HashMap<String, C> = if ids.is_empty() {
HashMap::new()
} else {
let mut records = loading
.query()?
.filter(|_| Expr::In {
column: C::PRIMARY_KEY,
values: ids,
})
.on(conn.clone())
.all()
.await?;
run_nested(&mut records, &conn, &loading.nested).await?;
records
.into_iter()
.filter_map(|c| Some((key(&c.id_value())?, c)))
.collect()
};
for parent in parents.iter_mut() {
let record = key(&foreign_key(parent)).and_then(|k| found.get(&k).cloned());
assign(parent, record);
}
Ok(())
}
#[doc(hidden)]
#[allow(clippy::too_many_arguments)]
pub async fn load_has_many<P, C>(
parents: &mut [P],
conn: Connection,
loading: Loading<C>,
foreign_key_column: &'static str,
order: Option<(&'static str, bool)>,
kind: Option<(&'static str, &'static str)>,
foreign_key: impl Fn(&C) -> Value,
assign: impl Fn(&mut P, Vec<C>),
) -> Result<()>
where
P: Model,
C: Model,
{
let ids: Vec<Value> = parents.iter().map(Model::id_value).collect();
let mut grouped: HashMap<String, Vec<C>> = HashMap::new();
if !ids.is_empty() {
let mut query = loading.query()?.filter(|_| Expr::In {
column: foreign_key_column,
values: ids,
});
if let Some(kind) = kind {
query = query.filter(|_| of_kind(kind));
}
if let Some((column, descending)) = order {
query = query.order(|_| super::query::Order::by(column, descending));
}
let mut children = query
.order(|_| super::query::Order::by(C::PRIMARY_KEY, false))
.on(conn.clone())
.all()
.await?;
run_nested(&mut children, &conn, &loading.nested).await?;
for child in children {
if let Some(k) = key(&foreign_key(&child)) {
grouped.entry(k).or_default().push(child);
}
}
}
for parent in parents.iter_mut() {
let children = key(&parent.id_value())
.and_then(|k| grouped.remove(&k))
.unwrap_or_default();
assign(parent, children);
}
Ok(())
}
pub(crate) fn of_kind((column, name): (&'static str, &'static str)) -> Expr {
Expr::Compare {
column,
op: "=",
value: Value::Text(name.to_owned()),
}
}
#[doc(hidden)]
pub async fn count_has_many<P, C>(
parents: &mut [P],
conn: Connection,
foreign_key_column: &'static str,
kind: Option<(&'static str, &'static str)>,
assign: impl Fn(&mut P, usize),
) -> Result<()>
where
P: Model,
C: Model,
{
let ids: Vec<Value> = parents.iter().map(Model::id_value).collect();
let counts: HashMap<String, i64> = if ids.is_empty() {
HashMap::new()
} else {
let mut query = Query::<C>::new().via_association().filter(|_| Expr::In {
column: foreign_key_column,
values: ids,
});
if let Some(kind) = kind {
query = query.filter(|_| of_kind(kind));
}
query
.on(conn)
.count_by(foreign_key_column)
.await?
.into_iter()
.collect()
};
for parent in parents.iter_mut() {
let count = counts
.get(&parent.id_value().to_text())
.copied()
.unwrap_or(0);
assign(parent, usize::try_from(count).unwrap_or(0));
}
Ok(())
}
#[doc(hidden)]
#[allow(clippy::too_many_arguments)]
pub async fn load_has_many_through<P, C>(
parents: &mut [P],
conn: Connection,
loading: Loading<C>,
join_table: &'static str,
owner_key: &'static str,
target_key: &'static str,
order: Option<(&'static str, bool)>,
assign: impl Fn(&mut P, Vec<C>),
) -> Result<()>
where
P: Model,
C: Model + Clone,
{
let ids: Vec<Value> = parents
.iter()
.map(Model::id_value)
.filter(|id| key(id).is_some())
.collect();
let ordered = loading.is_ordered();
let mut targets: HashMap<String, Vec<String>> = HashMap::new();
let mut found: HashMap<String, C> = HashMap::new();
let mut rank: HashMap<String, usize> = HashMap::new();
if !ids.is_empty() {
let mut sql = super::Sql::new();
sql.push(&format!(
"SELECT CAST({owner_key} AS BIGINT) AS owner, CAST({target_key} AS BIGINT) AS target \
FROM {join_table} WHERE {owner_key}"
));
sql.push_in(ids);
let rows = conn.read_all(&sql).await?;
let mut target_ids: Vec<Value> = Vec::new();
for row in rows.iter() {
let (Some(owner), Some(target)) = (
row.get::<Option<i64>>("owner")?,
row.get::<Option<i64>>("target")?,
) else {
continue;
};
let target = Value::Int(target);
if !target_ids.contains(&target) {
target_ids.push(target.clone());
}
targets
.entry(key(&Value::Int(owner)).unwrap_or_default())
.or_default()
.extend(key(&target));
}
if !target_ids.is_empty() {
let mut query = loading.query()?.filter(|_| Expr::In {
column: C::PRIMARY_KEY,
values: target_ids,
});
if let Some((column, descending)) = order {
query = query.order(|_| super::query::Order::by(column, descending));
}
let mut children = query.on(conn.clone()).all().await?;
run_nested(&mut children, &conn, &loading.nested).await?;
for (i, child) in children.into_iter().enumerate() {
if let Some(k) = key(&child.id_value()) {
rank.insert(k.clone(), i);
found.insert(k, child);
}
}
}
}
for parent in parents.iter_mut() {
let mut keys: Vec<&String> = key(&parent.id_value())
.and_then(|k| targets.get(&k))
.into_iter()
.flatten()
.collect();
if order.is_some() || ordered {
keys.sort_by_key(|k| rank.get(*k).copied().unwrap_or(usize::MAX));
}
let children: Vec<C> = keys
.into_iter()
.filter_map(|k| found.get(k).cloned())
.collect();
assign(parent, children);
}
Ok(())
}
#[doc(hidden)]
#[allow(clippy::too_many_arguments)]
pub async fn load_has_many_via<P, Mid, C>(
parents: &mut [P],
conn: Connection,
loading: Loading<C>,
owner_key: &'static str,
source_key: &'static str,
child_key: &'static str,
order: Option<(&'static str, bool)>,
assign: impl Fn(&mut P, Vec<C>),
) -> Result<()>
where
P: Model,
Mid: Model,
C: Model + Clone,
{
if Mid::COLUMNS.contains(&source_key) {
return load_has_many_through(
parents,
conn,
loading,
Mid::TABLE,
owner_key,
source_key,
order,
assign,
)
.await;
}
let ids: Vec<Value> = parents
.iter()
.map(Model::id_value)
.filter(|id| key(id).is_some())
.collect();
let mut owner_of: HashMap<String, String> = HashMap::new();
let mut grouped: HashMap<String, Vec<C>> = HashMap::new();
if !ids.is_empty() {
let mut sql = super::Sql::new();
sql.push(&format!(
"SELECT CAST({} AS BIGINT) AS middle, CAST({owner_key} AS BIGINT) AS owner FROM {} \
WHERE {owner_key}",
Mid::PRIMARY_KEY,
Mid::TABLE
));
sql.push_in(ids);
let mut middle_ids: Vec<Value> = Vec::new();
for row in conn.read_all(&sql).await?.iter() {
let (Some(middle), Some(owner)) = (
row.get::<Option<i64>>("middle")?,
row.get::<Option<i64>>("owner")?,
) else {
continue;
};
let middle = Value::Int(middle);
if let (Some(m), Some(o)) = (key(&middle), key(&Value::Int(owner))) {
owner_of.insert(m, o);
}
middle_ids.push(middle);
}
if !middle_ids.is_empty() {
let mut query = loading.query()?.filter(|_| Expr::In {
column: child_key,
values: middle_ids,
});
if let Some((column, descending)) = order {
query = query.order(|_| super::query::Order::by(column, descending));
}
let mut children = query
.order(|_| super::query::Order::by(C::PRIMARY_KEY, false))
.on(conn.clone())
.all()
.await?;
run_nested(&mut children, &conn, &loading.nested).await?;
for child in children {
let middle = child
.values()
.into_iter()
.find(|(column, _)| *column == child_key)
.map(|(_, value)| value);
let owner = middle.as_ref().and_then(key).and_then(|m| owner_of.get(&m));
if let Some(owner) = owner {
grouped.entry(owner.clone()).or_default().push(child);
}
}
}
}
for parent in parents.iter_mut() {
let children = key(&parent.id_value())
.and_then(|k| grouped.remove(&k))
.unwrap_or_default();
assign(parent, children);
}
Ok(())
}
#[doc(hidden)]
pub async fn set_through_ids(
owner: Value,
join_table: &'static str,
owner_key: &'static str,
target_key: &'static str,
ids: Vec<i64>,
) -> Result<()> {
write_through_ids(
owner,
join_table,
owner_key,
target_key,
ids,
Links::Exactly,
)
.await
}
#[derive(Clone, Copy, PartialEq)]
#[doc(hidden)]
pub enum Links {
Add,
Remove,
Exactly,
}
pub(crate) async fn write_through_ids(
owner: Value,
join_table: &'static str,
owner_key: &'static str,
target_key: &'static str,
ids: Vec<i64>,
links: Links,
) -> Result<()> {
let conn = super::current()?;
let mut sql = super::Sql::new();
sql.push(&format!(
"SELECT CAST({target_key} AS BIGINT) AS target FROM {join_table} WHERE {owner_key} = "
));
sql.push_value(owner.clone());
let mut existing = Vec::new();
for row in conn.fetch_all(&sql).await? {
if let Some(id) = row.get::<Option<i64>>("target")? {
existing.push(id);
}
}
let gone: Vec<Value> = match links {
Links::Add => Vec::new(),
Links::Remove => existing
.iter()
.filter(|id| ids.contains(id))
.map(|id| Value::Int(*id))
.collect(),
Links::Exactly => existing
.iter()
.filter(|id| !ids.contains(id))
.map(|id| Value::Int(*id))
.collect(),
};
if !gone.is_empty() {
let mut sql = super::Sql::new();
sql.push(&format!("DELETE FROM {join_table} WHERE {owner_key} = "));
sql.push_value(owner.clone());
sql.push(&format!(" AND {target_key}"));
sql.push_in(gone);
conn.execute(&sql).await?;
}
let mut added = Vec::new();
for id in ids {
if links == Links::Remove || existing.contains(&id) || added.contains(&id) {
continue;
}
let mut sql = super::Sql::new();
sql.push(&format!(
"INSERT INTO {join_table} ({owner_key}, {target_key}) VALUES ("
));
sql.push_value(owner.clone());
sql.push(", ");
sql.push_value(Value::Int(id));
sql.push(")");
conn.execute(&sql).await?;
added.push(id);
}
Ok(())
}
#[doc(hidden)]
pub fn value_of<T: ToValue>(value: &T) -> Value {
value.to_value()
}
#[doc(hidden)]
pub async fn touch_parent<P: crate::model::Model>(id: Value) -> Result<()> {
let Some(column) = P::UPDATED_AT else {
return Ok(());
};
if id.is_null() {
return Ok(());
}
let mut sql = crate::db::Sql::new();
sql.push("UPDATE ")
.push_ident(P::TABLE)
.push(" SET ")
.push_ident(column)
.push(" = ");
sql.push_value(Value::Timestamp(crate::time::now()));
sql.push(" WHERE ").push_ident(P::PRIMARY_KEY).push(" = ");
sql.push_value(id);
crate::db::current_in(P::DATABASE)?.execute(&sql).await?;
Ok(())
}
const NESTED_INVALID: &str = "glacier: a nested record is invalid";
#[doc(hidden)]
pub fn nested_invalid() -> crate::Error {
crate::Error::unprocessable(NESTED_INVALID)
}
#[doc(hidden)]
pub fn is_nested_invalid(err: &crate::Error) -> bool {
err.message() == NESTED_INVALID
}
#[doc(hidden)]
pub async fn save_nested_child<C>(
parent_id: Value,
foreign_key: &'static str,
entry: &crate::Params,
allow_destroy: bool,
) -> Result<Vec<String>>
where
C: crate::model::Model + Default + Clone,
{
let id = entry.get("id").map(str::trim).filter(|id| !id.is_empty());
let Some(id) = id else {
let mut params = entry.clone().without("_destroy");
params.insert(foreign_key, parent_id.to_text());
let mut child = C::default();
return Ok(if child.update(params).await? {
Vec::new()
} else {
child.messages()
});
};
let id = id.parse::<i64>().map_err(|_| crate::Error::not_found())?;
let child = Query::<C>::new()
.via_association()
.filter(|_| Expr::Compare {
column: C::PRIMARY_KEY,
op: "=",
value: Value::Int(id),
})
.filter(|_| Expr::Compare {
column: foreign_key,
op: "=",
value: parent_id,
})
.first()
.await?;
let Some(mut child) = child else {
return Err(crate::Error::not_found());
};
let destroy = entry
.get("_destroy")
.is_some_and(|d| matches!(d.trim(), "1" | "true" | "on" | "yes"));
if destroy && allow_destroy {
child.destroy().await?;
return Ok(Vec::new());
}
let params = entry
.clone()
.without("id")
.without("_destroy")
.without(foreign_key);
Ok(if child.update(params).await? {
Vec::new()
} else {
child.messages()
})
}