use std::borrow::Cow;
use crate::error::{OrmError, Result};
use crate::ir::{Boolean, ColumnRef, InValues, Where, WhereClause};
use crate::model::Model;
use crate::query::Builder;
use crate::record::Record;
use crate::value::Value;
pub(crate) struct RelationCore<P: Model, R: Model> {
pub(crate) name: Cow<'static, str>,
pub(crate) parent: Option<P>,
pub(crate) query: Builder<R>,
}
impl<P: Model, R: Model> RelationCore<P, R> {
pub(crate) fn new(parent: Option<P>, name: Cow<'static, str>) -> Self {
RelationCore {
name,
parent,
query: Builder::new().with_relation_defaults(),
}
}
pub(crate) fn parent(&self) -> Result<&P> {
self.parent.as_ref().ok_or_else(|| {
OrmError::invalid(format!(
"the relation `{}` of {} was not made from a record: call the relation method on one (`record.{}()`)",
self.name,
P::meta().name(),
self.name
))
})
}
pub(crate) fn unbound(&self) -> Self {
RelationCore {
name: self.name.clone(),
parent: None,
query: self.query.clone(),
}
}
}
impl<P: Model, R: Model> Clone for RelationCore<P, R> {
fn clone(&self) -> Self {
RelationCore {
name: self.name.clone(),
parent: self.parent.clone(),
query: self.query.clone(),
}
}
}
pub(crate) fn column_value<M: Model>(model: &M, column: &str, relation: &str) -> Result<Value> {
model.value(column)?.ok_or_else(|| {
OrmError::invalid(format!(
"the relation `{relation}` uses column `{column}`, which {} does not have",
M::meta().name()
))
})
}
pub(crate) fn column_values<M: Model>(
records: &[Record<M>],
column: &str,
relation: &str,
) -> Result<Vec<Value>> {
records
.iter()
.map(|record| column_value(&record.model, column, relation))
.collect()
}
pub(crate) fn qualified(table: &str, column: &str) -> ColumnRef {
ColumnRef::new(Some(table.to_owned()), column.to_owned())
}
pub(crate) fn nothing<R: Model>() -> Where {
Where::In {
expr: crate::query::key_expr::<R>(),
values: InValues::List(Vec::new()),
not: false,
}
}
pub(crate) fn constrain<R: Model>(mut query: Builder<R>, constraints: Vec<Where>) -> Builder<R> {
let caller = std::mem::take(&mut query.ir.wheres);
query.ir.wheres = constraints.into_iter().map(WhereClause::and).collect();
if caller.iter().any(|clause| clause.boolean == Boolean::Or) {
query.ir.wheres.push(WhereClause::and(Where::Group(caller)));
} else {
query.ir.wheres.extend(caller);
}
query
}
pub(crate) fn new_with<R: Model + Default>(
attributes: &[crate::column::Assignment],
fill: impl FnOnce(&mut R),
) -> Result<Record<R>> {
let mut model = R::default();
for attribute in attributes {
match attribute.assigned_value() {
Some(value) => model.set_value(attribute.column(), value.clone())?,
None => {
return Err(OrmError::invalid(format!(
"the attribute `{}` of a {} to find or create must be a value",
attribute.column(),
R::meta().name()
)));
}
}
}
fill(&mut model);
Ok(Record::new(model))
}
pub(crate) fn matching<R: Model>(
query: Builder<R>,
attributes: &[crate::column::Assignment],
) -> Builder<R> {
let table = R::meta().table();
attributes.iter().fold(query, |query, attribute| {
query.where_(attribute.to_filter(Some(table)))
})
}
pub(crate) async fn save_atomically<R: Model>(
target: &crate::exec::Target<'_>,
record: &mut Record<R>,
) -> Result<bool> {
match target.begin_savepoint().await? {
Some(savepoint) => {
let nested = target.on_transaction(&savepoint);
let result = crate::persist::save(&nested, record).await;
drop(nested);
match result {
Ok(saved) => {
savepoint.commit().await?;
Ok(saved)
}
Err(error) => {
savepoint.rollback().await?;
Err(error)
}
}
}
None => crate::persist::save(target, record).await,
}
}
pub(crate) async fn restore_record<R: Model>(
target: &crate::exec::Target<'_>,
record: &mut Record<R>,
) -> Result<bool> {
use crate::hooks::{Flow, Hooks, ModelEvent};
let Some(deleted_at) = R::meta().deleted_at() else {
return Ok(false);
};
if !record.trashed() {
return Ok(false);
}
let ctx = target.context();
let hooks = Hooks::<R>::resolve(&ctx).await?;
if hooks.before(ModelEvent::Restoring, &ctx, record).await? == Flow::Cancel {
return Ok(false);
}
record.model.clear_timestamp(deleted_at);
if !crate::persist::save(target, record).await? {
return Ok(false);
}
hooks.after(ModelEvent::Restored, &ctx, record).await?;
Ok(true)
}
pub(crate) fn distribute<T: Clone>(
mut values: std::collections::HashMap<crate::relations::keys::RelationKey, T>,
parents: &[Option<crate::relations::keys::RelationKey>],
) -> Vec<Option<T>> {
let mut remaining: std::collections::HashMap<&crate::relations::keys::RelationKey, usize> =
std::collections::HashMap::new();
for key in parents.iter().flatten() {
*remaining.entry(key).or_default() += 1;
}
parents
.iter()
.map(|key| {
let key = key.as_ref()?;
let left = remaining.get_mut(key)?;
*left -= 1;
if *left == 0 {
values.remove(key)
} else {
values.get(key).cloned()
}
})
.collect()
}
pub(crate) struct Bound<R: Model> {
pub(crate) query: Builder<R>,
pub(crate) empty: bool,
pub(crate) finish: Option<Finisher<R>>,
}
pub(crate) type Finisher<R> = Box<dyn Fn(&mut [Record<R>]) -> Result<()> + Send + Sync>;
impl<R: Model> Bound<R> {
pub(crate) fn new(query: Builder<R>) -> Self {
Bound {
query,
empty: false,
finish: None,
}
}
pub(crate) fn nothing(query: Builder<R>) -> Self {
let query = constrain(query, vec![nothing::<R>()]);
Bound {
query,
empty: true,
finish: None,
}
}
pub(crate) fn finishing(mut self, finish: Option<Finisher<R>>) -> Self {
self.finish = finish;
self
}
pub(crate) fn finish(&self, records: &mut [Record<R>]) -> Result<()> {
match &self.finish {
Some(finish) => finish(records),
None => Ok(()),
}
}
}
macro_rules! relation_query_methods {
() => {
$crate::query::filters::filters!();
$crate::query::clauses::clauses!();
pub fn where_key(mut self, key: impl Into<R::Key>) -> Self {
self.core.query = self.core.query.where_key(key);
self
}
pub fn where_key_not(mut self, key: impl Into<R::Key>) -> Self {
self.core.query = self.core.query.where_key_not(key);
self
}
pub fn where_key_in(mut self, keys: impl IntoIterator<Item = impl Into<R::Key>>) -> Self {
self.core.query = self.core.query.where_key_in(keys);
self
}
pub fn where_key_not_in(
mut self,
keys: impl IntoIterator<Item = impl Into<R::Key>>,
) -> Self {
self.core.query = self.core.query.where_key_not_in(keys);
self
}
pub fn scope(
mut self,
scope: impl FnOnce($crate::Builder<R>) -> $crate::Builder<R>,
) -> Self {
self.core.query = self.core.query.scope(scope);
self
}
pub fn without_global_scope<S: $crate::GlobalScope<R>>(mut self) -> Self {
self.core.query = self.core.query.without_global_scope::<S>();
self
}
pub fn without_global_scopes(mut self) -> Self {
self.core.query = self.core.query.without_global_scopes();
self
}
pub fn with_trashed(mut self) -> Self {
self.core.query = self.core.query.with_trashed();
self
}
pub fn latest(mut self) -> Self {
self.core.query = self.core.query.latest();
self
}
pub fn oldest(mut self) -> Self {
self.core.query = self.core.query.oldest();
self
}
pub fn with(mut self, path: impl $crate::relations::RelationPath<R>) -> Self {
self.core.query = self.core.query.with(path);
self
}
pub fn with_all(
mut self,
paths: impl IntoIterator<Item = impl $crate::relations::RelationPath<R>>,
) -> Self {
self.core.query = self.core.query.with_all(paths);
self
}
pub fn with_constrained<Q: 'static>(
mut self,
path: impl $crate::relations::ConstrainPath<R, Q>,
constraint: impl Fn(Q) -> Q + Send + Sync + 'static,
) -> Self {
self.core.query = self.core.query.with_constrained(path, constraint);
self
}
pub fn without(mut self, path: impl $crate::relations::RelationPath<R>) -> Self {
self.core.query = self.core.query.without(path);
self
}
pub fn with_only(
mut self,
paths: impl IntoIterator<Item = impl $crate::relations::RelationPath<R>>,
) -> Self {
self.core.query = self.core.query.with_only(paths);
self
}
pub fn without_eager_loads(mut self) -> Self {
self.core.query = self.core.query.without_eager_loads();
self
}
pub fn with_count(mut self, path: impl $crate::relations::RelationPath<R>) -> Self {
self.core.query = self.core.query.with_count(path);
self
}
pub fn has(mut self, path: impl $crate::relations::RelationPath<R>) -> Self {
self.core.query = self.core.query.has(path);
self
}
pub fn doesnt_have(mut self, path: impl $crate::relations::RelationPath<R>) -> Self {
self.core.query = self.core.query.doesnt_have(path);
self
}
pub fn where_has<T: $crate::Model>(
mut self,
path: impl $crate::relations::RelationPathTo<R, T>,
constraint: impl FnOnce($crate::Builder<T>) -> $crate::Builder<T>,
) -> Self {
self.core.query = self.core.query.where_has(path, constraint);
self
}
pub fn where_doesnt_have<T: $crate::Model>(
mut self,
path: impl $crate::relations::RelationPathTo<R, T>,
constraint: impl FnOnce($crate::Builder<T>) -> $crate::Builder<T>,
) -> Self {
self.core.query = self.core.query.where_doesnt_have(path, constraint);
self
}
pub fn where_relation(
mut self,
path: impl $crate::relations::RelationPath<R>,
filter: impl Into<$crate::Filter>,
) -> Self {
self.core.query = self.core.query.where_relation(path, filter);
self
}
pub fn relation_name(&self) -> &str {
&self.core.name
}
pub fn related_table(&self) -> &'static str {
<R as $crate::Model>::meta().table()
}
pub fn named(mut self, name: impl Into<std::borrow::Cow<'static, str>>) -> Self {
self.core.name = name.into();
self
}
};
}
pub(crate) use relation_query_methods;
macro_rules! relation_retrieval_methods {
() => {
pub async fn get<E: $crate::Executor + ?Sized>(
self,
exec: &E,
) -> $crate::Result<$crate::Collection<R>> {
let bound = self.bound()?;
if bound.empty {
return Ok($crate::Collection::new());
}
let target = exec.target($crate::Access::Read).await?;
let query = bound.query.clone();
let mut records = query.fetch(&target).await?;
bound.finish(&mut records)?;
Ok(records)
}
pub async fn first<E: $crate::Executor + ?Sized>(
self,
exec: &E,
) -> $crate::Result<Option<$crate::Record<R>>> {
Ok(self.limit(1).get(exec).await?.into_vec().into_iter().next())
}
pub async fn first_or_fail<E: $crate::Executor + ?Sized>(
self,
exec: &E,
) -> $crate::Result<$crate::Record<R>> {
self.first(exec).await?.ok_or_else(|| {
$crate::OrmError::not_found(<R as $crate::Model>::meta().name(), Vec::new())
})
}
pub async fn first_where<E: $crate::Executor + ?Sized>(
self,
exec: &E,
filter: impl Into<$crate::Filter>,
) -> $crate::Result<Option<$crate::Record<R>>> {
self.where_(filter).first(exec).await
}
pub async fn sole<E: $crate::Executor + ?Sized>(
self,
exec: &E,
) -> $crate::Result<$crate::Record<R>> {
self.limit(2).get(exec).await?.sole()
}
pub async fn find<E: $crate::Executor + ?Sized>(
self,
exec: &E,
key: impl Into<R::Key>,
) -> $crate::Result<Option<$crate::Record<R>>> {
self.where_key(key).first(exec).await
}
pub async fn find_many<E: $crate::Executor + ?Sized>(
self,
exec: &E,
keys: impl IntoIterator<Item = impl Into<R::Key>>,
) -> $crate::Result<$crate::Collection<R>> {
let keys: Vec<R::Key> = keys.into_iter().map(Into::into).collect();
if keys.is_empty() {
return Ok($crate::Collection::new());
}
self.where_key_in(keys).get(exec).await
}
pub async fn find_or_fail<E: $crate::Executor + ?Sized>(
self,
exec: &E,
key: impl Into<R::Key>,
) -> $crate::Result<$crate::Record<R>> {
let key: R::Key = key.into();
let text = $crate::PrimaryKey::to_key_string(&key);
self.find(exec, key).await?.ok_or_else(|| {
$crate::OrmError::not_found(<R as $crate::Model>::meta().name(), vec![text])
})
}
pub async fn find_sole<E: $crate::Executor + ?Sized>(
self,
exec: &E,
key: impl Into<R::Key>,
) -> $crate::Result<$crate::Record<R>> {
self.where_key(key).sole(exec).await
}
pub async fn exists<E: $crate::Executor + ?Sized>(self, exec: &E) -> $crate::Result<bool> {
let bound = self.bound()?;
if bound.empty {
return Ok(false);
}
bound.query.exists(exec).await
}
pub async fn doesnt_exist<E: $crate::Executor + ?Sized>(
self,
exec: &E,
) -> $crate::Result<bool> {
Ok(!self.exists(exec).await?)
}
pub async fn count<E: $crate::Executor + ?Sized>(self, exec: &E) -> $crate::Result<u64> {
let bound = self.bound()?;
if bound.empty {
return Ok(0);
}
bound.query.count(exec).await
}
pub async fn sum<T: $crate::Field + Default>(
self,
exec: &(impl $crate::Executor + ?Sized),
column: impl $crate::IntoExpr,
) -> $crate::Result<T> {
let bound = self.bound()?;
if bound.empty {
return Ok(T::default());
}
bound.query.sum(exec, column).await
}
pub async fn avg<T: $crate::Field>(
self,
exec: &(impl $crate::Executor + ?Sized),
column: impl $crate::IntoExpr,
) -> $crate::Result<Option<T>> {
let bound = self.bound()?;
if bound.empty {
return Ok(None);
}
bound.query.avg(exec, column).await
}
pub async fn min<T: $crate::Field>(
self,
exec: &(impl $crate::Executor + ?Sized),
column: impl $crate::IntoExpr,
) -> $crate::Result<Option<T>> {
let bound = self.bound()?;
if bound.empty {
return Ok(None);
}
bound.query.min(exec, column).await
}
pub async fn max<T: $crate::Field>(
self,
exec: &(impl $crate::Executor + ?Sized),
column: impl $crate::IntoExpr,
) -> $crate::Result<Option<T>> {
let bound = self.bound()?;
if bound.empty {
return Ok(None);
}
bound.query.max(exec, column).await
}
pub async fn value<E, C>(self, exec: &E, column: C) -> $crate::Result<Option<C::Output>>
where
E: $crate::Executor + ?Sized,
C: $crate::Selectable,
{
let bound = self.bound()?;
if bound.empty {
return Ok(None);
}
bound.query.value(exec, column).await
}
pub async fn pluck<E, C>(self, exec: &E, column: C) -> $crate::Result<Vec<C::Output>>
where
E: $crate::Executor + ?Sized,
C: $crate::Selectable,
{
let bound = self.bound()?;
if bound.empty {
return Ok(Vec::new());
}
bound.query.pluck(exec, column).await
}
pub async fn paginate<E: $crate::Executor + ?Sized>(
self,
exec: &E,
page: impl Into<$crate::PageRequest>,
) -> $crate::Result<$crate::Page<$crate::Record<R>>> {
let bound = self.bound()?;
let mut page = bound.query.clone().paginate(exec, page).await?;
bound.finish(&mut page.data)?;
Ok(page)
}
pub async fn simple_paginate<E: $crate::Executor + ?Sized>(
self,
exec: &E,
page: impl Into<$crate::PageRequest>,
) -> $crate::Result<$crate::SimplePage<$crate::Record<R>>> {
let bound = self.bound()?;
let mut page = bound.query.clone().simple_paginate(exec, page).await?;
bound.finish(&mut page.data)?;
Ok(page)
}
pub async fn cursor_paginate<E: $crate::Executor + ?Sized>(
self,
exec: &E,
request: impl Into<$crate::CursorRequest>,
) -> $crate::Result<$crate::CursorPage<$crate::Record<R>>> {
let bound = self.bound()?;
let mut page = bound.query.clone().cursor_paginate(exec, request).await?;
bound.finish(&mut page.data)?;
Ok(page)
}
pub async fn update<E: $crate::Executor + ?Sized>(
self,
exec: &E,
assignments: impl IntoIterator<Item = $crate::Assignment>,
) -> $crate::Result<u64> {
let bound = self.bound()?;
if bound.empty {
return Ok(0);
}
bound.query.update(exec, assignments).await
}
pub async fn delete<E: $crate::Executor + ?Sized>(self, exec: &E) -> $crate::Result<u64> {
let bound = self.bound()?;
if bound.empty {
return Ok(0);
}
bound.query.delete(exec).await
}
pub async fn increment<E, T>(
self,
exec: &E,
column: $crate::Column<R, T>,
amount: T,
) -> $crate::Result<u64>
where
E: $crate::Executor + ?Sized,
T: $crate::Numeric,
{
let bound = self.bound()?;
if bound.empty {
return Ok(0);
}
bound.query.increment(exec, column, amount).await
}
pub async fn decrement<E, T>(
self,
exec: &E,
column: $crate::Column<R, T>,
amount: T,
) -> $crate::Result<u64>
where
E: $crate::Executor + ?Sized,
T: $crate::Numeric,
{
let bound = self.bound()?;
if bound.empty {
return Ok(0);
}
bound.query.decrement(exec, column, amount).await
}
pub fn into_query(self) -> $crate::Result<$crate::Builder<R>> {
Ok(self.bound()?.query)
}
pub fn to_sql(&self, dialect: $crate::Dialect) -> $crate::Result<$crate::Statement> {
self.clone().bound()?.query.to_sql(dialect)
}
};
}
pub(crate) use relation_retrieval_methods;
macro_rules! relation_builder_traits {
($relation:ident) => {
impl<P: $crate::Model, R: $crate::Model> $crate::query::filters::HasWheres
for $relation<P, R>
{
fn wheres_mut(&mut self) -> &mut Vec<$crate::ir::WhereClause> {
&mut self.core.query.ir.wheres
}
}
impl<P: $crate::Model, R: $crate::Model> $crate::query::clauses::HasQuery
for $relation<P, R>
{
fn query_mut(&mut self) -> &mut $crate::ir::QueryIr {
&mut self.core.query.ir
}
fn default_select(&self) -> Vec<$crate::ir::SelectItem> {
$crate::query::model_columns::<R>(self.core.query.ir.table.qualifier())
}
}
impl<P: $crate::Model, R: $crate::Model> $crate::Scoped<R> for $relation<P, R> {
fn apply_scope(
mut self,
scope: impl FnOnce($crate::Builder<R>) -> $crate::Builder<R>,
) -> Self {
self.core.query = self.core.query.scope(scope);
self
}
}
};
}
pub(crate) use relation_builder_traits;